【问题标题】:How to get the current Url within a Django Forms?如何在 Django 表单中获取当前 URL?
【发布时间】:2019-03-20 15:16:30
【问题描述】:

我想检查 URL 路径,以便可以基于它创建表单。在视图中,我们可以使用request参数来获取URL路径,有没有类似的方法可以在forms.py里面获取当前的URL?

URL=??
if URL == 'phones':
      brand_choises= (('Sumsung', 'Sumsung'),
                     ('Iphon', 'Iphone'),)
if URL == 'cars':
      brand_choises= (('Honda', 'Honda'),
                     ('Toyota', 'Toyota'),)
class Productform(forms.ModelForm):
    brand=forms.ChoiceField(choices=brand_choises,widget=forms.Select(attrs={'class':'products'}))
    class Meta:
      model = Product

   def __init__(self, *args, **kwargs):
     super(ProductForm, self).__init__(*args, **kwargs)
     self.fields['brand'].choices = brand_choises

【问题讨论】:

标签: django django-forms django-urls


【解决方案1】:

你不能这样做。模块级别或类级别的任何内容都是在首次导入模块时定义的,因此不能依赖于 URL。您唯一能做的就是在实例化表单时传入一个参数,并根据该参数更改选择。您可以使用 dict 来保存选项,以便表单可以从参数中选择相关选项:

CHOICE_DICT = {
  'phone': (
    ('Samsung', 'Samsung'),
    ('iPhone', 'iPhone'),
  )
  'car': (
    ('Honda', 'Honda'),
    ('Toyota', 'Toyota'),
  )
}

class Productform(forms.ModelForm):
    brand=forms.ChoiceField(choices=brand_choises,widget=forms.Select(attrs={'class':'products'}))
    class Meta:
      model = Product

   def __init__(self, *args, **kwargs):
     form_type = kwargs.pop('form_type', None)
     super(ProductForm, self).__init__(*args, **kwargs)
     self.fields['brand'].choices = CHOICE_DICT[form_type]

然后在你的表单中你会做form = Productform(form_type='car') 或其他什么。不要忘记在 POST 和 GET 上都传递它。

【讨论】:

  • 感谢您的回答,我按照您的指示进行操作,但收到此错误“__init__() got an unexpected keyword argument 'form_type'”
猜你喜欢
  • 2011-02-22
  • 1970-01-01
  • 2011-02-21
  • 1970-01-01
  • 2019-09-23
  • 2010-12-23
相关资源
最近更新 更多