简体   繁体   中英

is it possible to store form values in a drop down list in django

I am using django to make a questions application, I am allowing users to add questions to the site with a couple of optional answers for each question that are defined by the user who made the question. I am wanting to display the optional answers in a drop down box. but I keep getting an error from my model saying option one is not defined.

choice modal

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)

    CHOICES = (
        (option_one,option_one),
        (option_two,option_two),

    )
    user_choice = models.CharField(
        max_length=200,
        choices=CHOICES,
        default=Yes,
    )

    votes = models.IntegerField(default=0)

    def __str__(self):
        return  self.user_choice

view

def create_poll(request):

    if request.method == 'POST':
        form = CreatePollForm(request.POST)
        if form.is_valid():
            question = form.cleaned_data['question']
            option_one = form.cleaned_data['option_one']
            option_two = form.cleaned_data['option_two']
            print option_one
            q = Question.objects.create(question_text=question)
            o = Choice.objects.create(question=q, option_one=option_one,option_two=option_two)
            q.save()
            o.save

            form = CreatePollForm()
            return render(request, 'polls/createPolls_form.html', {'form':form})

    form = CreatePollForm()
    return render(request,'polls/createPolls_form.html',{'form':form})

forms.py

class CreatePollForm(forms.Form):
        question = forms.CharField(max_length=100)
        option_one = forms.CharField(max_length=100)
        option_two = forms.CharField(max_length=100)

Why don't you try to remove the default choices and then try same:

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)

    user_choice = models.CharField(
        max_length=200,
        default=Yes,
    )

    votes = models.IntegerField(default=0)

    def __str__(self):
        return  self.user_choice

you are using option_one as a variable and that's not defined. you can use it as a string like 'option_one' or can define it earlier like option_one = 'whatever you want to define.....'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM