django:通用視圖-UpdateView更新有參數的form類,django-updateview

來源:互聯網
上載者:User

django:通用視圖-UpdateView更新有參數的form類,django-updateview

這個提示放在開始:要想使用通用視圖更新form,那麼這個form的類型必須是ModelForm,

即:

class FileForm(forms.ModelForm):    ....

不要問我為什麼知道的

------------------------------------------------------------------------------------------------------

首先:urls.py

#coding=utf-8from django.conf.urls import patterns,urlfrom app_filemanager import viewsurlpatterns=patterns('',    ...    url(r'^(?P<pk>\d+)/update/$', views.FileUpdateView.as_view(), name='update'),    # 通用視圖傳值統一使用pk作為變數名,而這個pk往往都是model自己產生的那個編號,所以後面正則匹配用d+)

然後:forms.py

#coding=utf8from django import formsfrom .models import File, Project, Tagfrom django.contrib.auth.models import User, Groupclass FileForm(forms.ModelForm):    def __init__(self, user, *args, **kwargs):        super(FileForm, self).__init__(*args, **kwargs)        self.fields['tag'] = forms.ModelChoiceField(            queryset = Tag.objects.filter(owner=user),            required = True,            label = "分類",            help_text = "不可為空,個人文檔分類使用",            error_messages = {'required': "以下是必填項"},            empty_label = "請至少選擇一個",            widget = forms.Select(                attrs = {                    'class': 'form-control',                    'style': 'width:100%',                }            ),        )    project = forms.ModelChoiceField(        queryset = Project.publicProjects.order_by('-add_date'),        required = False,        label = "所屬項目",        help_text = "可為空白,為了防止混淆,一個文檔只能屬於一個項目",        error_messages = {'required': "以下是必填項"},        widget = forms.Select(            attrs = {                'class': 'form-control',                'style': 'width:100%',            }        ),    )    tag = forms.ModelChoiceField(        queryset = Tag.objects.none(),    )    group = forms.ModelMultipleChoiceField(        queryset = Group.objects.order_by('-id'),        required = True,        label = "哪些組可見",        help_text = "可以多選",        error_messages = {'required': "以下至少選擇一個"},        widget = forms.SelectMultiple(            attrs = {                'class': 'form-control',                'style': 'width:100%'            }        ),    )    desc = forms.CharField(        required = False,        label = "描述",        widget = forms.Textarea(            attrs = {                'placeholder': u'可以通過描述尋找文檔',                'rows': 2,                'style': 'width:100%',                'class': 'form-control',            }        ),    )    file = forms.FileField(        required = True,        label = "文檔",        help_text = "大小限制為1G",        error_messages = {'required': "請選擇一個檔案"},    )    deleted = forms.BooleanField(        required = False,        label = "選中則標記為刪除",        help_text = "預設公開,個人檔案不會被項目歸類",        widget = forms.HiddenInput(            attrs = {                'style': 'width:100%',                'class': 'form-control',            }        ),    )    public = forms.BooleanField(        required = False,        label = "公開",        #help_text = "選中為公開,個人檔案不會被項目歸類",    )    class Meta:        model = File        fields = ('project', 'tag', 'group', 'desc', 'file', 'public')

關於form類裡的init方法,你可以參考我的上篇,這裡

上篇博文是如何將request.user傳到form裡面,這裡講一下如何在update通用視圖傳user

再然後:views.py

class FileUpdateView(UpdateView):    model = File    template_name_suffix = '_update_form'    success_url = '/file/'    permission_required = 'app_filemanager.can_change_file'    permission_fail_message = ('You don\'t have permission to change employee info.')    form_class = FileForm    def get_form_kwargs(self):        kwargs = super(FileUpdateView, self).get_form_kwargs()        kwargs.update({            'user':self.request.user        })        return kwargs

最後:file_update_form.html

{% extends "base.html" %}{% block content_middle %}<form action="" method="post">{% csrf_token %}    {{ form.as_p }}    <input type="submit" class="btn btn-default" value="Update" /></form>{% endblock %}


附上:


就是這麼簡單,所以說django的form類如果會用並且靈活應用的話是很省事的,有問題留言

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.