表单中来自不同模型的 2 个字段

2 fields from different models in a form

我有一个可以正常工作的表格
models.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>

当我打开网站时,我可以 select 一个位置并通过创建按钮进行评论。但是,现在我依赖于位置 class 中的预填充值。如果我希望用户可以直接创建描述和位置标题怎么办(我不希望标题位于 class Review 中)我已经尝试在文档中查找但找不到找到任何东西。我在某处读到我可以创建两种不同的形式来处理不同的事情,但我不确定如何将它们全部合并到 class 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

在视图中使用它:

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

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