简体   繁体   English

Django 2 request.POST未使用instance = request.user保存到数据库

[英]Django 2 request.POST not saving to database with instance=request.user

I have a form where a user can submit some text, which then gets saved to the model TextSubmission . 我有一个表单,用户可以提交一些文本,然后将其保存到模型TextSubmission

However, it only saves when I take out instance=request.user from views.py and it does not save with the instance of the user who submitted it. 但是,仅当我从views.py取出instance=request.user时才保存,并且不与提交它的用户实例一起保存。

If I leave instance=request.user in, the request.POST object does not get saved but does get posted. 如果我将instance=request.user留在,则request.POST对象不会被保存,但会被发布。 (I can see from print(request.POST) (我可以从print(request.POST)看到

Can someone help me figure out why this is and how to get the text to save along with the user? 有人可以帮我弄清楚为什么会这样,以及如何使文本与用户一起保存吗?

models.py 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 forms.py

class TextSubmissionForm(forms.ModelForm):

    class Meta:
        model = TextSubmission
        fields = ['text_submission']

views.py 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 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>

You're passing the TextSubmission form an instance of User, when you want to be passing it an instance of TextSubmission. 您要从User的实例传递TextSubmission,而要向其传递TextSubmission的实例。 Try 尝试

try:
    t_form = TextSubmissionForm(request.POST, instance=request.user.textsubmission)
except TextSubmission.DoesNotExist:
    t_form = TextSubmissionForm(request.POST)

Override the __init__() method and save() method of the form as 将表单的__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']

Then, in your views, 然后,在您看来

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)

Reference 参考

  1. Passing a user, request to forms 传递用户,请求表格

The instance require the instance of the referenced model in form definition. 该实例需要表单定义中引用模型的实例。 In your case it is TextSubmission , so you have first get object of this model and then pass it to the TextSubmissionForm 在您的情况下是TextSubmission ,因此您首先要获得此模型的对象,然后将其传递给TextSubmissionForm

user = User.objects.get(id = request.user)
txtSubmsn = TextSubmission.objects.get(user)
u_form = TextSubmissionForm(instance=txtSubmsn)

Same case for UserUpdateForm UserUpdateForm情况相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM