简体   繁体   中英

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?

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.

In my experience, assuming the default behavior as a GET request inside function-based views will avoid some mistakes and you will get rid off those if-else statements. If you are trying to edit an object you need to populate the form during GET request too:

def settings(request):
    site_profile = Site.objects.get(user=request.user)
    form = SiteForm(instance=site_profile) # GET method
    if request.method == "POST":
        # Don't forget the request.POST !
        form = SiteForm(request.POST, instance=site_profile)
        if form.is_valid():
            form.save()
            return redirect('dashboard_home')
    return render(request, "dashboard/settings.html", {'form': form })
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(instance = site_profile)

        return render(request, "dashboard/settings.html", {'form': form })
  1. the else block in line 12 has one indentation to much
  2. you must set the instance argument also in the else block

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM