There was a problem with adding ads from registered users: created a form (PostForm) with inheritance from the model (Post), created a view (create_post), a template. The problem is that after filling out the form fields and clicking the "Finish" button, the announcement is not saved in the database. I suspect that the publish () method that is present in the Post model is not involved. If the problem really is this - how and where to call it?

models.py

class Post(models.Model): action = models.CharField(max_length=7, choices=( ('Продам', 'Продам'), ('Куплю', 'Куплю'), ('Сдам', 'Сдам'), ('Сниму', 'Сниму'), ), default='Продам') name = models.CharField(max_length=36) author = models.ForeignKey('registration.ExtUser') author_id = ExtUser.id price = models.IntegerField(null=True, help_text='RUB') text = models.TextField() contact = models.IntegerField(null=True) category = models.ForeignKey(Category, null=True) published_date = models.DateField( blank=True, null=True, ) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.name 

forms.py

 class PostForm(ModelForm): class Meta: model = Post fields = ['action', 'name', 'price', 'text', 'contact', 'category'] 

views.py

 def create_post(request): if not request.user.is_authenticated(): return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) else: author_id = request.user.id if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): PostForm.published_date = timezone.now() form.save() return HttpResponseRedirect('myboard/home.html') else: form = PostForm() 

urls.py

 url(r'^new_post/$', views.create_post, name='new_post'), 

new_post.html

 <form action="/" method="post"> {% csrf_token %} <p>Action: {{ form.action }}</p> <p>Category: {{ form.category }}</p> <p>Title: {{ form.name }}</p> <p>Text: {{ form.text }}</p> <p>Contact: {{ form.contact }}</p> <p>Price: {{ form.price }} {{ form.price.help_text }}</p> <p>Published date: {{ form.published_date }}</p> <p>Author: {{ form.author }}</p> <p>{{ author_id }}</p> <form> <p><input type="submit" name="submitData" value="Готово" /></p> </form> </form> 

Sorry so much extra code

  • Why do you need an extra form around the input? To debug a form, you can look at form.errors , after the condition if form.is_valid() - Ivan Semochkin

1 answer 1

As it turned out, the problem is in the "extra letters". In addition to the extra form around input, it was not necessary to specify the action in the working form.