Django表单错误-该选择不是可用选择之一

时间:2018-09-04 02:23:19

标签: python django

我正在尝试在用户之间创建自定义消息传递平台。由于某种原因,它表示我的表单在提交时无效,并且当我使用print(messageform.errors)打印错误时,我得到:

<ul class="errorlist"><li>receiver<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul>

这很奇怪,因为我不相信我在表格的任何地方都使用了下拉菜单。有谁知道为什么会这样?

forms.py

class MessageForm(forms.ModelForm):
    class Meta:
        model = Message
        fields = ['text', 'receiver']

html文件

<form action="" method="post">
    {% csrf_token %}
     <input type="text" name="text" value="" />
     <label for="text">Enter your message here</label><br/>

     <input type="text" name="receiver" value="" />
     <label for="receiver">id of receiver</label><br/>

     <input type="submit" value="Send" />
</form>

models.py

class Message(models.Model): 
    text = models.TextField(max_length=10000, blank=True)
    sender = models.ForeignKey(
                    settings.AUTH_USER_MODEL,
                    on_delete=models.CASCADE,
                    null = True, 
                    related_name="sender"
                    )
    receiver = models.ForeignKey(
                    settings.AUTH_USER_MODEL,
                    on_delete=models.CASCADE,
                    null = True, 
                    related_name="receiver"
                    )

views.py

usermodel = get_user_model()

if request.method == "POST" and not signupform.is_valid():
        messageform = MessageForm(request.POST)
        print(messageform.errors)
        if messageform.is_valid():
            receiverid = messageform.cleaned_data['receiver']
            newmessage = messageform.save(commit=False)
            newmessage.sender = request.user
            newmessage.receiver = usermodel.objects.filter(username=receiverid)
            newmessage.text = messageform.cleaned_data['text']
            new_profile.save()

        return HttpResponseRedirect('/profile/')

0 个答案:

没有答案