Note that there are some explanatory texts on larger screens.

plurals
  1. POA better way of setting values in CreateView?
    primarykey
    data
    text
    <p><code>models.py</code>:</p> <pre><code>class BlogPost(models.Model): title = models.CharField(max_length=200) post_body = models.TextField() user = models.ForeignKey(User) pub_date = models.DateTimeField('published') def get_absolute_url(self): return u'/entries/%d' % self.id </code></pre> <p><code>forms.py</code>:</p> <pre><code>class NewPostForm(forms.ModelForm): class Meta: model = BlogPost fields = ('title', 'post_body') </code></pre> <p>So, I was trying to make a view for users to post a new post into blog. BlogPost model has 4 fields - <code>title</code>, <code>post_body</code>, <code>user</code>, and <code>pub_date</code>. User should be able to fill the <code>title</code> and <code>post_body</code>, while the other two should be filled automatically. First thing I tried was this:</p> <pre><code>class NewPostView(generic.edit.CreateView): model = BlogPost form_class = NewPostForm def get_initial(self): return {'pub_date': timezone.now(), 'user': self.request.user} </code></pre> <p>But the only thing it does is providing the default values for html form. After additional research this is the code that ended up working:</p> <pre><code>class NewPostView(generic.edit.CreateView): model = BlogPost form_class = NewPostForm def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user obj.pub_date = timezone.now() obj.save() return HttpResponseRedirect(obj.get_absolute_url()) </code></pre> <p>So, while overriding form_valid method worked, I don't feel like it's how it should be done maybe? Is there a better place to put this actions into? What is the conventional way of doing this?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload