將我的def視圖轉換為基於類的視圖

[英]Convert my def view to class based view


I have this view in my app:

我的應用程序中有這個視圖:

def contact(request):
    form_class = ContactForm

    if request.method == 'POST':
        form = form_class(data=request.POST)

        if form.is_valid():
            contact_name = form.cleaned_data['contact_name']
            contact_email = form.cleaned_data['contact_email']
            contact_website = form.cleaned_data['contact_website']
            contact_subject = form.cleaned_data['contact_subject']
            form_content = form.cleaned_data['content']

            template = get_template('contact/contact_template.txt')
            context = Context({'contact_name': contact_name,
                               'contact_email': contact_email,
                               'contact_website': contact_website,
                               'contact_subject': contact_subject,
                               'form_content': form_content, })
            content = template.render(context)

            email = EmailMessage(
                "New contact form submission",
                content,
                "www.inexistente.com" + '<support@inexistente.com>',
                ['mymail@gmail.com'],
                headers={'Reply-To': contact_email}
            )
            email.send()
            return redirect('/')

    return render(request, 'contact/contact.html', {'form': form_class, })

I want to transform this to a class based view, I believe that is "more organized" for me...

我想把它變成一個基於階級的觀點,我相信這對我來說“更有條理”......

  • What generic Django view to use?
  • 使用什么通用Django視圖?
  • Do you believe that is recommended to do this?
  • 你認為建議這樣做嗎?
  • In the view, Is recommended use this code at the end to renew the form in case of not passing?
  • 在視圖中,建議在最后使用此代碼更新表單以防未通過?

"else: form = form_class()"

“else:form = form_class()”

i was trying without that code and my form renews itself perfectly.

我試着沒有那個代碼,我的表格完美地更新了。

apologizeme in advance if I overlook something, any contribution is wellcome, Thanks for evaluate!

如果我忽視某些事情,請提前道歉,任何貢獻都是好的,謝謝評價!

1 个解决方案

#1


1  

Since you have a view that displays a form and which redisplays the form with validation errors on error and redirects to a new URL on success, you can use FormView generic view.

由於您有一個顯示表單的視圖,並且在錯誤時重新顯示包含驗證錯誤的表單,並在成功時重定向到新URL,因此您可以使用FormView通用視圖。

Your FBV code converted to CBV:

您的FBV代碼轉換為CBV:

from django.views.generic import FormView

class Contact(FormView):

    form_class = ContactForm  # Form class to be used
    template_name = 'contact/contact.html' # Template to be used
    success_url = '/'  # Redirect to this url when form is valid

    def form_valid(self, form):
        template = get_template('contact/contact_template.txt')
        context_dict = form.cleaned_data
        context_dict['form_content'] = form.cleaned_data['content'] 
        context = Context(context_dict)             
        content = template.render(context)

        email = EmailMessage(
                "New contact form submission",
                content,
                "www.inexistente.com" + '<support@inexistente.com>',
                ['mymail@gmail.com'],
                headers={'Reply-To': contact_email}
            )
        email.send()
        return super(Contact, self).form_valid(form)

Here,
form_class: defines the form class to be used.
template_name: defines the template to be used to display the form.
success_url: defines the url to be used when the form is valid.

這里,form_class:定義要使用的表單類。 template_name:定義用於顯示表單的模板。 success_url:定義表單有效時要使用的url。

You can put all the logic for the code to be executed when form is valid inside the form_valid() function. After performing all the operations, call the super() which redirects to the success_url defined in your class.

當form在form_valid()函數中有效時,您可以將代碼的所有邏輯放在執行中。執行所有操作后,調用super(),它會重定向到您班級中定義的success_url。

Also, when you are building context to be passed to the email template, you can use the form.cleaned_data dictionary. All the keys you have used to build the context dictionary is same as in the form's cleaned_data dictionary except the form_content key. So, i have just used the form's cleaned_data dictionary and added an extra key form_content in a context_dict dictionary which will be then used in the email template for rendering.

此外,在構建要傳遞給電子郵件模板的上下文時,可以使用form.cleaned_data字典。除了form_content鍵之外,用於構建上下文字典的所有鍵與表單的cleaning_data字典中的相同。所以,我剛剛使用了表單的cleaning_data字典,並在context_dict字典中添加了一個額外的鍵form_content,然后將其用於電子郵件模板中進行渲染。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/07/04/72fd83a477219cab6556a1a3a06c3bc3.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com