创建django表单 [英] creating django forms

查看:106
本文介绍了创建django表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力让我的头转向django形式..我一直在阅读各种文档,但是不能完全理解这些概念。我必须掌握模型,视图和模板。我想要做的是创建一个表单,其中包含由数据库中的值填充的下拉列表和复选框的各种字段。

I'm struggling to get my head round django forms.. I've been reading various documentation but just can't quite grasp the concepts. I have got to grips with models, views and templates. What I am trying to do is to create a form with various fields composing of dropdown lists and checkboxes which are populated by values in a database.

我有一个名为vms的工作应用程序。使用models.py我建立了一个容纳大小和类型的简单模式。尺寸由小,中和 '大'。类型为'windows'& 'Linux的。使用管理员网站,我可以添加额外的大小,例如超大。

I have a working app called vms. Using the models.py I have a built a simple schema that holds size and type. Size consists of 'small', 'medium' & 'large'. Type is 'windows' & 'linux'. Using the admin site, I can add an extra size, for example 'Extra Large'.

我想做的是创建一个下拉列表的表单的vm大小。如果通过管理网站添加了一个额外的大小,我希望这个大小显示在下拉列表中。

What I would like to do is create a form that has a drop down list of the vm sizes. If an extra size gets added via the admin site, I would like that size to appear in the drop down list.

我会提交我对代码的尝试,但实际上我正在努力与这些概念。任何人可以帮助指导我如何完成上述?

I would submit my attempts at the code, but actually am struggling with the concepts. Can anyone help guide me in how to accomplish the above?

感谢
Oli

Thanks Oli

推荐答案

表单只是简化和加速(开发)从请求中提取POST数据的过程的工具。一个HTML格式的所有字段的手动方式是对 request.POST.get('somefield')进行处理。但是,Django可以做得比那更好。

Forms are just a tool to simplify and speed-up (the development of) the process of fetching POST data from the request. A manual way would be to do request.POST.get('somefield') for all the fields there are in some HTML form. But Django can do better than that...

其实质在于一个Form类包含一些Fields并执行这些任务:

In its essence, a Form class holds a number of Fields and performs these tasks:


  1. 显示HTML输入

  2. 在用户提交数据时收集和验证数据

  3. if字段不验证,如果所有字段验证,请将值与错误消息一起返回到HTML,

  4. ,提供 form.cleaned_data 作为访问这些值的一种方便的方法。

  1. display HTML inputs,
  2. collect and validate data when user submits it,
  3. if fields don't validate, return the values along with error messages to HTML,
  4. if all fields validate, provide form.cleaned_data dictionary as a convenient way to access these values in view.

使用这些值,我可以手动创建一个新$实例c $ c> MyModel 并保存。当然,我必须在MyModel模型中的每个字段的窗体中定义一个字段。

With these values, I could then manually create a new instance of a MyModel and save it. Of course, I would have to define a Field in the Form for every Field in MyModel model.

这意味着,基本上我可以做这样的事情:

(原谅我没有测试这个代码,所以我不能保证它是100%正确的)

This means that, basically, I could do something like this:
(forgive me for not testing this code, so I can't vouch that it's 100% correct)

models.py:

    class MyModel(models.Model):
        field1 = models.CharField(max_length=40, blank=False, null=False)
        field2 = models.CharField(max_length=60, blank=True, null=True)

forms.py:

    class FormForMyModel(forms.Form):
        form_field1 = forms.CharField(max_length=40, required=True)
        form_field2 = forms.CharField(max_length=60, required=False)

views.py:

    def create_a_my_model(request):
        if request.method == 'POST':
            form = FormForMyModel(request.POST)
            if form.is_valid():
                my_model = MyModel()
                my_model.field1 = form.cleaned_data.get('form_field1', 'default1')
                my_model.field2 = form.cleaned_data.get('form_field2', 'default2')
                my_model.save()
        else:        
            form = FormForMyModel()
        context_data = {'form': form}
        return HttpResponse('templtate.html', context_data)

(这可能会用少行代码编写,但这意味着尽可能的清楚)

(this could be written with a few lines of code less, but it's meant to be as clear as possible)

注意模型字段和表单字段之间没有关系!在创建它时,我们必须手动将值分配给MyModel实例。

Notice there are no relation between model Fields and form Fields! We have to manually assign values to MyModel instance when creating it.

上述示例概述了通用表单工作流。通常需要复杂的情况,但不是像这样一个简单的例子。

The above example outlines generic form workflow. It is often needed in complex situations, but not in such a simple one as is this example.

对于这个例子(和一个真实世界的例子),Django可以做得比那更好...

For this example (and a LOT of real-world examples), Django can do better than that...

您可以注意到上述示例中有两个令人讨厌的问题:

You can notice two annoying issues in the above example:


  1. 我必须分别在 MyModel FormForMyModel 之间的字段中定义字段。然而,这两个字段(类型)之间有很多相似之处,所以这是一种重复的工作。添加标签,验证器等时,相似度会增加。

  2. 创建 MyModel 实例有点傻,必须分配所有这些值

  1. I have to define Fields on MyModel and Fields on FormForMyModel separately. However, there is a lot of similarity between those two groups (types) of Fields, so that's kind of duplicate work. The similarity grows when adding labels, validators, etc.
  2. creating of MyModel instance is a bit silly, having to assign all those values manually.

这是一个 ModelForm 的地方。

这些行为基本上就像一个常规格式(实际上,他们从常规表单扩展),但他们可以拯救我的一些工作(我刚刚概述的两个问题,当然:)

These act basically just like a regular form (actually, they are extended from regular forms), but they can save me some of the work (the two issues I just outlined, of course :) ).

所以回到两个问题:


  1. 而不是为每个模型Field定义一个表单Field,我只需在 Meta 类中定义 model = MyModel 。这指示表单自动从模型字段生成表单字段。

  1. Instead of defining a form Field for each model Field, I simply define model = MyModel in the the Meta class. This instructs the Form to automatically generate form Fields from model Fields.

模型表单具有保存方法可用。这可以用于在视图中的一行中创建模型实例,而不是手动分配逐个字段。

Model forms have save method available. This can be used to create instance of model in one line in the view, instead of manually assigning field-by-field.

所以,让上面的例子用一个 ModelForm

So, lets make the example above with a ModelForm:

models.py:

    class MyModel(models.Model):
        field1 = models.CharField(max_length=40, blank=False, null=False)
        field2 = models.CharField(max_length=60, blank=True, null=True)

forms.py:

    class MyModelForm(forms.ModelForm):  # extending ModelForm, not Form as before
        class Meta:
            model = MyModel

views.py:

    def create_a_my_model(request):
        if request.method == 'POST':
            form = MyModelForm(request.POST)
            if form.is_valid():
                # save the model to database, directly from the form:
                my_model = form.save()  # reference to my_model is often not needed at all, a simple form.save() is ok
                # alternatively:
                # my_model = form.save(commit=False)  # create model, but don't save to database
                # my.model.something = whatever  # if I need to do something before saving it
                # my.model.save()
        else:        
            form = MyModelForm()
        context_data = {'form': form}
        return HttpResponse('templtate.html', context_data)

希望这个清除对Django的使用形式有所增加。

Hope this clears up the usage of Django forms a bit.

只需一个注释 - 在 ModelForm 。这些不会在 form.save()中使用,但仍可以使用 form.cleaned_data 访问,就像在常规表格。

Just one more note - it is perfectly ok to define form Fields on a ModelForm. These will not be used in form.save() but can still be access with form.cleaned_data just as in a regular Form.

这篇关于创建django表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆