views:

78

answers:

1

I'm writing a Django admin action to mass e-mail contacts. The action is defined as follows:

def email_selected(self,request,queryset):
    rep_list = [] 
    for each in queryset:

        reps = CorporatePerson.objects.filter(company_id = Company.objects.get(name=each.name))

        contact_reps = reps.filter(is_contact=True)
        for rep in contact_reps:
            rep_list.append(rep)

    return email_form(request,queryset,rep_list)

email_form exists as a view and fills a template with this code:

def email_form(request,queryset,rep_list):
    if request.method == 'POST':
        form = EmailForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            send_mail(
                cd['subject'],
                cd['message'],
                cd.get('email','noreply@localboast'),['[email protected]'],
            )
            return HttpResponseRedirect('thanks')
        else:
            form = EmailForm()
        return render_to_response('corpware/admin/email-form.html',{'form':form,})

and the template exists as follows:

<body>
    <form action="/process_mail/" method="post">
        <table>
            {{ form.as_table }}
        </table>
        <input type = "submit" value = "Submit">
    </form>
</body>

/process_mail/ is hardlinked to another view in urls.py - which is a problem. I'd really like it so that I don't have to use <form action="/process_mail/" method="post"> but unfortunately I can't seem to POST the user inputs to the view handler without the admin interface for the model being reloaded in it's place (When I hit the submit button with , the administration interface appears, which I don't want.)

Is there a way that I could make the form POST to itself (<form action="" method="post">) so that I can handle inputs received in email_form? Trying to handle inputs with extraneous URLs and unneeded functions bothers me, as I'm hardcoding URLs to work with the code.

+1  A: 

You can use django's inbuilt url tag to avoid hardcoding links. see...

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url

Chances are you'd be better off setting up a mass mailer to be triggered off by a cron job rather than on the post.

Check out the answer I posted here http://stackoverflow.com/questions/1534268/django-scheduled-jobs/1534675#1534675

Also if you insist on triggering the email_send function on a view update perhaps look at

http://docs.djangoproject.com/en/dev/topics/signals/

michael