提交表单时的Django IntegrityError(在视图中预先填充)

时间:2017-07-31 15:12:10

标签: python django forms mo

我无法为我的问题找到可靠的答案。我试图在视图中预先填充表单。因此,当用户使用表单时,一些数据已经被处理。我想要做的是自动获取用户名和他的组并将其提供给数据库。但是当我尝试这样做时,我得到了IntegrityError NOT NULL约束失败。

我是新手,我正在学习MDN网络文档。

我的views.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})

forms.py:

class AddNewForm(forms.ModelForm):
    def __init__(self, *args,**kwargs):
        super (AddNewView, self ).__init__(*args,**kwargs) 

    class Meta:
        model = Subscription
        fields = [
            'stuff',
            'description',
        ]

models.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

感谢您提供的任何帮助

2 个答案:

答案 0 :(得分:1)

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

   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()

答案 1 :(得分:0)

在您的表单中,

class AddNewForm(forms.ModelForm):

    class Meta:
        model = Subscription
        fields = [
            'description',
            ]

尝试像这样编辑你的视图,

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

        subscription.organization = request.user.groups.first()
        subscription.input_user = self.request.user.username

        subscription.save()

我不太明白为什么你在你的字段选项中包含了stuff,因为它不是你模型中的字段(至少不在你发布的字段中)。