django多对多表单不显示模型字符串

tag5nh1u  于 2023-06-07  发布在  Go
关注(0)|答案(1)|浏览(125)

Models.py

class Person(models.Model):
    name = models.CharField(max_length=128)
    email = models.EmailField(max_length=128, unique=True)
    courses = models.ManyToManyField('Course', through='Membership')
    def __str__(self):
        return self.email

class Course(models.Model):
    title = models.CharField(max_length=128, unique=True)
    members = models.ManyToManyField(Person, through='Membership')
    def __str___(self):
        return self.title

class Membership(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    course = models.ForeignKey(Course, on_delete=models.CASCADE)

Form.py

class PersonForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = ['name', 'email','courses']
    courses = forms.ModelMultipleChoiceField(
        queryset=Course.objects.all(),
        widget=forms.CheckboxSelectMultiple)

Views.py

class CourseFormView(generic.CreateView):
    model = Course
    fields = ['title']

class PersonFormView(generic.CreateView):
    model = Person
    fields = '__all__'
    reverse_lazy('hello:cookie')

preview here
为什么呈现的html显示Object。我怎样才能在那个表格中显示课程标题呢
我尝试在用户视图中显示课程标题。

uqcuzwp8

uqcuzwp81#

PersonsFormView中指定模板名称

class PersonFormView(generic.CreateView):
    model = Person
    #fields = '__all__'
    template_name = 'person_form.html'
    #reverse_lazy('hello:cookie')
    success_url = reverse_lazy('hello:cookie')

并创建模板文件名person_form.html

<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <ul>
    {% for course in form.courses %}
      <li>
        <label for="{{ course.id_for_label }}">
          {{ course.choice_label }}
        </label>
      </li>
    {% endfor %}
  </ul>
  <input type="submit" value="Submit">
</form>

替换choice_label到他们的显示标题或任何你想要的东西

相关问题