Skip to content Skip to sidebar Skip to footer

How To Prepopulate An Django Update Form And Write It Back To The Database

I'm new at Python & Django and currently struggling right now. I created an update/edit form with Django Model forms, but it just doesn't prepopulate the form fields and post i

Solution 1:

According to https://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values, you can use the initial attribute when instantiating forms in order to prepropulate your forms.

defupdate_advert(request, id):
    ifnot request.user.is_authenticated():
        return render(request, 'forum/login.html')
    else:
        advert_obj = get_object_or_404(Advert, pk=id)


        if request.method == 'POST':
            form = AdvertForm(request.POST orNone, request.FILES orNone, instance=advert_obj)
            if form.is_valid():
                form.save()
                return redirect('forum:user_account')
        else:
            # Prepopulation happens here:
            data = {"some_field": advert_obj.some_val} # Insert all the values of advert_obj here and their field names as keys.
            form = AdvertForm(initial=data) 


        context = {'form': form}
        return render(request, 'forum/update_advert.html', context)

In your AdvertForm, put this code:

classAdvertForm(forms.ModelForm):
    def__init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(AdvertForm, self).__init__(*args, **kwargs)

    defsave(self, commit=True):
        instance = super(AdvertForm, self).save(commit=False)
        instance.user = self.request.user

        if commit:
            instance.save()
        return instance

The overriding save method simply does what you were doing in the views to link up the request.user to the instance, however I have placed that code in the form class to keep your views simple.

Also, I can see one confusing (but not vital) issue - you have mixed up the variable names. When calling form = get_object_or_404(Advert, pk=id), this should return to a variable name such as advert or something similar. Not form as that can be confusing as we are returning a model object not a form. Similarly, form.save(commit=False) returns an "instance" not a model form. This won't solve your problem but should be pointed out for more clarification on what exactly is being returned and how you should then name your variables.

Post a Comment for "How To Prepopulate An Django Update Form And Write It Back To The Database"