21👍
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)
- In Django loaddata it throws errors for json format but work properly for yaml format, why?
- Using an aggregate in a Django model's property
- Is it possible to make a mobile app in Django?
Source:stackexchange.com