[英]Django ModelForm; User, this field is required
I am having some issues with a (model)form consisting of just a single button. 我在仅包含一个按钮的(模型)表单中遇到一些问题。 When I try to submit the form this message is displayed:
当我尝试提交表单时,将显示以下消息:
user This field is required.
用户此字段为必填项。
The ModelForm looks like this: ModelForm看起来像这样:
from django.forms import ModelForm
from .models import HulpOproep
class HulpOproepForm(ModelForm):
class Meta:
model = HulpOproep
fields = ['user', ]
The Model looks like this: 该模型如下所示:
class HulpOproep(models.Model):
user = models.ForeignKey(User)
time = models.DateTimeField(auto_now_add=True, verbose_name='Tijd')
def __str__(self):
return '%s %s' % (self.user.username, str(self.time))
def username(self):
return self.user.username
def first_name(self):
return self.user.first_name
def last_name(self):
return self.user.last_name
class Meta:
verbose_name = 'Hulp Oproep'
verbose_name_plural = 'Hulp Oproepen'
The View looks like this: 视图如下所示:
def verzend_oproep(request):
if request.method == 'POST':
form = HulpOproepForm(request.POST)
if form.is_valid():
oproep = form.save(commit=False)
oproep.user = request.user
oproep.save()
return redirect('portal/index/')
else:
form = HulpOproepForm()
return render(request, 'portal/verzend_oproep.html', {'form': form})
The Template: 模板:
{% extends "base.html" %}
{% block head %}
<title>Zorggroep | Hulp Oproep</title>
{% endblock %}
{% block body%}
<h1>Verstuur Hulpoproep</h1>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_P }}
{{ form.errors }}
<button type="submit" class="save btn btn-default">Verstuur</button>
</form>
{% endblock %}
The 'user' in the HulpOproep model is a ForeignKey and should be the currently logged in user's User object. HulpOproep模型中的“用户”是ForeignKey,应为当前登录用户的User对象。 I tried to specify this using the line:
我尝试使用以下行来指定:
oproep.user = request.user
So what should happen is: Get the current user's 'User' object and use it as the 'HulpOproepForm.user'. 因此,应该发生的事情是:获取当前用户的“用户”对象,并将其用作“ HulpOproepForm.user”。 This way the 'HulpOproepForm.user' is the 'HulpOproep.user' and a Foreign Key.
这样,“ HulpOproepForm.user”就是“ HulpOproep.user”和外键。
I have followed multiple tutorials and have searched around, but I cannot find a solution. 我遵循了多个教程并进行了搜索,但是找不到解决方案。 I'm sorry if the answer is logical, but I have been using Django for only 5 days and have 1.5 months of programming experience under my belt.
很抱歉,如果答案是合乎逻辑的,但是我仅使用Django已有5天,并且拥有1.5个月的编程经验。
Thank you! 谢谢!
Thanks PatNowak and Radek! 感谢PatNowak和Radek!
I did not know the form was waiting for user input instead of code input. 我不知道表单正在等待用户输入而不是代码输入。 I managed to fix it by adding exclude to the ModelForm.
我设法通过添加排除到ModelForm来解决它。
class HulpOproepForm(ModelForm):
class Meta:
model = HulpOproep
exclude = ['user', 'time']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.