0

How can I do to record responses to questions by looping ? I possess several questions and I would answer all powers at the same time creating a loop that gets me every I can create a loop for each question and each answer but when validating the form it does not register in my database ...

So this is my models.py :

class Page(models.Model):
    title = models.CharField(max_length=30)


    def __str__(self):
        return self.title

class Question(models.Model):
    label = models.CharField(max_length=30)
    page = models.ManyToManyField(Page)

    def __str__(self):
            return self.label

class Reply(models.Model):
    question = models.ForeignKey(Question)
    user = models.ForeignKey(Personne)
    answer = models.CharField(max_length=30)
    creationDate = models.DateTimeField(default=django.utils.timezone.now)

    def __str__(self):
        return str(self.answer)

and my templates :

<center><h3> Formulaire de la {{ numPages }} pour lutilisateur : <center>{{ logged_user|upper }}.</center> </h3></center>
<form action="" method="POST" enctype="multipart/form-data" >
    {% csrf_token %}
    <!-- {{ form.as_p }} -->
  <p>
    {% for question in questions %}<hr>
    <label for="question">{{ question }}</label>
    <input type="hidden" id="id_question_{{ question.id }}" name="question" value="{{ question.id }}"/>
  </p>
  <p>
    <label for="answer">Réponse :</label>
    <input type="text" id="id_answer_{{ question.id }}" name="answer" />
  </p>  
    {% endfor %}<hr>
  <p>
    <label for="creationDate">Date de création :</label>
    <input type="text" id="id_creationDate" name="creationDate" />
  </p> 
  <p>
    <label for="user"> User : {{ logged_user }}</label>
    <input type="hidden" id="id_user" name="user" /><!-- <select name="{{ logged_user }}" size="1">
      <option id="{{ logged_user.id }}">{{ logged_user }}</option>
    </select> -->
  </p>
  <p>
  <br><br><br>
    <center><input type="submit" class="btn btn-success" value="Submit" /></center>
  </p>
</form>

and my views.py :

def access(request,instance):
    replies = Reply.objects.all()
    logged_user = get_logged_user_from_request(request)
    numPages = Page.objects.get(pk=instance)
    questions = Question.objects.filter(page=instance)
    pagesfilter = Question.objects.get(pk=1) # PEUT ETRE CHANGER SE FILTRE - A VOIR
    # pagesfilter = Page.objects.get(pk=instance).reply_set.filter(user=logged_user) # PEUT ETRE CHANGER SE FILTRE - A VOIR
    form = ReplyForm(request.GET)
    personnes = Personne.objects.all()
    if logged_user:
        if len(request.POST) > 0:
            form = ReplyForm(request.POST)
            if form.is_valid():
                user = form.cleaned_data['user']
                question = form.cleaned_data['question']
                answer = form.cleaned_data['answer']
                form.save(commit=True)
                return HttpResponse(form.cleaned_data["user"])
            else:
                return render_to_response('polls/access.html', {'logged_user':logged_user, 'pagesfilter': pagesfilter, 'numPages': numPages, 'personnes': personnes, 'replies': replies, 'questions': questions, 'form': form})
        else:
            form = ReplyForm()
            return render_to_response('polls/access.html', {'logged_user':logged_user, 'pagesfilter': pagesfilter, 'numPages': numPages, 'personnes':personnes, 'replies': replies, 'questions': questions, 'form': form})
    else:
        return HttpResponseRedirect('/login')

My forms.py

class ReplyForm(forms.ModelForm):
    class Meta:
        model = Reply
        fields = ('question','answer','user')

EDIT url :

url(r'^baseVisite/$', views.baseVisite),
url(r'^access/(?P<instance>[0-9]+)/$', views.access),

Why my submit button does not work, what I forgot?

3
  • What exactly do you mean by "submit button does not work"? Commented Feb 10, 2016 at 13:12
  • @Hâken When i click on submit i have a good redirection but the information gone in responses does not register in my database Commented Feb 10, 2016 at 13:16
  • Have you tried to step through your view function with pdb? mike.tig.as/blog/2010/09/14/pdb Try to isolate your bug and create a minimal reproducible example. Commented Feb 10, 2016 at 13:25

2 Answers 2

2

EDIT: You want to update many records by using ModelForm : you can't. In your example, only {{ form.as_p }} fields will work. You should use standard form like this post : How to create a list of fields in django forms

Your syntax template is wrong. Your p tag is out your for loop.

Try this instead :

<center><h3> Formulaire de la {{ numPages }} pour lutilisateur : <center>{{ logged_user|upper }}.</center> </h3></center>
<form action="" method="POST" enctype="multipart/form-data" >
  {% csrf_token %}
  <!-- {{ form.as_p }} -->
  {% for question in questions %}
    <hr>
    <p>
      <label for="question">{{ question }}</label>
      <input type="hidden" id="id_question_{{ question.id }}" name="question" value="{{ question.id }}"/>
    </p>
    <p>
      <label for="answer">Réponse :</label>
      <input type="text" id="id_answer_{{ question.id }}" name="answer" />
    </p>  
  {% endfor %}<hr>
  <p>
    <label for="creationDate">Date de création :</label>
    <input type="text" id="id_creationDate" name="creationDate" />
  </p> 
  <p>
    <label for="user"> User : {{ logged_user }}</label>
    <input type="hidden" id="id_user" name="user" /><!-- <select name="{{ logged_user }}" size="1">
      <option id="{{ logged_user.id }}">{{ logged_user }}</option>
    </select> -->
  </p>
  <p>
  <br><br><br>
    <center><input type="submit" class="btn btn-success" value="Submit" /></center>
  </p>
</form>
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, this is because you generate your custom fields. The from.save() method will only take value in form generated with your <!-- {{ form.as_p }} --> line. You cant' use ModelForm if you want edit multiple models in the same time.
Do you have an exemple with ModelForm for multiple recording ?
I'm sorry but no. This is not the goal of ModelForm. Try to update many record by using ModelForm is a pretty bad practice. But you can try Django Forms.
-1

You have to define form action attribute with proper url to access your view, right now your action="" what is wrong.

So you have to define route and register your view with Django URLDispatcher then you would be ready to set form action.

Try to work with Django Tutorial to get better understanding of how django works.

Your form action should be action="access/{id}/", where {id} is id of item page rendered for, but notice that's better to add name to your url declaration as in snippet below:

url(r'^access/(?P<instance>[0-9]+)/$', views.access, name='access')

And use {% url %} to build form action:

action="{% url id %}"

4 Comments

And how i can do that ?
Show your urls.py file
@JeremyLgdr Updated answer with additional information
This is not the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.