user3464297
user3464297

Reputation: 1

Django - This is field is required error

I am new to Django and trying to save some data from the form to the model. I want to insert into two models which have a foreign key constraint relationship (namely Idea and IdeaUpvotes) i.e. from a html template to a view.

My submit code is:

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'),)))

I am able to print the values and see that they are passed,but I still get the following error :

Error Description

I have removed any foreign key references to the table, the fields are simple character fields.

Please help me out.

Thanks.

Upvotes: 0

Views: 3525

Answers (2)

AndriiFedotov
AndriiFedotov

Reputation: 1

 Finished = models.IntegerField('Finished percentage', error_messages={'required':''})

Worked for me.

Upvotes: 0

Kaloyan Stoykov
Kaloyan Stoykov

Reputation: 11

In the first place, your form validation is failing. It seems to me that your form template may be wrong.

The second thing is that you don't use Django forms properly. All you need to do to achieve the functionality you are looking for is to use ModelForm and let the form's save method to create the object for you. All you need to do is:

  1. Associate your SubmitNewIdeaForm with the Idea model:

        # 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. Render the form

    #form_template.html
    <form action="{% url 'your_url' %}" method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="Submit" />
    </form>
    
  3. Finally jsut check if the form is valid and call form.save() like so:

    def submitNewIdea(request):
        if form.is_valid():
            form.save()
    

That's it! I hope that I helped you.

Cheers!

Upvotes: 1

Related Questions