python - 表单中不同模型的 2 个字段

标签 python django forms field

我有一个工作完美的表单
模型.py:

class Location(models.Model):
    title = models.CharField(max_length=300)
    description = models.TextField(null=True, blank=True)
    address = models.TextField(null=True, blank=True)

class Review (models.Model):
    location = models.ForeignKey(Location)
    description = models.TextField(null=True, blank=True) 

views.py:

class Create(CreateView):
  model = coremodels.Review
  template_name = 'location/test.html'
  fields = '__all__'
  def form_valid(self, form):
    form.save()
    return HttpResponseRedirect('')

    return super(Create, self).form_valid(form)

html:

<form action="" method="post">{% csrf_token %}
    {{ form}} 
    <input type="submit" value="Create" />
</form>

当我打开网站时,我可以选择一个位置并通过创建按钮进行评论。但是,现在我依赖于 Location 类中预填充的值。如果我希望用户可以直接创建描述以及位置标题(我不希望标题位于 class Review 中),我已经尝试在文档中查找此内容,该怎么办但找不到任何东西。我在某处读到我可以创建两种不同的形式来处理不同的事情,但我不确定如何将所有内容合并到类Create中。有没有类似 model = coremodels.Review & coremodels.Location 的东西,然后在 html 中我可以这样做

{{form.title}}
{{form.description}}  

我可以寻找任何想法或搜索词吗?

谢谢!

编辑 好的,感谢 Ruddra 和 this post ,这是工作解决方案。我必须对其进行一些编辑才能使其为我工作,

class SomeForm(forms.ModelForm):

   def __init__(self, *args, **kwargs):
      super(SomeForm, self).__init__(*args, **kwargs)
      self.fields['title'] = forms.CharField(label='Title', required = False)
      self.fields['description'] = forms.CharField(label='Description', required = False)
      self.fields['location'] = forms.ModelChoiceField(queryset= Location.objects.all(), required = False) # This line is for making location not required in form field for input

   class Meta:
        model = Review
        fields = '__all__'


   def save(self, commit=True):
       """
       It will save location from choice field or inputs of title and description
       """
       instance = super(SomeForm, self).save(commit=False)
       if instance.location_id:
           instance.save()
       else:
           new_location = Location.objects.create(title=self.cleaned_data['title'])
           instance.location = new_location
           instance.save()
      return instance

和views.py

class Create(CreateView):
  model = coremodels.Review
  template_name = 'location/test.html'
  form_class = SomeForm

最佳答案

不幸的是,您不能使用这样的两个模型,您必须编写一个表单并在那里执行操作。例如:

class SomeForm(forms.ModelForm):

   def __init__(self, *args, **kwargs):
      super().__init__(*args, **kwargs)
      self.fields['title'] = forms.CharField(label='Title', required = False)
      self.fields['description'] = forms.CharField(label='Description', required = False)
      self.fields['location'] = forms.ModelChoiceField(queryset= Location.objects.all(), required = False) # This line is for making location not required in form field for input

   class Meta:
        model = Review
        fields = '__all__'


   def save(self, commit=True):
       """
       It will save location from choice field or inputs of title and description
       """
       instance = super().save(commit=False)
       if instance.location:
           instance.save()
       else:
           new_location = Location.objects.create(title=self.cleaned_data['title'], description = self.cleaned_data['description']])
           instance.location = new_location
           instance.save()
      return instance

在 View 中使用它:

class Create(CreateView):
  model = coremodels.Review
  template_name = 'location/test.html'
  form = SomeForm

并且您已确保位置可以为空或表单中不需要(我已将其添加到示例中)

关于python - 表单中不同模型的 2 个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32000147/

相关文章:

Angular 6嵌套子子响应式(Reactive)表单未重置

jquery - 使用 jQuery 填写表单

python - 我已经安装了pylint。但它不会按类型、原始指标、重复等显示统计信息。表。如何让 pylint 显示它?

django导入客户端

django - Wagtail CMS 文档返回 404

python - 如何设置 matplotlib 以使用 Django 框架(python)

javascript - 无法通过在javascript中使用表单名称获取表单元素

list - 将列表切片为子列表列表

python - 如何获取表中出现频率最高的行

python - 告诉 python 在每一行写一些东西