当前位置: 动力学知识库 > 问答 > 编程问答 >

Extending Django's Generic Views

问题描述:

I'm writing my first app in Django, and I have a problem with the create_object Generic View; In my urls.py, I have:

(r'^new$', CreateView.as_view()),

The problem is that when the user submits the "new" form, I need to manipulate the data that will be saved to the database (I actually need to add the user_id foreign key); without Generic Views I used to write:

 form = ClientForm(request.POST)

if form.is_valid():

data = form.save(commit=False)

data.user = request.user

data.save()

form.save_m2m()

in my view (notice data.user=request.user). I've searched Django docs but I can't find a way to do this (maybe by extending the CreateView class) - somewere in The Book there is only an example that overrides the get_object method of a ListView class to update a last_accessed_date field.

网友答案:

You can do this by overriding the get_form method:

from django.views.generic import CreateView

class CustomCreateView(CreateView):
    def get_form(self, form_class):
        form = super(CustomCreateView, self).get_form(form_class)
        form.instance.user = self.request.user
        return form

EDIT: Nowadays I would override form_valid as per Issac Kelly's answer:

from django.views.generic import CreateView

class CustomCreateView(CreateView):
    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(CustomCreateView, self).form_valid(form)
网友答案:

You want to override the form_valid method. link

分享给朋友:
您可能感兴趣的文章:
随机阅读: