我有一个表单,用户可以在其中编辑他们的个人信息/设置,如果他们过去输入了该信息,我正试图让它预先填充。我看这里:
寻求帮助,但仍然无法让表单预填充。提前致谢。
#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))