在Django中更新表单

时间:2018-11-04 16:22:31

标签: python django django-models django-forms

我有2个模型:User和Profile,为此我创建了2个表单类。

表格

class UserProfileForm(ModelForm):   
    class Meta:
        model = Profile
        fields = ['dob','country']

class UserForm(ModelForm):
     class Meta:
        model = User
        fields = ['username','first_name','last_name','email','password']

我的个人资料模型

class Profile(models.Model):
      user = models.ForeignKey(User,on_delete = models.CASCADE)
      country = CountryField()
      dob = models.DateField(max_length=10)
      profile_pic = models.ImageField(upload_to='profile_image',blank=True) 

如何保存这些表格?

forms.save()似乎没有帮助。

查看

def profile(request):
    print(request.user)
    form1 = UserForm()
    form2  = UserProfileForm()
    if request.method == 'POST':
        if form1.is_valid() and form2.is_valid():
            form1.save()
            form2.save()
    return render(request,'account/profile.html',{'form1':form1, 'form2':form2})

2 个答案:

答案 0 :(得分:0)

您需要将数据传递到表单中,以便进行验证,并在成功验证后保存模型。现在,form1.is_valid()form2.is_valid()始终返回False,并且您没有处理这种情况,因此页面仅被重新呈现。

def profile(request):
    print(request.user)
    form1 = forms.UserForm()
    form2 = forms.UserProfileForm()
    if request.method == 'POST':
        form1 = forms.UserForm(request.POST, request.FILES)
        form = forms.UserProfileForm(request.POST, request.FILES)
        if form1.is_valid() and form2.is_valid():
            form1.save()
            form2.save()
        else:
            return Http404 
    return render(request,'account/profile.html',{'form1':form1, 'form2':form2})

答案 1 :(得分:0)

尝试此操作,因为您没有将任何数据保存到数据库中

from .models import Profile
from django.contrib.auth.models import User

def profile(request):
    print(request.user)

    if request.method == 'POST':
        form1 = UserForm(request.POST)
        form2  = UserProfileForm(request.POST)

        if form1.is_valid() and form2.is_valid():
            profile = Profile()
            user = User.objects.get(username=request.user)

            user.username = form1.cleaned_data['username']
            user.first_name = form1.cleaned_data['first_name']
            user.last_name = form1.cleaned_data['last_name']
            user.email = form1.cleaned_data['email']
            user.set_password(form1.cleaned_data['password'])
            user.save()

            profile.user = request.user # user field cannot be empty
            profile.dob = form2.cleaned_data['dob']
            profile.country = form2.cleaned_data['country']
            profile.save()
    else:
        form1 = UserForm()
        form2  = UserProfileForm() 

    context = {
       'form1' : form1,
       'form2' : form2
      }

    return render(request,'account/profile.html', context = context)

这是正确的做法,并检查其是否为GET返回空表格。但是我不确定您是否可以同时保存配置文件和用户,因为您在配置文件中有外键,并且不能为空。您需要具有预定义的用户。