gpt4 book ai didi

python - 提交表单时出现 Django IntegrityError (在 View 中预填充)

转载 作者:太空宇宙 更新时间:2023-11-03 14:57:22 25 4
gpt4 key购买 nike

我无法为我的问题找到可靠的答案。我正在尝试在 View 中预先填充表单。因此,当用户使用表单时,一些数据已经被处理了。我想做的是自动获取用户用户名和他的组并将其输入数据库。但是当我尝试这样做时,我得到 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 %}

我得到的错误是:异常类型:完整性错误异常值:
NOT NULL 约束失败:myapp_myapp.organization_id

感谢您提供的任何帮助

最佳答案

您实际上并未将值分配给您的订阅列

   if form.is_valid():
subscription = form.save(commit=False)

subscription.organization = request.user.groups.first()
subscription.input_user = self.request.user
subscription.stuff = form.cleaned_data['stuff']
subscription.description = form.cleaned_data['description']

subscription.save()

关于python - 提交表单时出现 Django IntegrityError (在 View 中预填充),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45419512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com