question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

DAL v3: ModelSelect2 with form initial does not respect get_result_label

See original GitHub issue

hello, I’m moving to DAL v3. I wonder if it is possible that the value set to form the initial, is shown as get_result_label

Sample code

views.py
from django.views import generic
from django.db.models import Q
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth.models import User
from dal import autocomplete

from .models import SampleModel
from .forms import SampleForm


class UserAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        # Don't forget to filter out results depending on the visitor !
        if not self.request.user.is_authenticated():
            return User.objects.none()

        qs = User.objects.all()

        if self.q:
            qs = qs.filter(Q(first_name__icontains=self.q) | Q(last_name__icontains=self.q))
        return qs

    def get_result_label(self, result):
        return result.get_full_name().title()


class SampleView(generic.UpdateView):
    form_class = SampleForm
    model = SampleModel

    def get_success_url(self):
        return reverse_lazy('sample_update', {'pk': self.object.pk})

    def get_initial(self):
        initial = super(SampleView, self).get_initial()
        user = getattr(self.request, 'user', None)
        if user and user.is_authenticated():
            initial.update({'selected_user': user})
        return initial
models.py
from django.db import models
from django.contrib.auth.models import User


class SampleModel(models.Model):
    selected_user = models.ForeignKey(to=User,
                                      related_name="%(app_label)s_%(class)s_selected_user", null=True,
                                      blank=True, on_delete=models.SET_NULL)

forms.py
from dal import autocomplete
from django import forms
from django.contrib.auth.models import User
from .models import SampleModel


class SampleForm(forms.ModelForm):
    selected_user = forms.ModelChoiceField(
        queryset=User.objects.all(),
        widget=autocomplete.ModelSelect2(url='user-autocomplete')
    )

    class Meta:
        models = SampleModel
        fields = '__all__'

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^sample-update/(?P<pk>\d+)/$',
        views.SampleView.as_view(),
        name='sample_update'
        ),
    url(r'^user-autocomplete/$',
        views.UserAutocomplete.as_view(),
        name='user-autocomplete'
        )
]

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Reactions:2
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
luzfcbcommented, Feb 26, 2016

RESOLVED!!

This is not a problem DAL v3.

it was necessary to create a new class that inherits from forms.ModelChoiceField and create a label_from_instance method which returns the value of the label that need.

look at the end of the ModelChoiceField documentation https://docs.djangoproject.com/es/1.9/ref/forms/fields/#modelchoicefield

this would be a good example to include in the documentation, because I believe it is a common use.

from dal import autocomplete
from django import forms
from django.contrib.auth.models import User
from .models import SampleModel


class UserModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.get_full_name().title()

class SampleForm(forms.ModelForm):
    selected_user = UserModelChoiceField(
        queryset=User.objects.all(),
        widget=autocomplete.ModelSelect2(url='user-autocomplete')
    )

    class Meta:
        models = SampleModel
        fields = '__all__'

@jpic thank you for the incredible work.

0reactions
Simanascommented, Mar 31, 2021

What is yl.getForwards(select)?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Django-Autocomplete-Light v3 widget doesn't work
This is not a DAL issue, but a Django issue. It can't reverse the url with name "brand_autocomplete", because it wasn't registered in...
Read more >
Tutorial - django-autocomplete-light 3.9.0rc1 documentation
Autocompletes are based on 3 moving parts: widget compatible with the model field, does the initial rendering,. javascript widget initialization code, to ...
Read more >
Django Tutorial Part 9: Working with forms - MDN Web Docs
To do this we'll create a form that allows users to enter a date value. We'll seed the field with an initial value...
Read more >
Creating forms from models - Django documentation
Each model field has a corresponding default form field. ... If you have excluded any model fields, validation will not be run on...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found