简体   繁体   English

Django 最佳实践。 形式

[英]Django best practice. Forms

I have a question related to forms in django(i'm new on it) Look.我有一个与 django 中的表单相关的问题(我是新手)看。 Here i have form that looks like:在这里,我的表格如下所示:

class ProccessAgentForm(forms.Form):
    agent_id = forms.HiddenInput()
    main_name = forms.IntegerField()
    company_name = forms.CharField(max_length=60)
    company_state = forms.CharField(max_length=60)
    company_city = forms.CharField(max_length=60)
    company_country = forms.CharField(max_length=60)
    company_post_code = forms.IntegerField()
    agent_first_name = forms.CharField(max_length=60)
    agent_last_name = forms.CharField(max_length=60)
    agent_phone = forms.CharField(max_length=60)
    agent_fax = forms.CharField(max_length=60)
    agent_email = forms.EmailField()
    agent_city = forms.CharField(max_length=60)
    agent_post_code = forms.IntegerField()
    agent_state = forms.CharField(max_length=60)
    agent_country = forms.CharField(max_length=60)
    signer_first_name = forms.CharField(max_length=60)
    signer_last_name = forms.CharField(max_length=60)
    signer_title = forms.CharField(max_length=60)

And i parsed it like(i know it's not the best choice):我像这样解析它(我知道这不是最好的选择):

form = ProccessAgentForm(request.POST)
    if form.is_valid():
        ....
    designated_company = DesignatedCompany()
    designated_company.pdf_link = copyright_agent.pdf_link
    designated_company.name = request.POST['company_name']
    designated_company.address = company_address
    designated_company.city = request.POST['company_city']
    designated_company.post_code = request.POST['company_post_code']
    designated_company.state = request.POST['company_state']
    designated_company.country = request.POST['company_country']
    designated_company.save()

    agent = DesignatedAgent()
    agent.company = designated_company
    agent.first_name = request.POST['agent_first_name']
    agent.last_name = request.POST['agent_last_name']
    agent.email = request.POST['agent_email']
    agent.address = agent_address
    agent.city = request.POST['agent_city']
    agent.country = request.POST['agent_country']
    agent.post_code = request.POST['agent_post_code']
    agent.state = request.POST['agent_state']
    agent.fax = request.POST['agent_fax']
    agent.phone = request.POST['agent_phone']
    agent.save()

and so on... How can i make it more readable?等等......我怎样才能使它更具可读性? Should i split logic to forms ?我应该将逻辑拆分为表单吗? I know about model Forms, but here i have foreign keys as you saw.我知道模型表单,但这里我有你看到的外键。 I'd appreciate for more detailed response :)我很感激更详细的回复:)

How can i make it more readable?我怎样才能使它更具可读性?

First you can make it safer by using your form's cleaned_data instead of request.POST - it will contain cleaned up, sanitized, and eventually correctly typed values instead of the raw strings from the request's body.首先,您可以通过使用表单的cleaned_data而不是request.POST来使其更安全——它将包含清理、清理和最终正确键入的值,而不是请求正文中的原始字符串。

A bit unrelated but while we're at it: a postal code (zip code) is NOT an integer, it's a string (eventually containing only numeric characters depending on the country).有点不相关,但当我们在做的时候:邮政编码(邮政编码)不是整数,它是一个字符串(根据国家/地区的不同,最终仅包含数字字符)。

Then you could use objects.create() and pass your data directly instead of creating a blank model instance, assigning all attributes manually and then saving it:然后你可以使用objects.create()并直接传递你的数据,而不是创建一个空白模型实例,手动分配所有属性然后保存它:

data = form.cleaned_data
designated_company = DesignatedCompany.objects.create(
    pdf_link=copyright_agent.pdf_link,
    name=data['company_name'],
    address=company_address,
    city=data['company_city'],
    # etc
    )

And finally : just use a pair of ModelForms instead.最后:只需使用一对ModelForms

Should i split logic to forms ?我应该将逻辑拆分为表单吗?

The answer is in the question.答案就在问题中。

I know about model Forms, but here i have foreign keys as you saw.我知道模型表单,但这里我有你看到的外键。

And ?和 ? How is it a problem ?怎么会有问题? Exclude fields you don't want / can't use now from the ModelForm and use the commit=False flag when saving the second form so you can add the missing parts yourself.从 ModelForm 中排除您现在不需要/不能使用的字段,并在保存第二个表单时使用commit=False标志,以便您可以自己添加缺少的部分。

You can even facade both forms and all this inner working in a "form-like" class of your own (a class that doesn't inherhit from Form but has the same API - at least the parts your interested in - and delegates to your CompanyForm and AgentForm) so the view's code don't have to bother...您甚至可以在您自己的“类似表单”的类(该类不继承自Form但具有相同的 API - 至少是您感兴趣的部分 - 并委托给您的CompanyForm 和 AgentForm),所以视图的代码不必打扰......

You can use ModelForm to automatically generate forms that create model instances on save, like this:您可以使用ModelForm自动生成在保存时创建模型实例的表单,如下所示:

class DesignatedCompanyForm(ModelForm):
     class Meta:
         model = DesignatedCompany
         fields = ['name', 'city', 'post_code', 'state', 'country']

There is also CreateView that doesn't require separate form:还有不需要单独表单的CreateView

class DesignatedCompanyCreate(CreateView):
    model = DesignatedCompany
    fields = ['name', 'city', 'post_code', 'state', 'country']

(snippets aren't tested, some fixes could be needed) (片段未经测试,可能需要一些修复)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM