Search code examples
djangoformsfielddefault

Django - Easiest way to set initial value for form fields to the current database value, for custom UserChangeForm?


Essentially I have a custom UserChangeForm that uses my user model 'Writer' and I want to set the default for all the fields as the current value from the database(or the value from the request user). What would be the best way to go about this?

I tried to set the defaults in the form however the request object isn't accessable in forms.py

the form...

class writerChangeForm(UserChangeForm):

    class Meta:
        model = Writer
        fields = ('username', 'email', 'first_name', 'last_name', 'country')
        country = CountryField().formfield()
        widgets = {'country': CountrySelectWidget()}

The view...

class ProfileView(generic.CreateView):
    form_class = writerChangeForm
    template_name = 'diary/profile.html'

Thanks for any input!


Solution

  • The best way will be to override get_initial() method.

    class ProfileView(generic.CreateView):
        form_class = writerChangeForm
        template_name = 'diary/profile.html'
    
        def get_initial(self):
            # get_initial should return dict. They should be rendered in template.
            writer = Writer.objects.get(pk=1) # first get data from database.
            # dictionary key names should be same as they are in forms.
            return {
                'username': writer.username,
                'email': writer.email,
                'first_name': writer.first_name
            }