1

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

感谢您提供的任何帮助

4

2 回答 2

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()
于 2017-07-31T15:15:20.367 回答
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在您的字段选项中,因为它不是您模型中的字段(至少不是您发布的字段)。

于 2017-07-31T15:18:46.423 回答