Django CreateView基于url参数自定义表单默认字段 [英] Django CreateView customise form default field based on url parameter

查看:88
本文介绍了Django CreateView基于url参数自定义表单默认字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文件:Capacity / models.py

file: Capacity/models.py

class Env(models.Model):
    name = models.CharField(max_length=50)
    def get_absolute_url(self):
            return reverse('index')

class Envhosts(models.Model):
    env =  models.ForeignKey(Env)
    hostname = models.CharField(max_length=50)
    count = models.IntegerField()

    class Meta:
        unique_together = ("env","hostname")

    def get_absolute_url(self):
        return reverse('index')

文件:Capacity / views.py

file: Capacity/views.py

 class EnvhostsCreate(CreateView):
    model = Capacity.models.Envhosts
    fields=['env','hostname','count']
    template_name_suffix = '_create_form'

文件容量/ urls。

file Capacity/urls.py:

urlpatterns = patterns(........ url(r'^createhosts/(?P<envid>\d+)/$',EnvhostsCreate.as_view(),name='envhosts_create'))

现在,当我打开此表单时,

/ Capacity / createhosts / 3 / (其中3是我的环境ID)
根据环境对象的数量,它显示环境对象的选项作为下拉列表。但是我希望它根据env id(在这种情况下为'3')独自使用env。

So now, when i open this form: /Capacity/createhosts/3/ (where 3 is my env id) It shows an option of env objects as a drop down list based on the number of object of Env. But i want it to take the env on its own based on the env id ('3' in this case)

我知道我必须重写类EnvhostsCreate中的某些方法(创建视图)。但是我无法根据 / createhosts /

I know i have to override some method in class EnvhostsCreate(CreateView). But i m unable to figure out which method and how to take the env based on the part after /createhosts/

推荐答案

您可以使用用于添加request.user的文档-这是相同的原理。从字段列表中删除 env ,然后定义 form_valid()

You can use the pattern described in the documentation for adding request.user - it's the same principle. Remove env from the fields list, then define form_valid():

class EnvhostsCreate(CreateView):
    model = Capacity.models.Envhosts
    fields = ['hostname', 'count']
    template_name_suffix = '_create_form'

    def form_valid(self, form):
        form.instance.env = Envhosts.objects.get(pk=self.kwargs['envid'])
        return super(EnvhostsCreate, self).form_valid(form)

这篇关于Django CreateView基于url参数自定义表单默认字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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