如何将我的html表单发布到django模型并保存?

时间:2017-09-13 05:06:16

标签: python html django django-forms

我有html表单,我想发送并保存到django模型。当我尝试发送消息时,我收到错误:

ValueError at /account/userinfo/akylson/
"<Mail: hhh>" needs to have a value for field "id" before this many-to-many relationship can be used.
Request Method: POST
Request URL:    http://localhost:8000/account/userinfo/akylson/
Django Version: 1.11.3
Exception Type: ValueError
Exception Value:    
"<Mail: hhh>" needs to have a value for field "id" before this many-to-many relationship can be used.

您可以在下面看到我的代码。

以下是我的html表单: -

<form role="form" class="form-horizontal" method="post">
{% csrf_token %}
  <div class="form-group">
    <input type="checkbox" id="id_receiver" name="receiver" value="{{ user.username }}" checked hidden>
    <label class="col-lg-2 control-label">Тема</label>
    <div class="col-lg-10">
    <input type="text" placeholder="" id="id_subject" name="subject" value="{{ subject }}" class="form-control">
     </div>
  </div>
  <div class="form-group">
    <label class="col-lg-2 control-label">Сообщение</label>
    <div class="col-lg-10">
      <textarea rows="10" cols="30" class="form-control" id="id_message" name="message"></textarea>
    </div>
  </div>
  <div class="form-group">
    <div class="col-lg-offset-2 col-lg-10">
      <span class="btn green fileinput-button"><i class="fa fa-plus fa fa-white"></i>
      <span>Приложение</span><input type="file" name="files[]" multiple=""></span>
      <button class="btn btn-send" value="submit" type="submit">Send</button>
    </div>
  </div>
</form>

这是我的view.py

@login_required()
def userinfo(request, username):
    username = User.objects.get(username=username)
    args = {}
    args['user'] = username
    if request.method == 'POST':
        sender = request.user
        receiver = request.POST['receiver']
        subject = request.POST['subject']
        message = request.POST['message']
        b = Mail.objects.create(sender=sender, receiver=receiver, subject=subject, message=message)
        b.save()
    return render(request, 'account/userinfo.html', args)

这是我的models.py

class Mail(models.Model):
    sender = models.ForeignKey(User, related_name='mail_sender')
    receiver = models.ManyToManyField(User, related_name='mail_receiver')
    subject = models.CharField(max_length=200)
    message = RichTextUploadingField()
    date = models.DateTimeField(auto_now=True, null=False, blank=False)

    class Meta():
        ordering = ['-date']

    def __str__(self):
        return self.subject

这是我的forms.py

class NewMailForm(forms.ModelForm):
    class Meta:
        model = Mail

        fields = (
            'sender',
            'receiver',
            'subject',
            'message',
        )
        widgets = {'receiver': forms.CheckboxSelectMultiple()}

3 个答案:

答案 0 :(得分:0)

您必须将user个实例传递给views.py

如下所示更改views.py

views.py

@login_required()
def userinfo(request):
    user = request.user
    form = NewMailForm(request.POST or None)
    if request.method == 'POST':
        if not form.is_valid():
            print form.errors
            return render(request,'')
        else:
        sender = user
        receiver = form.cleaned_data.get("receiver")
        subject = form.cleaned_data.get("subject")
        message = form.cleaned_data.get("message")
        b = Mail.objects.create_user(
                sender=sender,
                receiver=receiver,
                subject=subject,
                message=message)
        b.save()
    return render(request, 'account/userinfo.html')

forms.py

<form action="." method="POST">{% csrf_token %}

{{ form.as_p }}

</form>

这将创建一个包含请求用户的新邮件对象。

答案 1 :(得分:0)

在views.py中创建模型的实例 例如m = Mail() 然后使用实例发布每个字段 m.receiver = request.POST.get('receiver') 然后保存 m.save()

答案 2 :(得分:0)

您犯了几个错误:

    如果您制作了HTML表单并链接到项目,则不需要
  1. forms.py

  2. 您尚未定义b。刚刚写成b.save

只需调试这些错误,您就完成了!