Django表单数据未保存到数据库

时间:2019-08-29 06:37:09

标签: django django-forms

我正在尝试允许用户使用城市,描述,网站地址等更新其用户资料。

使用Django 2.0,我在一个视图中有两种形式:

EditProfileForm(EPF)=电子邮件,名字和姓氏和密码的表单

EditProfileForm似乎可以保存数据。但是,EditUserProfile似乎没有。

EditUserProfile(EUP)=用于进一步的用户信息的表格,例如城市,描述,网站地址等。

在输入数据并提交表单时,EUP表单的数据似乎无法保存或更新用户信息

我也尝试过以下方法:

if form_EUP.is_valid():
    obj = form_EUP.save(commit=False)
    obj.user = request.user
    obj.save()

并尝试创建与RegistrationForm中使用的格式类似的自定义保存方法,但我没有运气

我是django框架的初学者,所以任何想法都会受到赞赏,欢呼。

views.py

def edit_profile(request):
    if request.method == 'POST':
        form_EPF = EditProfileForm(request.POST, instance=request.user)
        form_EUP = EditUserProfile(request.POST, instance=request.user)

        if form_EPF.is_valid():
            form_EPF.save()
            return redirect(reverse('accounts:view_profile'))

        if form_EUP.is_valid():
            form_EUP.save()
            return redirect(reverse('accounts:view_profile'))

    else:
        form_EPF = EditProfileForm(instance=request.user)
        form_EUP = EditUserProfile(instance=request.user)

        args = {'form_EPF': form_EPF, "form_EUP": form_EUP}
        return render(request, 'accounts/edit_profile.html', args)

forms.py


class RegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = (
            'username', 
            'first_name',
            'last_name',
            'email',
            'password1',
            'password2'
            )

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.email = self.cleaned_data['email']

        if commit:
            user.save()

        return user

class EditProfileForm(UserChangeForm):

    class Meta:
        model = User
        fields = (
            'email',
            'first_name',
            'last_name',
            'password',
            )

class EditUserProfile(ModelForm):
    description = forms.CharField(required=False)
    city = forms.CharField(required=False)
    website = forms.URLField(required=False)

    class Meta:
        model = UserProfile
        fields = (
            'description',
            'city',
            'website',
            'image',
            )

models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    description = models.CharField(max_length=100, default='')
    city = models.CharField(max_length=100, default='')
    website = models.URLField(default='')
    phone = models.IntegerField(default=0)
    image = models.ImageField(upload_to='profile_image', blank=True)

    def __str__(self):
        return self.user.username

def create_profile(sender, **kwargs):
    if kwargs['created']:
        user_profile = UserProfile.objects.create(user=kwargs['instance'])

post_save.connect(create_profile, sender=User)

edit_profile.html

{% block body %}
<div class="container">
    <h1>Edit profile</h1>
    <form method="post">
        {% csrf_token %}
        {{ form_EPF.as_p }}
        {{ form_EUP.as_p }}
        <button type="submit">Submit</button>
    </form>
</div>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

这里:

    if form_EPF.is_valid():
        form_EPF.save()
        return redirect(reverse('accounts:view_profile')) # !!!!!

    if form_EUP.is_valid():
        form_EUP.save()
        return redirect(reverse('accounts:view_profile'))

您将在保存用户表单后立即返回,因此配置文件表单的确不会保存(除非用户表单是无效的xD)。

您要

    if form_EPF.is_valid() and form_EUP.is_valid():
        form_EPF.save()
        form_EUP.save()
        return redirect(reverse('accounts:view_profile')) # !!!!!

此外,您无法使用此功能:

form_EUP = EditUserProfile(request.POST, instance=request.user)

您正在传递̀User as实例, but the form expects a UserProfile`。

而且-虽然它不会阻止您的代码运行-但您绝对想对命名三思。 “ EditProfileForm”会编辑用户,因此应将其真正命名为“ EditUserForm”(或“ UserEditForm”等),并且视图中的变量也不会更好-̀form_EPF and form_EUP requires active thinking to parse the suffix and match it with the (already counter-intuitive) form class names, and you _don't_ want to have to do any effort to understand what a name means when reading code. Just use the all_lower form of the class instead, so assumin you renamed your form classes to a much saner UserEditForm {{ 1}} ProfileEditForm and user_edit_form , the variables would be profile_edit_form`。这确实是几次额外的击键,但是平均而言,您花费的时间比编写代码多花费1000倍,因此值得为读取进行优化。