我无法为我的问题找到可靠的答案。我正在尝试在视图中预先填充表单。所以当用户使用表单时,一些数据已经被处理了。我想要做的是自动获取用户名和他的组并将其输入数据库。但是当我尝试这样做时,我得到 IntegrityError NOT NULL 约束失败。
我是新手,我正在从 MDN 网络文档中学习。
我的意见.py:
class AddNewView(generic.View):
formClass = AddNewForm
template_name = 'myapp/subscription_form.html'
def get(self, request):
form = self.formClass(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.formClass(request.POST)
if form.is_valid():
subscription = form.save(commit=False)
organization = request.user.groups.values_list('id', flat=True).first()
input_user = self.request.user
stuff = form.cleaned_data['stuff']
description = form.cleaned_data['description']
subscription.save()
return render(request, self.template_name, {'form': form})
表格.py:
class AddNewForm(forms.ModelForm):
def __init__(self, *args,**kwargs):
super (AddNewView, self ).__init__(*args,**kwargs)
class Meta:
model = Subscription
fields = [
'stuff',
'description',
]
模型.py:
class Subscription(models.Model):
organization = models.ForeignKey(Group, help_text="which organization")
input_user = models.CharField(max_length=150)
input_date = models.DateTimeField(auto_now_add=True)
description = models.CharField(max_length=1000, null=True, blank=True, help_text='Description')
stuff = models.CharField(max_length=100)
html:
{% extends "base_generic.html" %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit" />
</form>
{% endblock %}
我得到的错误是:异常类型:IntegrityError 异常值:
NOT NULL 约束失败:myapp_myapp.organization_id
感谢您提供的任何帮助