Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submitting form without redirects in Django

In my main page I have included a template with form for adding emails to newsletter. I'd like this form to add new emails without redirecting anywhere. How I can achieve that ? Here is my code, when I was using separate page for this :

views :

def newsletter_add(request):
    if request.POST:
        f = NewsletterForm(request.POST)
        if f.is_valid():
            try:
                e = NewsletterEmails.objects.get(email = request.POST['email'])
                msg = u'Mail already added'
                return render_to_response('newsletter/add.html',
                    {'form':f,'msg':msg,},RequestContext(request))
            except Address.DoesNotExist:
                e = NewsletterEmails(email = request.POST['email'])
                e.save()
                msg = u'Mail added'
                return HttpResponseRedirect('/')
    else:
        f = NewsletterForm()
    return render_to_response('newsletter/add.html',{'form':f,},RequestContext(request))

form :

{% block content %}
    <div class="center-right">
        <div class="pane profile">
            <div class="div-content">
                {{ msg }}
                <form action="" method="post" enctype="multipart/form-data">
                    {{form.as_p}}
                    <input type="submit" class="submit" name="submit" value="Ok" />
                </form>
            </div>
        </div>
    </div>
{% endblock %}

forms :

class NewsletterEmails(forms.Form):
    email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,maxlength=75)),label=_("email"))
like image 957
crivateos Avatar asked Jul 08 '10 02:07

crivateos


1 Answers

without redirecting anywhere means

  1. the form submission should not redirect (or)
  2. after submitting the form user should be redirected to the same page with the form.

in case-1 you can do this using jquery-ajax-forms

in case-2 after the post request redirect the user to the same page instead of redirecting to '/'

return HttpResponseRedirect('redirect/to/form/page')
like image 126
Ashok Avatar answered Oct 17 '22 05:10

Ashok