我正在尝试在Django中创建一种调查应用程序,其中问题(称为类别)和选项会自动显示在一页上。类别和选项的数量是任意的-页面需要显示所有内容。像这样:
Category 1:
Response a
Response b
Category 2:
Response c
Response d
Response e
etc.
[submit]
我已经创建了一个工作视图,很大程度上依赖于我的模板,而不完全依赖于form.py。 (尚未进行表单验证。)现在所有选项都是单选按钮,但是稍后我将使用不同类型的输入,例如复选框,文本等。
我正在寻找一种方法来(更多)依赖forms.py和views.py,而不是在模板中包含大多数逻辑。
这是我的代码:
models.py:
class Category(models.Model):
category_name = models.CharField('Kategoriens navn', max_length=100)
category_created_at = models.DateTimeField(default=timezone.now, editable=False)
class CategoryOption(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
option_name = models.CharField('Knappens navn', max_length=100)
option_created_at = models.DateTimeField(default=timezone.now, editable=False)
class Response(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
response_created_at = models.DateTimeField(default=timezone.now, editable=False)
class ResponseValues(models.Model):
response = models.ForeignKey(Response, on_delete=models.CASCADE)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
option = models.ForeignKey(CategoryOption, on_delete=models.CASCADE)
views.py:
def project(request):
categories = Category.objects.filter(project=project) # project variable excluded for simplicity
if request.method == 'POST':
response = Response(project=project, user=request.user)
response.save()
for category in categories:
category_id = str(category.pk)
option = request.POST.get(category_id)
if option:
option = CategoryOption.objects.get(id=option)
responsevalues = ResponseValues(response=response, category=category, option=option)
responsevalues.save()
context = {'categories': categories,}
return render(request, 'survey/project.html', context)
project.html:
<form action="" method="post">
{% csrf_token %}
{% for category in categories %}
<h4>{{ category.category_name }}</h4>
{% for option in category.categoryoption_set.all %}
<input type="radio" name="{{ category.pk }}" value="{{ option.pk }}" id="{{ option.pk }}"><label for="{{ option.pk }}">{{ option.option_name }}</label><br>
{% endfor %}
{% endfor %}
<input type="submit" value="Save">
</form>