我已经建立了一对多的关系,我需要保持这种关系。也可以创建多种表单吗?我是python的新手。是否可以使用两个模型创建两个模型表单并将其放入views.py文件中,该怎么办? 但是我的网络表单中出现“选择一个有效的选择。男性不是可用的选择之一”的错误。
forms.py
from django import forms
from .models import Diseases, Gender
class GenderForm(forms.ModelForm):
class Meta:
model = Diseases
fields = ['gender_disease', 'diseases']
Models.py
from django.db import models
from django.db.models import Count
from itertools import groupby
Gender_Choice = (
('Male', 'MALE'),
('Female', 'FEMALE'),
)
Diseases_Choice= (
('Cholera', 'CHOLERA'),
('HIV', 'HIV'),
('Malaria', 'MALARIA'),
('Typhoid', 'TYPHOID'),
('Measles', 'MEASLES'),
)
class Gender(models.Model):
gender=models.CharField(max_length=19, choices=Gender_Choice , default='Male')
def __str__(self):
return self.gender
class Diseases(models.Model):
gender_disease = models.ForeignKey(Gender, choices=Gender_Choice, on_delete=models.CASCADE)
diseases = models.CharField(max_length=19, choices=Diseases_Choice , default='Malaria')
def __str__(self):
return self.diseases
Views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import GenderForm
from django.views.generic import ListView, CreateView, UpdateView
from . models import Gender, Diseases
from django.db.models import Count
from django.views.generic.list import ListView
class CreateMyModelView(CreateView):
model = Diseases
form_class = GenderForm
template_name = 'checkmate/name.html'
success_url = 'result'
context_object_name = 'name'
class MyModelListView(ListView):
template_name = 'checkmate/result.html'
context_object_name = 'Results'
def get_queryset(self):
queryset = GenderForm.objects.values('Gender', 'Diseases').annotate(Patients=Count('*'))
return queryset
name.html
{% extends 'checkmate/base.html' %}
{% block main_content %}
<br>
<form action="" method="post">{% csrf_token%}
{{form.as_p}}
<input type="submit" action="btn btn-success" value="Vote"/>
</form>
{% endblock %}
result.html
{% extends 'checkmate/base.html' %}
{% block main_content %}
<h2>Disease Count</h2>
<br>
<ul>
{% for item in Results %}
<li> <b>{{item.Gender}} - {{item.Diseases}} - {{ item.Patients}} votes</b></li>
{% endfor %}
</ul>
<br>
{% endblock %}
所需的输出
Male Malaria 4votes
Male HIV 3votes
Female HIV 5votes