Django is_valid () form not working

I am a real newbie in web development. The following code does not work when checking is_valid() . But I don’t understand why: Should the form fill out its data from POST data or not?

Model:

 class Statement(models.Model): text = models.CharField(max_length=255) user = models.ForeignKey(User) time = models.DateField() views = models.IntegerField() 

ModelForm:

 class StatementForm(ModelForm): class Meta: model = Statement widgets = { 'time':forms.HiddenInput(), 'user':forms.HiddenInput(), 'views':forms.HiddenInput(), } 

View function:

 def new(request): if request.method == 'POST': # If the form has been submitted... form = StatementForm(request.POST) # A form bound to the POST data if form.is_valid(): stmt = form.save() path = 'stmt/' + stmt.id return render_to_response(path, {'stmt': stmt}) else: c = {} c.update(csrf(request)) loggedin_user = request.user d = datetime.now() form = StatementForm(request.POST, initial={'time': d.strftime("%Y-%m-%d %H:%M:%S"), 'user':loggedin_user, 'views':0}) return render_to_response('new_stmt.html', {'form': form, },context_instance=RequestContext(request)) 

I found similar topics and tried a lot. This is how I think it should work. I really need some advice.

+6
source share
2 answers

All fields of your model are required. Thus, form.is_valid() will be True if all fields are filled with the correct values ​​and will not be filled. You declared the fields time , user , views as hidden fields. Are you sure you filled them in your form? In addition, you can specify the automatic stamping field time = models.DateField() . Change the model field, for example

 time = models.DateField(auto_now=True)`. 

After that, you do not need to fill it yourself in the form of a template.

Your view should return an HttpResponse object in all cases . If your form is invalid, i.e. If form.is_valid() returns False, then the HttpResponse object will not be returned by your view. This may be the source of your failure. Add an else for if form.is_valid() :

 from django.http import Http404 def new(request): if request.method == 'POST': # If the form has been submitted... form = StatementForm(request.POST) # A form bound to the POST data if form.is_valid(): stmt = form.save() path = 'stmt/' + stmt.id return render_to_response(path, {'stmt': stmt}) else: # Do something in case if form is not valid raise Http404 else: # Your code without changes 
+6
source

Change this line:

  form = StatementForm(request.POST, initial={'time': d.strftime("%Y-%m-%d %H:%M:%S"), 'user':loggedin_user, 'views':0}) 

For this:

  form = StatementForm(initial={'time': d.strftime("%Y-%m-%d %H:%M:%S"), 'user':loggedin_user, 'views':0}) 
+2
source

Source: https://habr.com/ru/post/918284/


All Articles