Django基于类的UpdateView

时间:2017-08-21 02:57:38

标签: django django-views

我们正在使用Django 1.9.5。我正在写更新公司资料视图。我想在我的更新个人资料页面上有两个字段:

  • 公司name
  • apikey(使用专用函数生成)。

我想手动更改字段name,然后点击按钮更新保存。对于已归档的apikey,我希望有一个单独的按钮,它会自动生成新密钥,将其保存到数据库并更新我的页面。

我正在post课程覆盖UpdateView方法。但是simething不起作用。请看一下我的代码:

models.py:

class Organization(models.Model):

    name = models.CharField(_('organisation display name'), max_length=512,
                            blank=True)


    apikey = models.CharField(_("API authentication key"), max_length=APIKEY_LENGTH,
                              default=get_apikey)

其中get_apikey

from django.utils.crypto import get_random_string


APIKEY_PREFIX = "key-"
APIKEY_LENGTH = 80


def get_apikey():
    rnd_len = APIKEY_LENGTH - len(APIKEY_PREFIX)
    return "{}{}".format(
            APIKEY_PREFIX,
            get_random_string(rnd_len, "abcdefghijklmnopqrstuvwxyz0123456789")
    )

forms.py:

from django import forms
from crispy_forms.helper import FormHelper, Layout
from orgs.models import Organization


class OrgProfileForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(OrgProfileForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_tag = False

    class Meta:
        model = Organization
        fields = ['name', 'apikey']

views.py

from django.views.generic.edit import UpdateView, BaseUpdateView
from orgs.forms import OrgProfileForm
from orgs.models import Organization
from local.auth import get_apikey


class OrgProfileView(UpdateView):
    model = Organization
    template_name = 'orgs/orgprofile.html'
    form_class = OrgProfileForm
    url_name = 'profile'
    success_url = '/'

    def get_object(self, queryset=None):
        org_obj = Organization.objects.get(orgname=self.kwargs["orgname"])
        return org_obj

    def post(self, request, *args, **kwargs):
        import ipdb
        ipdb.set_trace()
        if '_key' in request.POST:
            org_obj = Organization.objects.get(orgname=self.kwargs["orgname"])
            org_obj.apikey = get_apikey()
            org_obj.save()
        self.object = org_obj
        return super(BaseUpdateView, self).post(request, *args, **kwargs)

template.html

{% extends "base.html" %}
{% load i18n %}
{% load staticfiles %}
{% load crispy_forms_tags %}

{% block title %}{% trans "Organization profile" %}{% endblock title %}
{% block header_title %}{% trans "Organization profile" %}{% endblock header_title %}


{% block content %}
    <form action="" method="post">{% csrf_token %}
        {% crispy form %}
        <input type="submit" value="{% trans 'Generate new key' %}" name="_key">
        <input type="submit" value="{% trans 'Update form' %}" name="_update">
    </form>
{% endblock content %}

使用_key和'_update'我想区分两个按钮和操作更新name并重新生成新的apikey

1 个答案:

答案 0 :(得分:1)

哦,我找到了解决方法。在更新apikey的帖子请求中,我需要:

  • 更新模型中的views.py值并保存,
  • 重定向回来获取请求

class OrgProfileView(UpdateView): model = Organization template_name = 'orgs/orgprofile.html' form_class = OrgProfileForm url_name = 'profile' def get_object(self, queryset=None): org_obj = Organization.objects.get(orgname=self.kwargs["orgname"]) return org_obj def post(self, request, *args, **kwargs): if '_key' in request.POST: org_obj = Organization.objects.get(orgname=self.kwargs["orgname"]) org_obj.apikey = get_apikey() org_obj.save() self.object = org_obj return super(BaseUpdateView, self).get(request, *args, **kwargs) else: self.object = self.get_object() return super(BaseUpdateView, self).post(request, *args, **kwargs)

SELECT H.HistoryID, C.Col, C.Val
FROM (
    SELECT *, PrevUser = LAG([User]) OVER (ORDER BY HistoryID), PrevTag = LAG([Tag]) OVER (ORDER BY HistoryID)
    FROM [History] AS H
) AS H
CROSS APPLY (
    VALUES
        ('User', CASE WHEN PrevUser != [User] THEN [User] END),
        ('Tag', CASE WHEN PrevTag != Tag THEN Tag END)
) AS C(Col, Val)
WHERE C.Val IS NOT NULL;