我有什么看起来像是一个非常简单的模型设置,模型和使用这两者的视图。唯一的障碍是该模型具有无法POST到表单的用户属性,而应该由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.
我尝试使用f
使用initial
属性设置{"user": 1}
,但仍然说它是必需的。我已经尝试通过将request.POST
复制到一个新变量并在将其传递给UpdateForm之前修改它来传递修改后的POST但这很难看。我忘记了什么?
答案 0 :(得分:1)
您应该尝试排除
形式的用户字段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