Django - 这是字段必需的错误

时间:2018-05-16 10:56:03

标签: django django-forms django-views

我是Django的新手并尝试将一些数据从表单保存到模型中。我想插入两个具有外键约束关系的模型(即Idea和IdeaUpvotes),即从html模板到视图。

我的提交代码是:

def submitNewIdea(request):
    #get the context from the request
    context = RequestContext(request)

    print(context)

    #A HTTP POST?
    if request.method == 'POST':
        form = submitNewIdeaForm(request.POST)


        # Have we been provided with a valid form?
        if form.is_valid():
            # Save the new Idea to the Idea model

            print(request.POST.get("IdeaCategory"))
            print(request.POST.get("IdeaSubCategory"))


            i = Idea(   idea_heading = form["idea_heading"].value()
                        ,idea_description = form["idea_description"].value()
                        ,idea_created_by = form["idea_created_by"].value()
                        ,idea_votes = form["idea_votes"].value()
                        ,idea_category = request.POST.get("IdeaCategory") #value from dropdown
                        ,idea_sub_category = request.POST.get("IdeaSubCategory")  #value from dropdown
                     )

            i.save()
            # get the just saved id

            print(Idea.objects.get(pk = i.id))

            iu = IdeaUpvotes(idea_id = Idea.objects.get(pk = i.id)
                            ,upvoted_by = form["upvoted_by"].value()
                            ,upvoted_date = timezone.now() )

            iu.save()
            form.save(commit = True)
            # Now call the index() view.
            # The user will be shown the homepage.
            return index(request)
        else:
            # The supplied form contained errors - just print them to the terminal.
            print (form.errors)
    else:
        # If the request was not a POST, display the form to enter details.
        form = submitNewIdeaForm()

    # Bad form (or form details), no form supplied...
    # Render the form with error messages (if any).
    return render(request,'Ideas/Index.html',{'form' :form})

form.py --->

class submitNewIdeaForm(forms.ModelForm):

idea_heading = forms.CharField(label = "idea_heading",max_length =1000,help_text= "Please enter the idea heading.")
idea_description= forms.CharField(label = "idea_description",max_length =1000,help_text= "Please enter the idea description.",widget=forms.Textarea)
idea_created_by=forms.CharField(max_length =200, widget = forms.HiddenInput(), initial='wattamw')
idea_votes = forms.IntegerField(widget=forms.HiddenInput(), initial=1)
upvoted_by=forms.CharField(max_length =200, widget = forms.HiddenInput(), initial='abcde')

"""
#commented code

#idea_category_name = forms.CharField(label = "idea_category_name",max_length =250,help_text= "Please select an Idea Category.")
#idea_sub_category = forms.CharField(label = "idea_sub_category",max_length =250,help_text= "Please select an Idea Sub Category.")

idea_category_name = forms.ModelChoiceField(
                    queryset = IdeaCategory.objects.all(),
                    widget=autocomplete.ModelSelect2(url='category-autocomplete'))


idea_sub_category = forms.ModelChoiceField(
                    queryset = IdeaSubCategory.objects.all(),
                    widget = autocomplete.ModelSelect2(
                        url='subcategory-autocomplete',
                        forward = (forward.Field('idea_category_name','id'),)))
"""


class Meta:
    model = Idea
    fields = ('idea_heading','idea_description','idea_created_by','idea_votes','idea_category_name','idea_sub_category')

class Meta:
    model = IdeaUpvotes
    fields = ('upvoted_by',)

def __init__(self,*args,**kwargs):
    super(submitNewIdeaForm,self).__init__(*args,**kwargs)
    self.fields['idea_category_name'] = forms.ModelChoiceField(
                                        queryset = IdeaCategory.objects.all(),
                                        widget=autocomplete.ModelSelect2(url='category-autocomplete'))
    self.fields['idea_sub_category'] = forms.ModelChoiceField(
                                    queryset = IdeaSubCategory.objects.all(),
                                    widget = autocomplete.ModelSelect2(
                                    url='subcategory-autocomplete',
                                    forward = (forward.Field('idea_category_name','id'),)))

我可以打印值并看到它们已通过,但我仍然收到以下错误:

Error Description

我删除了对表的任何外键引用,字段是简单的字符字段。

请帮帮我。

感谢。

1 个答案:

答案 0 :(得分:1)

首先,您的表单验证失败。在我看来,您的表单模板可能是错误的。

第二件事是您没有正确使用Django表单。要实现所需功能,您需要做的就是使用ModelForm并让表单的save方法为您创建对象。您所需要做的就是:

  1. 将您的SubmitNewIdeaFormIdea型号相关联:

        # forms.py
        class SubmitNewIdeaForm(ModelForm):
            class Meta:
            model = Idea
            fields = (
                'idea_heading',
                'idea_description',
                'idea_created_by',
                'idea_votes',
                'idea_category',
                'idea_sub_category'
            )
    
  2. 渲染表单

    #form_template.html
    <form action="{% url 'your_url' %}" method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="Submit" />
    </form>
    
  3. 最后jsut检查表单是否有效并像这样调用form.save()

    def submitNewIdea(request):
        if form.is_valid():
            form.save()
    
  4. 就是这样!我希望我能帮助你。

    干杯!