Search code examples
pythondjangodjango-formsdjango-viewsdjango-generic-views

Where to execute the following code in Django?


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.


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