6

I have a link that when clicked, should submit a form that contains an invisible field via a post request. I then should be able to get the field value like:

var = request.POST.get('name_of_var', '')

After looking at a few posts, I can't seem to get this to work. This is what I have so far:

<form id="form-id" method="post">
    <li> 
        <input type="hidden" value="{{ obj }}" name="name_of_var">
        <a href="/activities" onclick="document.getElementById('form-id').submit();"> {{obj}} </a>
    </li>
</form>

In my view I have something like this, but a POST request is never triggered. What could be the issue here?:

if request.POST:
        var = request.POST.get('name_of_var', '')
        return render_to_response('activities/display_activities.html', var)

EDIT: Here is my views.py:

def index(request):
    if request.method == "POST":
        var = request.POST.get('name_of_var', '')
        return render_to_response('activities/display_activities.html', var)

    category1 = Service.objects.filter(category = 'Sports')
    category2 = Service.objects.filter(category = 'Dance')
    category3 = Service.objects.filter(category = 'Music')
    category4 = Service.objects.filter(category = 'Academics')
    category5 = Service.objects.filter(category = 'Art')
    category6 = Service.objects.filter(category = 'College')

    subcat1 = []
    subcat2 = []
    subcat3 = []
    subcat4 = []
    subcat5 = []
    subcat6 = []

    for obj in category1:
        subcat1.append(obj.subcategory)
    subcat1 = list(set(subcat1)) 

    for obj in category2:
        subcat2.append(obj.subcategory)
    subcat2 = list(set(subcat2)) 

    for obj in category3:
        subcat3.append(obj.subcategory)
    subcat3 = list(set(subcat3)) 

    for obj in category4:
        subcat4.append(obj.subcategory)
    subcat4 = list(set(subcat4)) 

    for obj in category5:
        subcat5.append(obj.subcategory)
    subcat5 = list(set(subcat5)) 

    for obj in category6:
        subcat6.append(obj.subcategory)
    subcat6 = list(set(subcat6)) 

    return render_to_response('activities/activities.html', {'user': request.user,  
        'category1':category1, 'category2':category2, 'category3':category3, 
        'category4':category4, 'category5':category5, 'category6':category6,  
        'subcat1':subcat1,'subcat2':subcat2, 'subcat3':subcat3, 
        'subcat4':subcat4, 'subcat5':subcat5,'subcat6':subcat6  })
Michael Smith
  • 3,307
  • 5
  • 25
  • 43

4 Answers4

5

This is how I ended up resolving this. Below is an example that is completely different from my original post. Note: replace the id and action with your relevant code. In my example, {{form4}} is passed in through the view and is a custom form in my forms.py with one field.

<form id = "form-id" action="/events/attending" method="post">{% csrf_token %}
    <a href="#" onclick="document.forms['form-id'].submit();" >  Submit </a> 
    {{form4.going}} I am attending this event!
</form>
Michael Smith
  • 3,307
  • 5
  • 25
  • 43
2

You should use <a> like this to prevent auto jump:

<a href="javascript:void(0);" onclick="document.getElementById('form-id').submit();"> {{obj}} </a>

This assume that you submit the form to the current url, if you want to submit to to some other url I suggest you use jquery instead of <a> like this:

<form id="form-id" method="post">
<li>
    <input type="hidden" value=" obj " name="name_of_var">
    <a id="sub" href="javascript:void(0);" onclick="document.getElementById('form-id').submit();"> tttttttttt</a>
</li>

<script type="text/javascript">
$(document).delegate("#sub", "click", function () {
    $.ajax({
        type: "POST",
        url: "/your/url/",
        data: {name_of_var: value_of_var},
        dataType: "json",
        success: function () {
            //do something
        }
    })
});

shellbye
  • 4,620
  • 4
  • 32
  • 44
1

You should check for a POST in this way:

if request.method == "POST":     # this will tell you if you are actually receiving a POST
    ...

instead of this:

if request.POST:                 # not reliable
    ...

See the docs for why this is the case.

Justin O Barber
  • 11,291
  • 2
  • 40
  • 45
  • This actually didn't solve my question. I mistakenly had the form redirect to the wrong view -- so it made it look like it worked at first glance-- and the POST request doesn't get sent. I am still unable to access the variable in the hidden field. Sorry for the confusion! – Michael Smith Dec 16 '14 at 03:30
  • Does the `POST` come through when you check for it? Or is it coming through as a `GET`? – Justin O Barber Dec 16 '14 at 03:34
  • I dont think it's coming through. It never reaches the if statement. I updated the question again so that the code mirrors exactly what I have. Thanks again – Michael Smith Dec 16 '14 at 03:37
  • Try adding `print request.method` right before you check `request.method` to see if it is `POST`. – Justin O Barber Dec 16 '14 at 03:39
  • I made the chnges including the print. The console reads that it's a GET – Michael Smith Dec 16 '14 at 03:41
  • Yes, it's a GET request – Michael Smith Dec 16 '14 at 03:43
  • Still a Get. Right now I have it so that it returns to the same page the href is in /activities. Then it renders the display_activities.html when the view reads a POST request. Is this a bad approach? – Michael Smith Dec 16 '14 at 03:54
  • I'm not sure I completely understand. Why aren't you using a submit button? The issue may be with the link with javascript. – Justin O Barber Dec 16 '14 at 03:59
  • I would like to submit data upon the user clicking a link. That data is the name of the subcategory. I've heard that it is possible to do this, but I'm not quite sure how to do this in Django. – Michael Smith Dec 16 '14 at 04:03
  • I'll take a look and report when I find a solution. I'll probably make a simple django test project and try to submit a post request with an href. You've spent enough time helping me :) Thanks for the help. – Michael Smith Dec 16 '14 at 04:10
  • Sorry I couldn't be of more use. I don't have a django instance on this machine. – Justin O Barber Dec 16 '14 at 04:11
0

Given the lack of details, Im thinking that your request never get triggered most likely due to the missing trailing white slash at the end of your href ( assuming you are posting to that url). It is good practice to have trailing white slashes for post request!

Your code :

<a href="/activities/view" onclick="document.getElementById('form-id').submit();"> {{obj}} </a>

Should be

<a href="/activities/view/" onclick="document.getElementById('form-id').submit();"> {{obj}} </a>
#                        ^ Note the trailing slash!

Let me know if that works for you

Cheers, Biobirdman

Cody Piersall
  • 8,312
  • 2
  • 43
  • 57
biobirdman
  • 4,060
  • 1
  • 17
  • 15