I tried customizing a Django poll tutorial.
I gave options so that users can add questions and options themselves.
'Choice' object from my models.py seems to be tricky.
from django.db import models
# Create your models here.
class Question(models.Model):
question = models.CharField(max_length=200)
def __str__(self):
return self.question
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='choices')
option = models.CharField(max_length=100)
vote = models.IntegerField(default=0)
def __str__(self):
return self.option
Choice object is one-to-one relation with the Question. When I end values through the below HTML page, it doesn't create a new Choice.
{% extends 'base.html' %}
{% block content %}
<h1>Add Member</h1>
<form action = 'addoptrecord/' method='post'>
{% csrf_token %}
Choice: <br>
<input name='ch'>
<br>
Vote: <br>
<input name='vo'>
<br>
<label for="optquestions">Choose a Question:</label><br>
<select name="optquestions" id="optquestions">
{% for question in questions %}
<option value={{question.id}}>{{question}}</option>
{%endfor%}
</select><br><br>
<input type='submit' value='Submit'>
</form>
{% endblock %}
Not sure about the right syntax/method to associate the Choice data with Question while adding through views.py
def addoptrecord(request,optquestions):
ch = request.POST.get('ch')
vo = request.POST.get('vo')
que = Question.objects.get(id=optquestions)
pollopt = Choice(que,option=ch,vote=vo)
pollopt.save()
return HttpResponseRedirect(reverse('index'))
The above operation throws me an Integrity Error.
IntegrityError at /addopt/addoptrecord/
NOT NULL constraint failed: pollsapp_question.question
UPDATE: Adding my template file - addopt.html
{% extends 'base.html' %}
{% block content %}
<h1>Add Member</h1>
<form action = 'addoptrecord/' method='post'>
{% csrf_token %}
Choice: <br>
<input name='ch'>
<br>
Vote: <br>
<input type = 'number' name='vo'>
<br>
<label for="optquestions">Choose a Question:</label><br>
<select name="optquestions" id="optquestions">
{% for question in questions %}
<option value={{question.id}}>{{question}}</option>
{%endfor%}
</select><br><br>
<input type='submit' value='Submit'>
</form>
{% endblock %}