[Answered ]-Django forms – rendering form and redirecting

1👍

Solution:
When the page is called in the first instance using GET, the form is not valid as it seeks a POST method. Hence, all the method need to be changed to POST in the view, i.e.,

@login_required
def index(request):
    user_list = User.objects.exclude(username=request.user)
    form = NetworkForm()
    if request.method == 'POST':
        form = NetworkForm(request.POST)
        if form.is_valid():
            print form.data
            return redirect(request.META['HTTP_REFERER'])

    return render(request, 'chat/index.html', {
        'user_list': user_list,
        'form': form,
    })

Earlier, index was using a GET to render data to index page, and using a POST to use the form. Now, everything works fine.
Special shout-out to @fazil-zaid for the heads-up since you mentioned to include everything in the index view itself, rather than making a separate view for form. Your code pointed that out in a way in addition to Stack here.

1👍

If you want the form to be in the index page, then you could include it in the index view itself.

def index(request):
    if request.method == 'POST':
        form = NetworkForm(request.POST)
        if form.is_valid():
            #do what you wanna do
            #with the form data.
    else:
        form = NetworkForm()
    render(request, 'chat/index.html', { 'form': form})

In the template,

<div class="row"> 
<form action="" method="post"> 
{% csrf_token %} 
{{ form.as_p }} 
<button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button> 
</form> 
</div>

You are not rendering another template, but the same ‘index.html’. Then, multiple view for that is just redundant. Index page could contain the form and render itself. From what I understand, there’s no need of redirections.

There’s no need of add_user view if you’re showing the form in the index page itself.

For your issue, try changing the “class” attribute of the form fields, maybe something like this,

class NetworkForm(forms.Form):
    user_id = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.Select(attrs={'class': 'form-control'}))

Leave a comment