Django:使用相同的tamplateview进行创建和更新

时间:2018-07-24 11:51:16

标签: python django

我有这个TemplateView:

class DamageEntry(TemplateView):
    template_name = "damage/damageadd.html"

def get(self, request):
    general = General.objects.get(pk=1)
    form = DamageEntryForm()
    args = {'form': form,
            'general': general,
            }
    return render(request, self.template_name, args)

def post(self, request):
    general = General.objects.get(pk=1)
    form = DamageEntryForm(request.POST)
    form.non_field_errors()

    if form.is_valid():
        post = form.save(commit=False)

        if self.request.user.is_authenticated():
            post.user = request.user


        post.userip = get_client_ip(request)  # το IP του χρήστη

        location = get_cocation(post.lat, post.lng)

        post.location = location
        post.formatted_address= location.formatted_address


        post.entry_date = datetime.datetime.now(tz=timezone.utc)
        post.save()

        form = DamageEntryForm()
        args = {'form': form,
                'general': general
                }
        return http.HttpResponseRedirect('damage/add/')

    else:
         print('form is not valid')
         print(form.errors)
        # form = DamageEntryForm()
         args = {'form': form,
                'general': general
                }
         return render(request, self.template_name, args)

它可以很好地用于创建新记录。 我想使用相同的视图进行更新,因为“发布”部分中的额外代码

我使用此网址进行更新:

# /damage/damage/list/1
url(r'damage/list/(?P<pk>[0-9]+)/$', views.DamageEntry.as_view(), name="damage-by-id"),

我可以这样做吗?如何传递pk来创建和更新记录

非常感谢

0 个答案:

没有答案