I have an UpdateView in Django.
I have just a normal submit button. When the object is updated correctly it redirects to an object list via success_url.
Can I make two different submit buttons: One button which submits and redirects to objects list page (ListView) and another button which submits and redirects to the object detail page (DetailView)?
I don't know how to do this in a smart way.
Since you're submitting to the same place, and only want to change the redirect destination after save, this is simple. Submit buttons are just like any other input controls in that they have a name and a value, and you receive these in the POST data. So, in your template you can have:
<input type="submit" name="list" value="Submit and go to list">
<input type="submit" name="detail" value="Submit and go to detail">
and in your view:
if form.is_valid():
form.save()
if 'list' in request.POST:
return redirect('list_url')
else:
return redirect('detail_url')
Related
There is a button in blog detail view that asks user to login to comment, but after login user is redirected to home page because in settings.py I declared:
LOGIN_REDIRECT_URL = "projects:home"
I searched and I found this could be a solution:
Please login to reply
but this even didn't work.
Thank You
You are half-way there: When you add ?next={{request.path}} to your a tag, you are creating a 'next' variable and assigning the current path to it. But that alone isn't enough for your desired result; you still need to actually use that variable in your login form.
You haven't shown us your login template, but I assume it's a basic form. Add a hidden button to the login form, and have it use the 'next' variable that was captured in your a tag. Put the following code inside your login form tag, after everything else, but before closing the the form:
<input type="hidden" name="next" value="{{ request.GET.next }}" />
When a user submits the Login form, the template will use the value stored in request.GET.next, which was captured from your a tag.
In one of the pages of my website i m trying to create two buttons save and delete. Save as the name suggests saves the data filled into form in my database. Delete deletes this data. I want to access these two buttons separately in my views.py file but the only way i know to detect user input is checking if request.method == 'POST'. But in the case of both the save and delete button POST request is going to be made. How can i differentiate between the click of delete and save button so that i can write different code for each?
Use the name tag in the button to differentiate between POST operations.
For example:
<button name="delete">Delete</button>
And use in condition in view:
if "delete" in request.POST:
Use two separated form, and submit them by ajax seems the easiest way.
view.py
Create 2 views. One for add/update data, and second one for delete data.
def submit_view(...):
if request.POST:
# add data (if form.is_valid, and more)
def delete_view(...):
if request.POST:
# delete data (if form.is_valid, and more)
template
Now add two separated forms in template, and submit them by using ajax.
<form action="/submit" id="submit_form">
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="button" value="submit" id="submit_button">
</form>
<form action="/delete" id="delete_form">
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="button" value="delete" id="delete_button">
</form>
<script>
$('#submit_button').on('click',function(){$('#submit_form').submit();});
$('#delete_button').on('click',function(){$('#delete_form').submit();});
</script>
I have a web page that I am looking to be able to modify dynamically with multiple post requests. basically there are two methods that the user can submit text to be uploaded into models; one is through a text input field and the other is through a file upload field. How do I set up my python conditionals to do this? I want to be able to differentiate between the two post request with if and statements. What is the differentiating variable that I should use to tell these two apart. My views.py so far has the text input working.
def homesite(request):
corpusitems = CorpusItem.objects.order_by('name')
if (request.method == 'POST'):
f = CorpusItemForm(request.POST)
if f.is_valid():
new_corpusitem = f.save()
return render(request, 'content.html', {'corpusitems': corpusitems})
Submit buttons in HTML have name and value properties. For example if you have:
<form>
<input type="submit" name="action" value="Send"/>
<input type="submit" name="action" value="Hello"/>
</form>
Then in Django you can distinguish the two submit actions by the value of action:
if request.POST['action'] == 'Send':
# do this
elif request.POST['action'] == 'Hello':
# do that
Heres the scenario:
I have a email subscriber/un-subscriber app. I am stuck up in the un-subscribing a user part. The user is given a link, which if he/she follows will be able to un-subscribe. The link is typically a view, in the following format:
r^'/unsub_view/(?P<user_id>\w+)/$'
So, when the user follows this links he/she is doing a GET request on the view unsub_view with a parameter user_id. So I have coded up my view as:
def unsub_view(request, user_id):
if request.method == 'GET':
### Do some DB lookup to determine if it is a valid user or not
if user_is_valid:
return direct_to_template(request, '/app/unsub.html', {'user': user})
Now when a valid user is doing the GET, a confirmation dialogue is shown, along with a button. If he/she clicks on the button, I want the template to post the 'user' to the same view, thus the unsub_view also has this piece of code:
if request.method == 'POST':
if user_is_subscribed:
#Unsubscribe the user.
else:
#Show error meessage.
My question is how can I have the button in my template to post to this view ? I have looked around but I got POST-ing to a .php or .asp
Please help.
Note: If there is a better workflow idea, I am also open to that, so please do suggest if there is one.
In the template unsub.html rendering the form with the button, you should pass the url of your view using the reverse method
from django.code.urlresolvers import reverse
def unsub_view(request, viewid):
if request.method == 'POST':
if user_is_subscribed:
#Unsubscribe the user.
submit_url = reverse('unsub_view', viewid)
return direct_to_template(request, '/app/unsub.html', {'user': user, 'submit_url'})
else:
#Show error meessage.
in your template you can then render the form like follows :
...
<form method='post' action='{{ submit_url }}'>
{% csrf_token %}
<input type="hidden" value="{{ user_id }}" name="user_id" />
<input type="submit" value="unsubscribe"/>
</form>
...
Django also has a full framework dedicated to form modeling and rendering. You could take advantage of that to generate the form.
I have a Django project that, on one page, has multiple forms (in different tags) that can be submitted to have different effects. In all cases I want the user to be redirected back to the same page, so I use in my view the pattern of submitting the form and then redirecting to the original page. In at least one case, the only difference between two of the forms is the value of the submit button.
In my view I have the code (which is the first time my view function accesses the request.POST):
if request.POST['submit']=='Add':
#code to deal with the "Add" form
and in the template, the first form has a submit button like
<input type="submit" value="Add">
I thought this would work, but when I submit that form, I get an error at the line in view from above:
Key 'submit' not found in <QueryDict: {u'clientyear': [u'2012'], u'csrfmiddlewaretoken': [u'be1f2f051f09f6ab0375fdf76cf6a4d7'], u'ben': [u'123405']}>
Obviously, this does not have a 'submit' key or any key with the value corresponding to the submit button I clicked. So, since this does not work, how can access the value of the submit button or tell which of the forms has been submitted?
Submit is an HTML Form structure... You must use name attribute of form objects as follows... In your template:
<form>
...
<input type="submit" name="list" value="List Objects" />
</form>
<form>
...
<input type="submit" name="do-something-else" value="Do Something Else" />
</form>
In your view:
if 'list' in request.POST:
# do some listing...
elif 'do-something-else' in request.POST:
# do something else
One thing to keep in mind to prevent confusion. The name of the submit button will not show if there is only a single button in the form.
#template.html
<form action="..." method="post">
<input type="submit" name = "first_button" value="Add">
</form>
#view.py
...
'first_button' in request.POST #False
#template.html
<form action="..." method="post">
<input type="submit" name = "first_button" value="Add">
<input type="submit" name = "second_button" value="Remove">
</form>
#view.py
...
'first_button' in request.POST #True if you clicked on that button
I'm little bit late but here is the solution
Problem you are facing
Your are trying to get Button name but getting the initial value of button that is not correct way.
HTML Code
<input type="submit" value="Add">
Python Code/View.py
if request.POST['submit']=='Add':
#code to deal with the "Add" form
Solution
First find button name in request.POST dictionary if exist then get their value.
HTML Code
Add name of your button and their value.
<input type="submit" value="Add" name="add_object">
Views.py
You can find the button name in request.POST dictionary
if request.POST['submit'] == 'add_object':
# Both ways to deal with it
if 'add_object' in request.POST:
Extra Stuff
We have two forms on a page.
First form have 2 buttons with same name subjects but different values fav_HTML and fav_CSS.
Second form also have 2 buttons with same name tutorials but different values
Tutorials_HTML and Tutorials_CSS.
<form action="" method="post">
Form 1
<button name="subject" type="submit" value="interview_HTML">HTML</button>
<button name="subject" type="submit" value="interview_CSS">CSS</button>
</form>
<form action="" method="post">
Form 2
<button name="tutorials" type="submit" value="Tutorials_HTML">HTML</button>
<button name="tutorials" type="submit" value="Tutorials_CSS">CSS</button>
</form>
views.py
We can handle different forms, check which button is clicked then getting their values and do something.
if 'subject' in request.POST: # this section handle subject form (1st Form)
#now we can check which button is clicked
# Form 1 is submitted , button value is subject now getting their value
if 'interview_HTML' == request.POST.get('subject'):
pass
# do something with interview_HTML button is clicked
elif 'interview_CSS' == request.POST.get('subject'):
pass
# do something with interview_CSS button is clicked
elif 'tutorials' in request.POST: #this section handle tutorials form (2nd form)
#now we can check which button is clicked
# Form 1 is submitted , button name is tutorials now getting their value
if 'Tutorials_HTML' == request.POST.get('tutorials'):
pass
# do something with fav_HTML button is clicked
elif 'Tutorials_CSS' == request.POST.get('tutorials'):
pass
# do something with fav_CSS button is clicked