Bob Billinger
Bob Billinger

Reputation: 31

How to save to a database on click

In my previous question, I recently asked how to make forms.py in Django 1.9 show in HTML. now that this is done im trying to make a button which when the selection has been made (in this case it's radiobuttons) it will post to the database and move on with the questionaire.

Currently im attempting to make it post in my views.py but im having no luck in making it send the data.

def question1(request):
    question_form = QuestionForm()
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        if form.is_valid():
            return render(request, 'music.questions2,html')
    return render(request, 'music/question1.html', locals())

Would really appreciate the help in making this happen.

Upvotes: 0

Views: 409

Answers (2)

nik_m
nik_m

Reputation: 12086

def question1(request):
    question_form = QuestionForm()
    if request.method == 'POST':
        form = QuestionForm(request.POST)
            if form.is_valid():
                form.save()  # save to db!
                return render(request, 'music.questions2,html')
    return render(request, 'music/question1.html', locals())

# models.py
class Question(models.Model):
    # Q_CHOICES is the previous declared one
    question = models.CharField(max_length=20, choices=Q_CHOICES)

# forms.py
class QuestionForm(forms.ModelForm):
        class Meta:
            model = Question
            fields = ['question']
            widgets = {
                'question': forms.RadioSelect()
            }

Upvotes: 1

Marin
Marin

Reputation: 1121

Use: form.save()

def question1(request):
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'music.questions2,html')
    else:
        form = QuestionForm()
    return render(request, 'music/question1.html', locals())

Upvotes: 1

Related Questions