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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With