Home > Net >  form.is_valid() always returns false perhaps issue with "This field is required" error
form.is_valid() always returns false perhaps issue with "This field is required" error

Time:04-16

I am learning django. I am stuck with this problem.

The problem is that form.is_valid() always returns false.

I tried to debug and I think that the problem is because of "This field is required" error and I think that the field is file_name. I tried to resolve the issue but I am unable to do so.

Just to give a context of what I am trying to do -

I have created a form in which a user uploads a text file and selects a gender.

In the backend I want to save the name of the text file along with the gender in a model. The purpose of doing this is because when multiple users will use the application, I should know which user selected what gender so that I can produce the desired output.

Here is the link to my git repository -
git repository

As I already said I am new to django and some help will be appreciated.

CodePudding user response:

I think you are not saving the form. In your views line 24 you have

if request.method == 'POST':
        form = TranscriptForm(request.POST)
        return HttpResponse(str(form.errors))

If you are posting you will always return there,therefore there is no check for is_valid().

Same as line 60:

context = {'form': TranscriptForm()}
    return render(request, 'tutorial/upload.html', context)

you havent accessed/saved the form yet for it to be valid

CodePudding user response:

Your fields in form are fields = ['file_name','gender'] and in the template you have

<label for="myfile"> <b> Select a file: </b> </label> <br/>
<input type="file" name="document"> <br/><br/>
<br/><br/>
{{ form.gender }}

... fields document and gender, no file_name. Add {{ form.file_name }} to the template or, if you want to stick to manually writing code for input, file input with a name file_name. Input names need to match field names in form.

Also, read this: Working with forms.

CodePudding user response:

As a separate piece of advice outside the question, you've posted your settings including secret keys to a public repository. Later on with production keys this may pose an issue if you commit them to version history (especially publicly). https://github.com/AnshulGupta22/auto_generation/blob/main/auto_generation/settings.py

  • Related