我正在尝试使用fbv更新模型的字段,并且我也为这些字段创建了不同的表单。但无论如何,我无法提交表格。我认为问题出在图像字段,并且表单无法呈现为有效。有什么办法吗?
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True)
role = models.CharField(max_length=50, choices=Roles)
verified =models.BooleanField(default = False,blank=True)
photo = models.ImageField(upload_to='images', blank=True, default='default/testimonial2.jpg')
slug = models.SlugField(unique=False, blank=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.user.username)
super(UserProfile, self).save(*args, **kwargs)
def __str__(self):
return self.user.username
def get_absolute_url(self):
if (self.verified==True):
return reverse("NewApp:mail", kwargs={'pk': self.pk})
else:
return reverse("NewApp:userlist")
views.py
def UserUpdateView(request,slug):
object = User.objects.get(username=request.user)
user_form = UserUpdateForm(instance=object)
obj = UserProfile.objects.get(slug=request.user)
profile_form = UserProfileForm(instance=obj)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
return redirect('NewApp:logindex')
return render(request, 'NewApp/userprofile_form.html',
{'user_form': user_form,
'profile_form': profile_form,})
forms.py
class UserUpdateForm(forms.ModelForm):
class Meta():
model = User
fields = ('first_name','last_name','email')
class UserProfileForm(forms.ModelForm):
class Meta():
model = UserProfile
fields = ('photo',)
答案 0 :(得分:0)
在POST请求的情况下,请勿使用request.POST
和request.FILES
构造表单。您应该这样实现:
def UserUpdateView(request,slug):
user = request.user
profile = UserProfile.objects.get(user=user)
if request.method == 'POST':
user_form = UserUpdateForm(request.POST, request.FILES, instance=user)
profile_form = UserProfileForm(request.POST, request.FILES, instance=profile)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
return redirect('NewApp:logindex')
else:
user_form = UserUpdateForm(instance=user)
profile_form = UserProfileForm(instance=profile)
return render(
request,
'NewApp/userprofile_form.html',
{'user_form': user_form, 'profile_form': profile_form,}
)