Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.9K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
Creating a ModelForm with an arugment

I have some simple models of questions and answers.

#models.py
class Question(models.Model):
question_text = models.CharField(max_length=200)
question_info = models.TextField()

def __str__(self):
return self.question_text

class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
answer_text = models.CharField(max_length=200)
correct = models.BooleanField(default=False)

def __str__(self):
return self.answer_text

I am trying to create a ModelForm that takes all the answers for a given question and displays them with radio buttons. I can do this in views.py and the template just fine.

#views.py
def index(request):
q1 = Question.objects.get(pk=1)
context = {
'q1`': q1,
}
return render(request, 'questions/index.html', context)

\#index.html

<head>
<meta charset="utf-8" />
<title>Django</title>
</head>

<body>
<h1>Welcome!</h1>
<h2> {{ q_1.q_text }}</h2>
<form action="" method="POST">
{% csrf_token %}
{% for answer in q_1.answer_set.all %}
<input type="radio" name="answer" id="answer{{ forloop.counter }} value="{{ answer.id }}" />
<label for="choice{{ forloop.counter }}"> {{ answer.answer_text }} </label></br/>
{% endfor %}
<input type="submit" value="Submit" />
</form>

With this I can't call is_valid() so I tried to make a form for the model.

\#forms.py

class AnswerForm(forms.ModelForm):
class Meta:
model = Answer
a1 = Answer.objects.get(id=1)
a2 = Answer.objects.get(id=2)
a3 = Answer.objects.get(id=3)
a4 = Answer.objects.get(id=4)
a5 = Answer.objects.get(id=5)
fields = [
'correct',
]
widgets = {
'correct': forms.RadioSelect(choices = [
(a1.correct, Answer.objects.get(id=1)),
(a2.correct, Answer.objects.get(id=2)),
(a3.correct, Answer.objects.get(id=3)),
(a4.correct, Answer.objects.get(id=4)),
(a5.correct, Answer.objects.get(id=5))
]
)
}

This allows me to use the is_valid() method for validating the form but it is obviously inefficient as it only works for this one question. I would ideally like to the be able to pass a parameter into the ModelForm so that it uses that value to get the question whether from the id/pk or some other value. My thinking for this would then be that the ModelForm uses lets say id as its argument then I could also set up a url that takes the id of a question also and then when I pass the id in the view along with the request that id also gets used in the ModelForm. So I guess my questions are:

1. Is creating a ModelForm with an arugment for a specific object in the model possible?

2. Is the logic behind using the url id to pass to the ModelForm able to work as well?

Any help is appreciated, Thanks.

/r/djangolearning
http://redd.it/5adqqi