Extending Django's Generic Views

≡放荡痞女 提交于 2019-11-29 17:51:50

问题


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.


回答1:


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)



回答2:


You want to override the form_valid method.



来源:https://stackoverflow.com/questions/7147059/extending-djangos-generic-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!