如何在createview中将创建的对象传递给Django中的updateview权限

时间:2019-01-10 22:56:44

标签: django django-views

我在Django应用中有一个createview视图:

### Create a Group 
class GroupCreateView(CreateView): # {{{
  model = Group
  form_class = GroupForm
  template_name = 'ipaswdb/group/group_form.html'
  success_url = '/ipaswdb/group/'

  def get_context_data(self, **kwargs):
    ..do stuff..

  def post(self, request, *args, **kwargs):
    if self.request.POST.has_key('submit'):
      form = GroupForm(request.POST)
      if form.is_valid():

        ### Save the group
        self.object = form.save()


        #### Adding a provider forces a default location
        #if form['default_location'].value() == True:

        ### We are forcing the creation of a GroupLocation when a new Group is created 
        gl = GroupLocation(
          group = Group.objects.get(pk=self.object.id),

          doing_business_as = self.object.group_name,
          default_group_location = True,

          mailing_address_line_one = self.object.mailing_address_line_one,
          mailing_address_line_two = "",
          mailing_city = self.object.mailing_city,
          mailing_state = self.object.mailing_state,
          mailing_zip_code = self.object.mailing_zip_code,
          mailing_phone = self.object.mailing_phone,
          mailing_fax = self.object.mailing_fax,

          contact = self.object.group_contact,

          physical_address_line_one = self.object.billing_address_line_one,
          physical_address_line_two = "",
          physical_city = self.object.billing_city,
          physical_state = self.object.billing_state,
          physical_zip_code = self.object.billing_zip_code,
          physical_phone = self.object.billing_phone,
          physical_fax = self.object.billing_fax,

        ) 
        gl.save()
        new_grploc = gl
        self.object.default_location_id = new_grploc.id
        self.object.save()


        new_group_id = self.object.id
        new_grploc_id = new_grploc.id

        ### Now check the list of providers to see what has changed
        print "group_add_provider: ",
        print request.POST.getlist('group_add_provider')

        add_providers = request.POST.getlist('group_add_provider')

        if add_providers:
          for pro in add_providers:
            add_grploc = GroupLocationProvider(
                             grouplocation=GroupLocation.objects.get(pk=new_grploc_id),
                             provider=Provider.objects.get(pk=pro)
                         )
            add_grploc.save()


        ### Now check the list of insurances to see what has changed
        print "group_add_insurance: ",
        print request.POST.getlist('group_add_insurance')

        add_insurances = request.POST.getlist('group_add_insurance')

        if add_insurances:
          for ins in add_insurances:
            add_grpins = GroupInsurance(
                             group=Group.objects.get(pk=new_group_id),
                             insurance=Insurance.objects.get(pk=ins)
                         )
            add_grpins.save()

       #return HttpResponseRedirect(self.get_success_url())  #how it used to work, just fine but would go back to my list of groups
      return HttpResponseRedirect('ipaswdb:group_detail', self.object.pk)  #want it to call my edit view here.

我的网址模式

app_name = 'ipaswdb'

urlpatterns = [
      url(r'^group/(?P<pk>[0-9]+)/$', GroupUpdateView.as_view(), name='group_detail'),
      url(r'^group/add/$', GroupCreateView.as_view(), name='group_add'), 
      ..etc..

遇到错误,但我觉得我要靠近了吗?

DisallowedRedirect at /ipaswdb/group/add/
Unsafe redirect to URL with protocol 'ipaswdb'

我真的想用创建的对象加载页面,但将其作为更新视图 无论如何要从创建视图执行此操作?

1 个答案:

答案 0 :(得分:1)

强烈建议从成功的POST请求中返回重定向请求。否则,用户可能会通过重新加载页面意外创建多个对象。像这样:

from django.shortcuts import redirect

...

return redirect('name-of-update-url', pk=obj.pk)

如果您真的不想使用重定向,则需要更多的精力。基于类的视图并不意味着可以直接调用。您在as_view中使用的urls.py方法创建一个包装函数,该函数实例化该类并调用dispatch,该函数选择正确的处理程序方法(get / post / ...)。但是您不能使用as_view,因为您有POST请求,但可能想调用get方法。

因此,您必须创建UpdateView的实例并直接调用其get方法。使用标准的UpdateView,可以尝试执行以下操作:

class GroupCreateView(CreateView):
    ...
    def post(self, request, *args, **kwargs):
        ...
        obj = ... # create your object
        update_view = UpdateView()
        update_view.request = self.request
        update_view.args = []
        update_view.kwargs = {'pk': obj.pk}
        return update_view.get(self.request)

如果您大量定制了UpdateView,则可能需要对此进行调整。

我的首选资源https://ccbv.co.uk

是Django的基于类的视图的外观