我们从Python开源项目中,提取了以下5个代码示例,用于说明如何使用django.views.generic.edit.CreateView()。
def post(self, request, *args, **kwargs): self.get_model_from_url(**kwargs) self.get_child_model() # to use the django CreateView, we need self.model to be the model thats created self.parent_model = self.model self.model = self.child_model self.form_class = self.form_class_from_model() form = self.get_form() if form.is_valid(): print 'form valid' response_redirect = self.form_valid(form) # now self.object is saved else: print 'form invalid' response_redirect = self.form_invalid(form) if hasattr(self, 'object') and self.object: # if we created something, make a relationship if self.through_model: new_relationshp = self.through_model.create() new_relationshp.parent = self.parent new_relationshp.child = self.object new_relationshp.save() else: self.object.parent = self.parent self.object.save() return HttpResponse(status=201) # created return HttpResponse('Object was not created.', status=503) # unavailable
def get_create_view_class(self): class UCreateView(CreateView): def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return HttpResponseRedirect(self.get_success_url()) return UCreateView
def form_valid(self, form): f = form.save(commit=False) f.score = 0 f.submitter = self.request.user f.save() return super(CreateView, self).form_valid(form)
def form_valid(self, form): form.instance.creator = self.request.user # NOTE: this is necessary here even though it is a CreateView, because # "ValueError: "<Project: test_project>" needs to have a value for # field "project" before this many-to-many relationship can be used." form.instance.save() form.instance.manager.add(self.request.user) # per default a user follows the project he created follow_project(self.request.user, form.instance) # and every developer follows the project, too for dev in form.cleaned_data["developer"]: follow_project(dev, form.instance) return super(ProjectCreateView, self).form_valid(form)
def form_valid(self, form): form.instance.project = Project.objects.get(name_short=self.kwargs.get('project')) form.instance.creator = self.request.user # NOTE: this is necessary here even though it is a CreateView, because # otherwise the reversematch in signals.create.send fails form.instance.save() signals.create.send(sender=self.model, instance=form.instance, user=self.request.user) return super(IssueCreateView, self).form_valid(form)