我不确定如何使用常规Django表单将登录用户绑定到提交的表单。我看到了很多使用ModelForms的示例,但不使用ModelForms就没有(我可以说)。在我的forms.py中,我很难弄清楚如何添加author字段。我不能只添加author = Forms.ForeignKey或类似的东西。然后在我看来,我需要调用author字段以保存到数据库中(我的以下示例是我的最佳猜测,可能与“ tenant_form.author = request.user”不匹配)。
我有一个看起来像这样的模型,并且具有用户外键设置:
class AppyModel(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
date_time_form_filled = models.DateTimeField(auto_now_add=True)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
我有一个form.py:
class TenantForm(forms.Form):
first_name = forms.CharField(required=False, label='First Name')
last_name = forms.CharField(required=False, label='Last Name')
我有一个views.py
@login_required
def tenant_create_form_view(request):
tenant_form = TenantForm()
if request.method == 'POST':
tenant_form.author = request.user
tenant_form = TenantForm(request.POST)
if tenant_form.is_valid():
print(tenant_form.cleaned_data)
AppyModel.objects.create(**tenant_form.cleaned_data)
else:
print(tenant_form.errors)
context = {
'form': tenant_form
}
return render(request, 'fill_appy.html', context)
答案 0 :(得分:0)
您应在表单有效时添加作者,
tenant_form = TenantForm()
if request.method == 'POST':
tenant_form = TenantForm(request.POST)
if tenant_form.is_valid():
obj = tenant_form.save(commit=False)
obj.author = request.user #add author here
obj.save()
# .. rest of code