Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load an instance in Django ModelForms

I am using Django's user model.

How do I get a Django ModelForm to prepopulate values in a template? I know I have to use the instance for that form, but where am I going wrong below:

models.py:

class Site(models.Model):
   user = models.ForeignKey(User, )
   site_name = models.CharField(max_length=128, blank=False, null=False)

forms.py:

class SiteForm(forms.ModelForm):
      class Meta:
            model = Site
            fields = '__all__'

views.py:

def settings(request):

    site_profile = Site.objects.get(user=request.user)

    if request.method == "POST":
        form = SiteForm( instance=site_profile )
            if form.is_valid():
                form.save()

                return redirect('dashboard_home')

        else:
            form = SiteForm()

        return render(request, "dashboard/settings.html", {'form': form })

This code returns the page with no errors, however does not prepopulate the form fields with values from the database.

I can only assume the instance is not loading correctly?

like image 594
alias51 Avatar asked Dec 15 '22 13:12

alias51


1 Answers

def settings(request):
    if request.method == "POST":
        form = SiteForm(request.POST, instance=request.user.site_profile)
        if form.is_valid():
            form.save()
            return redirect('dashboard_home')
    site_profile = Site.objects.get(user=request.user)
    form = SiteForm(instance=site_profile)
    return render(request, "dashboard/settings.html", {'form': form })

Your indentation was off and you never passed the site_profile to the form to have it populated. In the event of a POST request you don't want to pass the old version of site_profile to the form. I assume you want the new values the user has filled out in the template.

like image 53
kylieCatt Avatar answered Jan 04 '23 17:01

kylieCatt