Reputation: 219
I have a form where users get edit their personal information/settings and I'm trying to get it to pre-populate if they have entered that information in the past. I looked here:
Django prepopulate form with the fields from the database
for help, but still can't get the form to prepopulate. Thanks in advance.
#model
class UserProfile(models.Model):
user = models.OneToOneField(User)
activation_key = models.CharField(max_length=40, blank=True)
first_name = models.CharField(max_length=50, blank=True)
last_name = models.CharField(max_length=50, blank=True)
phone_number = PhoneNumberField(blank=True, null=True)
address_line_1 = models.CharField(max_length=300, blank=True)
address_line_2 = models.CharField(max_length=300, blank=True)
address_line_3 = models.CharField(max_length=300, blank=True)
city = models.CharField(max_length=150, blank=True)
postalcode = models.CharField(max_length=10, blank=True)
paypal_email = models.EmailField(max_length=75, blank=True)
photo = models.ImageField(upload_to="images/", blank=True)
def __unicode__(self):
return self.user.username
def save(self, *args, **kwargs):
try:
existing = UserProfile.objects.get(user=self.user)
self.id = existing.id #force update instead of insert
except UserProfile.DoesNotExist:
pass
models.Model.save(self, *args, **kwargs)
#form
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
exclude = ('user', 'activation_key',)
# view
def update_settings(request):
if request.method== 'POST':
try:
u = UserProfile.objects.get(user=request.user)
form = UserProfileForm(request.POST, instance=u)
except ObjectDoesNotExist:
form = UserProfileForm(request.POST, request.FILES)
if form.is_valid:
profile = form.save(commit=False)
profile.user = request.user
profile.save()
return HttpResponseRedirect('registration/activation_complete.html')
else:
try:
u = UserProfile.objects.get(user=request.user)
form = UserProfileForm(request.POST, instance=u)
except ObjectDoesNotExist:
form = UserProfileForm(request.POST, request.FILES)
return render_to_response('registration/update_settings.html', locals(), context_instance=RequestContext(request))
Upvotes: 2
Views: 3875
Reputation: 53326
You can update your view code like this:
def update_settings(request):
if request.method== 'POST':
try:
u = UserProfile.objects.get(user=request.user)
form = UserProfileForm(request.POST, instance=u)
except ObjectDoesNotExist:
form = UserProfileForm(request.POST, request.FILES)
if form.is_valid(): #is_valid is function not property
profile = form.save(commit=False)
profile.user = request.user
profile.save()
return HttpResponseRedirect('registration/activation_complete.html')
else:
try:
u = UserProfile.objects.get(user=request.user)
form = UserProfileForm(instance=u) #No request.POST
except ObjectDoesNotExist:
form = UserProfileForm(request.FILES)
# move it outside of else
return render_to_response('registration/update_settings.html', locals(),
context_instance=RequestContext(request))
Upvotes: 4