django-autocomplete-light icon indicating copy to clipboard operation
django-autocomplete-light copied to clipboard

DAL with pre-populated forms using instance

Open sumitbindra opened this issue 4 years ago • 1 comments

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:

https://drive.google.com/file/d/13651JtB_1f7VJWgGsXeJSTm1l7B-xA-b/view?usp=sharing

Any thought on why the field is empty when the primary key field is not the same as display field? Thanks.

sumitbindra avatar May 05 '20 19:05 sumitbindra

I have looked at this in more detail and when there is an ID auto field in there instead of custom primary key, the forms errors out when you try to pre-populate it with data from an instance.

I think the issue is more general with pre-populating forms.

sumitbindra avatar May 09 '20 03:05 sumitbindra