python - 预填充表单数据 Django

标签 python django

我有一个表单,用户可以在其中编辑他们的个人信息/设置,如果他们过去输入过该信息,我会尝试将其预先填充。我看这里:

Django prepopulate form with the fields from the database

寻求帮助,但仍然无法预填充表单。提前致谢。

#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))

最佳答案

您可以像这样更新 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():  #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))

关于python - 预填充表单数据 Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12014462/

相关文章:

python - 为什么当我覆盖 base.html django-admin 时已禁用响应式界面?

python - 将多个参数发送到只定义一个的类

Python "push server"TCP 客户端

python - 从不同的 DataFrame 中减去值

django - 我们如何在 Django 中编写扩展多个父模板的子模板?

python - 我如何反射(reflection) Django 中的属性和模型字段?

python - ModelChoiceField 的 Django 表单查询集

python - 使用 sklearn 的 KFold 分离 Pandas 数据框

python - PyErr_SetString 的字符串参数 : is it borrowed?

Python:迭代具有不同维数的列表,有通用的方法吗?