R
R
realgord882015-09-14 00:58:12
Django
realgord88, 2015-09-14 00:58:12

How to do data validation from form with data from database?

A small service for tasks is being written.
The page displays all tasks under which forms for entering the correct answer (flag). Tell me how to check the entered data in the form with the desired answer in the database?
views.py

def tasks(request):
    task = Task.objects.all()
    context = {
        'tasks': task,
    }
    if request.method == 'POST':
        form = AnswerForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/result/')
    else:
        form = AnswerForm()
        context = {
            'tasks': task,
            'form': form
        }
    return render(request, 'Socket/task.html', context)

models.py
class Task(models.Model):
    name = models.TextField()
    category = models.TextField()
    right_answer = models.TextField()
    description = models.TextField(blank=True)
    points = models.IntegerField()
    date = models.DateField()
    file = models.FileField(upload_to='/Files/', verbose_name='Файл', blank=True)

template
{% block content %}
{% for task in tasks %}
    <h3>{{ task.name }} - {{ task.points }} очков</h3>
    <h4>Категория - {{ task.category }}</h4>
    <pre>{{ task.description }}</pre>
    <form action="" method="post">
      {% csrf_token %}
       {% bootstrap_form form %}
     {% buttons %}
        <button type="submit" class="btn btn-primary">
            {% bootstrap_icon "ok" %} Ответить
        </button>
    {% endbuttons %}

    </form>
    {% endfor %}
{% endblock %}

The form
class AnswerForm(forms.Form):
    answer = forms.CharField(widget=forms.TextInput, label='Флаг')

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
zigen, 2015-09-14
@realgord88

It is necessary to override the form.is_valid() method and add a comparison of the entered answer with the true one from the database

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question