在我看来,我有一个非常简单的模型设置、模型形式和一个将两者结合在一起的 View 。唯一的问题是该模型有一个用户属性不能发布到表单,而应该由 request.user
填充,所以我有这个:
# models.py
class Update(models.Model):
user = models.ForeignKey(User, related_name="updates")
organisation = models.ForeignKey(Organisation, related_name="updates")
publish = models.BooleanField(default=True)
class UpdateForm(ModelForm):
name = forms.CharField(
max_length=140,
required=False,
widget=forms.TextInput(attrs={"class": "blankable"})
)
class Meta(NodeForm.Meta):
model = Update
# views.py
def status(request):
from myproject.organisations.models import Organisation
from myproject.feeds.models import Update, UpdateForm
stream = 0
if request.method == "POST":
o = request.POST.get("organisation")
if not o or request.user not in Organisation.objects.get(pk=request.POST.get("organisation")).administrators.all():
return HttpResponseRedirect(reverse("ethico.core.views.index"))
f = UpdateForm(request.POST, instance=Update(user=request.user))
if f.is_valid():
stream = f.save()
else:
stream = f.errors
...
每当我运行它时,我总是得到同样的错误:
user: This field is required.
我已经尝试使用 {"user": 1}
设置 f
和 initial
属性,它仍然说它是必需的。我尝试通过将 request.POST
复制到一个新变量并在将其传递给 UpdateForm 之前修改它来传递修改后的 POST,但这很丑陋。我在这里忘记了什么?
最佳答案
您应该尝试排除表单中的用户字段
class UpdateForm(ModelForm):
name = forms.CharField(
max_length=140,
required=False,
widget=forms.TextInput(attrs={"class": "blankable"})
)
class Meta:
model = Update
exclude = ("user",)
http://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#s-using-a-subset-of-fields-on-the-form
关于python - 为什么Django的ModelForm验证会认为这个是无效的呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2315086/