Question

Trying to learn Django, maybe I'm getting the main concepts wrong.

Creating a form:

class PostForm(ModelForm):
class Meta:
    model = Post
    exclude = ('pub_date', )
    labels = {
        'body_text': _('Post'),
}

Calling a view with the form:

class PostCreate(generic.CreateView):
    template_name = 'post/post_form.html'
    form_class = PostForm

The problem is I need to manually enter the EXCLUDED value. Python docs say to do something like this:

form = PartialAuthorForm(request.POST)
author = form.save(commit=False)
author.title = 'Mr'
author.save()

I have no idea where to enter this code. My understanding of View functions is that they contain code to make the page and hence won't be called again, but i'm probably wrong. Or maybe I can't use the generic view in this case?

A solution to this problem will suffice, but a conceptual explanation of views would be better.

Was it helpful?

Solution

what is a POSTView? Is it something you created, or maybe something new in django?

One way to accomplish what you are trying to do is to use a django FormView (or CreateView) and override the form_valid method.

class PostCreate(CreateView):
    template_name = 'post/post_form.html'
    form_class = PostForm

    def form_valid(self, form):        
        author = form.save(commit=False)
        author.title = 'Mr'
        author.save()
        # return HttpResponse

OTHER TIPS

If you're using generic view you should have a look at https://docs.djangoproject.com/en/1.6/ref/class-based-views/generic-editing/#createview and look for the methods you inherited from the ancestors (MROs).

Here you could override the post method to assign a value to the pub_date field before saving the model instance. Something like:

class PostCreate(generic.CreateView):
    template_name = 'post/post_form.html'
    form_class = PostForm

    def post(self, request, *args, **kwargs):

         form = PostForm(request.POST)

         if form.is_valid():
             post = form.save(commit=False)
             post.pub_date = datetime.now()
             post.save()

             return self.form_valid(form)

         return self.form_invalid(form)

You could even use form_valid method override directly. Either way, remind that the view can be called with a GET request (involving the presentation of the form, usually empty for create views) and with a POST (form submission).

Look at the Django doc for ModelForm to better understand bound and unbound form behaviour.

Hope this helps!

This example is using a function view, not a class based one. You can do it in your class view inside the form_valid method, but you will need to drop the first line as the form is passed to that method already.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top