Django Autocomplete Light … PK vs display field

亡梦爱人 提交于 2020-05-14 09:03:09

问题


I am using DAL to provide a selectable dropdown list like this:

class OccupationsModel(models.Model):
    Occupation_Code            = models.CharField(max_length = 20, primary_key=True)
    Occupation_Title           = models.CharField(max_length = 150, unique=True)
    Occupation_Desc            = models.CharField(max_length = 1000)

    class Meta:
        db_table = 'Occupation_Info'

    def __str__(self):
        return self.Occupation_Title

Note here that occupation_code is my PK while I am using str to show occupation_title as my display. Mostly everything works fine but then I use instance to prepopulate the form, the title is not displayed. The form field is empty. I have other similar models where the PK is the same as display and those work just fine. So I am pretty sure there is something I am missing here.

Here is my DAL view:

class OccCreateView(CreateView):
    model           = OccupationsModel
    template_name   = 'dashboard/input_page.html'
    form_class      = InputForm


class occautocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):

        qs = OccupationsModel.objects.all().order_by('Occupation_Code')     

        # Don't forget to filter out results depending on the visitor !
        if not self.request.user.is_authenticated:                    
            qs = qs[:3] 
            if self.q:
                qs = qs[:3]  

        if self.q:
            qs = qs.filter(Occupation_Title__icontains = self.q) 

        return qs

Here is my form:

    def miscuserinfo_view(request):  
        misc_user_info = MiscUserInfoModel.objects.get(user = request.user.id)
        if request.method == 'POST':      
            if form.is_valid():
                obj = form.save(commit=False)
                # do something here with the form      
                obj.save()
                return HttpResponseRedirect(reverse('registration:userprofile'))
        else:     # Pre-populate with existing data that user entered before
            form = MiscUserInfoForm(instance = misc_user_info)
        return render(request, "registration/miscinfo_page.html", {'form': form})

And here is what I see:

Any help is much appreciated. Thanks.

来源:https://stackoverflow.com/questions/61602875/django-autocomplete-light-pk-vs-display-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!