我有一个表单,用户可以提交一些文本,然后将其保存到模型TextSubmission
中。
但是,仅当我从instance=request.user
中取出views.py
时它才保存,并且不与提交它的用户实例一起保存。
如果我将instance=request.user
留在其中,request.POST
对象将不会保存,但会被发布。 (我可以从print(request.POST)
有人可以帮我弄清楚为什么会这样以及如何与用户一起保存文本吗?
models.py
class TextSubmission(models.Model):
text_submission = models.CharField(max_length=50, null=True, blank=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
class Meta:
ordering = ['text_submission']
def __str__(self):
return self.text_submission
forms.py
class TextSubmissionForm(forms.ModelForm):
class Meta:
model = TextSubmission
fields = ['text_submission']
views.py
def profile_view(request):
if request.method == 'POST':
p_form = ProfileUpdateForm(request.POST, instance=request.user)
t_form = TextSubmissionForm(request.POST, request.FILES, instance=request.user.profile)
if p_form.is_valid() and t_form.is_valid():
p_form.save()
t_form.save()
messages.success(request, f'Your account has been updated!')
return redirect('profile')
else:
p_form = ProfileUpdateForm(instance=request.user.profile)
t_form = TextSubmissionForm(instance=request.user.textsubmission)
context = {
'p_form': p_form,
't_form': t_form,
}
return render(request, 'profile.html', context)
profile.html
<form method="POST" enctype="multipart/form-data">
<div class="profile-form">
{{ p_form }}
{{ t_form }}
</div>
<button type="submit" value="submit">Update Profile</button>
</form>
答案 0 :(得分:1)
您要从User的实例传递TextSubmission,而要向其传递TextSubmission实例。试试
try:
t_form = TextSubmissionForm(request.POST, instance=request.user.textsubmission)
except TextSubmission.DoesNotExist:
t_form = TextSubmissionForm(request.POST)
答案 1 :(得分:1)
将表单的 __init__()
方法和 save()
方法覆盖为
class TextSubmissionForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super().__init__(*args, **kwargs)
def save(self, commit=True):
self.instance.user = self.user
return super().save(commit)
class Meta:
model = TextSubmission
fields = ['text_submission']
然后,在您看来,
def profile_view(request):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST) # change is here
t_form = TextSubmissionForm(request.POST, user=request.user) # change is here
if u_form.is_valid() and t_form.is_valid():
u_form.save()
t_form.save()
messages.success(request, f'Your account has been updated!')
return redirect('profile')
else:
u_form = UserUpdateForm() # change is here
t_form = TextSubmissionForm() # change is here
context = {
'u_form': u_form,
't_form': t_form,
}
return render(request, 'profile.html', context)
答案 2 :(得分:-1)
实例需要表单定义中引用模型的实例。在您的情况下为TextSubmission
,因此您首先要获得此模型的对象,然后将其传递给TextSubmissionForm
user = User.objects.get(id = request.user)
txtSubmsn = TextSubmission.objects.get(user)
u_form = TextSubmissionForm(instance=txtSubmsn)
与UserUpdateForm
相同的情况