Django 1.2 - Pb with form in template (WSGIRequest)

I try to display a form on a template, but I get a fantastic error:

Caught AttributeError on rendering: WSGIRequest object does not have 'get' attribute

The error in this line is: {% for the field in form.visible_fields%}

My opinion:

def view_discussion(request, discussion_id):
 discussion = get_object_or_404(Discussion, id=discussion_id)
 form = BaseMessageForm(request)

 return render(request,'ulule/discussions/view_discussion.html', {
  'discussion':discussion,
  'form':form,
 })

My form:

class BaseMessageForm(forms.Form):
 message_content = forms.CharField(widget=forms.HiddenInput())

My template:

<form action="" method="post">
{% csrf_token %}
    {% for field in form.visible_fields %}
        <div class="fieldWrapper">
            {% if forloop.first %}
                {% for hidden in form.hidden_fields %}
                {{ hidden }}
                {% endfor %}
            {% endif %}

            {{ field.errors }}
            {{ field.label_tag }}: {{ field }}
        </div>
    {% endfor %}
    <p><input type="submit" value="Send message" /></p>
</form>

Many thanks for your help!

+3
source share
1 answer

If I remember correctly, the error you get is because you got the form initializer’s signature incorrectly: the first argument for it is “data”, which in your case is in the .POST request (and not the request itself) if you arrive in the POST which is located.

Typically, a view with a form will look something like this:

def my_view(request, ...):
    if request.method == 'POST': # The form has been submitted
        form = MyForm(request.POST)
        if form.is_valid():
            # do whatever you want here, save the form, etc
    else:
        form = MyForm()
    return render_to_response('myform.html', ... )
+6
source

Source: https://habr.com/ru/post/1737110/


All Articles