Failure in multiple times Parameters Passing in Django (Python) - python

I am new to django. My current plan is displaying user name on different html pages, once user have successfully logged in. At the moment, the page after login page can successfully display the user name with the django tag in html which is {{ username }}. But once it has successfully passed to my second page, my second page CAN NOT pass it to my third page. The attached images are my html codes for second.html and third.html. Thanks for your help.
Second.html
<form action="/SecondPageSub/" method="POST">
{% csrf_token %}<br>
<b>NTID:</b><br>
<label name="usrnm">{{username}}</label>
<button type="submit" name="SecondPageSub">
SUBMIT
</button>
</form>
Third.html
<form action="/ThirdPageSub/" method="POST">
{% csrf_token %}<br>
<b>NTID:</b><br>
<label name="usrnm">{{username}}</label>
<button type="submit" name="ThirdPageSub">
SUBMIT
</button>
</form>
Python codes in view.py
def ActionGet(request):
if request.method == "POST":
if 'login' in request.POST:
usrname = request.POST.get("usrnm", None)
passwrd = request.POST.get("pwd", None)
dic={}
dic['username']=usrname
dic['password']=passwrd
return render(request, "Second.html",dic)
if 'SecondPageSub' in request.POST:
usrname = request.POST.get("usrnm", None)
dic={}
dic['username']=usrname
return render(request, "Third.html",dic)
if 'ThirdPageSub' in request.POST:
usrname = request.POST.get("usrnm", None)
dic={}
dic['username']=usrname
return render(request, "Forth.html",dic)

by default django gives you {{ request.user.username }} through out your templates. So you can call it on any templates

You aren't passing the usrnm in your post request with SUBMIT on your SecondPageSub

Related

Django problem with form using action and not the if method == post in the view

So i am trying to add a value to the session dictionary because i wanted to make a cart/checkout for guests.
This is the code in my views.py
def productdetail(request, pk):
Decks = decks.objects.get(id=pk)
if request.method == 'POST':
form = order(request.POST)
if form.is_valid():
request.session['cart'] = [pk]
else:
form = order()
return render(request, 'shop/single_product.html', {'deck': Decks, 'form': form})
And the code in my html
<form action="{% url 'productdetailcart' deck.id%}" method="post">
{% csrf_token %}
{{ form }}
<input class="btn btn-lg btn-block btn-round btn-b" type="submit" value="Add To Cart">
Now my problem is that without the action in the form tag the session['cart'] in the views.py adds the value in the session which is what i want. But if i have the action to go to that url i only go to the url without adding the pk to the session['cart'] . Its like im forced to choose between going to the page or saving to session.

how to get username from login form, when reset password link is clicked django

I am trying to get the username from my login form when the reset password link has been pressed.
view.py
def ResetPassword(request):
if request.method == 'POST':
username = request.Post.get['login_username']
if username:
#send password reset link via email
else:
#if username is empty search for your account
return render(request, 'accounts/forms/email_search.html',{})
forms.html
<form class="navbar-form navbar" method="POST"action="{% url 'login' %}">
{% csrf_token %}
<div class="form-group">
{{ form.login_username }}
</div>
<div class="form-group">
{{ form.login_password }}
</div>
<button type="submit" id="loginBtn" class="btn btn-default">Submit</button>
<br>
Reset Password
</form>
First of all, the request object has not attribute Post, but POST.
So, it should be either
# use this if you're sure that login_username will always be passed
`username = request.POST['login_username']`
or
# use this and in case login_username fails, then an empty string is returned
`username = request.POST.get('login_username', '')`.
Now, to your problem. The form has a submit input only for the login view. The change password button is just a plain link. Thus, when you click on it you make a GET request to the ResetPassword view (by the way, you should rename it to reset_password, it's the Python way), without any arguments passed.
To fix this, you must remove this link from inside the form.
Then you have to create the template for the ResetPassword view, say reset_password.html and inside there create another form (with only the username field required) that will POST to ResetPassword view.
For example:
<!-- reset_password.html -->
<form class="navbar-form navbar" method="POST" action="{% url 'ResetPassword' %}">{% csrf_token %}
<div class="form-group">
<input type="text" name="login_username" required />
</div>
<button type="submit" id="reset-pwd-btn" class="btn btn-default">Reset Password</button>
</form>
And last:
# ResetPassword.py
def ResetPassword(request):
if request.method == 'POST':
# login_username is the same as the input's name
username = request.POST.get('login_username')
if username:
# send password reset link via email
else:
# if username is empty search for your account
return render(request, 'accounts/forms/email_search.html', {})
return render(request, 'accounts/forms/reset_password.html', {})

Django view is not redirecting properly

I'm facing some difficulties to render pages with Django shortcuts. My workflow is quite simple:
Users go a page where they can view some project data (detail_project)
If they want to update the project data, they should click a button that will send a POST request and loads update_project page. This page is loaded with current project data.
Users update and submit new data. After submission, they are returned to detail_project page.
My view is like this:
def update_project(request):
if request.method == 'POST':
if 'update_project_submit' in request.POST:
# updates project with form data and returns to detail project page
return redirect('detail_project', project_name=project_name)
else:
# loads project original data into the form
return render(request, 'project/update_project.html', context)
def detail_project(request, project_name):
if request.method == 'POST':
if 'update_project' in request.POST:
return update_project(request)
else:
# does another stuff
else:
# shows project details
return render(request, 'project/detail_project.html', context)
urls.py:
url(r'^project/update/$', views.update_project, name='update_project'),
url(r'^project/details/(?P<project_name>[a-zA-Z][a-zA-Z0-9-_]+)/$', views.detail_project, name='detail_project'),
And update_project.html:
<form class="form-horizontal" role="form" action="" method="post">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<div class="col-sm-3">
<label for="{{ field.id_for_label }}" class="control-label">{{ field.label }}</label>
</div>
<div class="col-sm-9">
{{field}}
</div>
<div class="col-sm-12">
{{ field.help_text }}
</div>
</div>
{{field.non_field_errors }}
{{field.errors}}
{% endfor %}
<button type="submit" name="update_project_submit" class="btn btn-primary">Submit</button>
</form>
[ Update ]
Forms.py
class UpdateProjectForm(forms.Form):
project_name_validator = RegexValidator(r'^[a-zA-Z][a-zA-Z0-9-_]{1,31}$', constants.PROJECT_NAME_INVALID)
project_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'required': 'true'}), validators=[project_name_validator])
project_description = forms.CharField(required=True, widget=forms.Textarea(attrs={'style':'resize:none;', 'required': 'true'}))
project_expiration = forms.DateField(required=False, widget=forms.TextInput(attrs={'class':'datepicker'}))
def __init__(self, *args, **kwargs):
super(UpdateProjectForm, self).__init__(*args, **kwargs)
self.fields['project_name'].label = "Project Name:"
self.fields['project_description'].label = "Project Description:"
self.fields['project_expiration'].label = "Expiration Date:"
The problem is that I cannot update my project. My page loads the form properly (update_project) with the current data (step 2), but when I submit it (click the Submit button, I'm redirected to detail project page without entering the if 'update_project_submit' in request.POST: statement. Maybe my workflow is wrong. I cannot figure it out.
I printed my request, and I've really cofirmed that when I submit the form, I'm receiving a POST request to detail_project.
Is there something I am missing? Or am I trying to do something wrong according to Django's logic?
Use
if request.POST.get('update_project_submit', False):
instead of
if 'update_project_submit' in request.POST:

How to show confirmation modal in Flask app after form submission?

I'm trying to show a confirmation/success message to the user in my Flask app, but I can't figure out how to display it in a modal.
#app.route("/", methods=["POST"]
def sendForm():
form = ContactForm(request.form)
if request.method == 'POST':
if form.validate():
# do stuff with form data
return render_template("contact.html", form=form)
else:
# display error message
else:
return render_template("index.html")
The part where I return the contact.html template is where I need help, I think. Because that page is basically refreshed and shown again after the POST request successfully completes. Need to display a confirm message to the user in a modal instead.
On the front-end, my form is looks like this:
<form method="POST" action="{{ url_for('sendForm') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
{{ render_field(form.email) }}
{{ render_field(form.name) }}
<input id="submit-form" type="submit" value="Send">
</form>
I would do some form of this...
Pass a boolean in your render_template:
submission_successful = True #or False. you can determine this.
render_template("contact.html", form=form, submission_successful=submission_successful))
Then in your template place an if statement
{% if submission_successful %}
// modal elements here
{% endif %}

Django/Python: How to pass a variable from a form to a python script with POST method?

I'm getting this error when submit:
CSRF verification failed. Request aborted.
I've got this far following the documentation, but I don't fully understand it and it's definitely wrong. I just want to take a query word from my search box(form) and pass it to a python script as an argument. I'm new to Django and getting stuck on the easiest things.
In models.py:
class QueryForm(forms.Form):
query = forms.CharField(label='query',max_length=100)
I added this line to my urls.py
url(r'^results/$', 'tweemo.views.results'),
On my homepage where my search box is I have this code for my form:
<form action="/home/results/" method="post">
<label for="query">Search:</label>
<input id="query" type="text" name="query" value="{{ current_query }}">
<input type="submit" value="ok">
</form>
In views.py I added these two functions:
def get_query(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.isvalid():
return HttpResponseRedirect('/thanks/')
else:
form = QueryForm()
return render(request, 'results.html', {'form': form})
def results(request):
return render_to_response('results.html',{'here':TwitterStream.objects.all() })
MY results.html contains just this:
<form action="/home/results/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit"/>
</form>
You must just add the {% csrf_token %} tag inside EVERY <form></form> tag which has method to be post in your template.
So the below markup should be corrected:
<form action="/home/results/" method="post">
{% csrf_token %}
<label for="query">Search:</label>
<input id="query" type="text" name="query" value="{{ current_query }}">
<input type="submit" value="ok">
</form>
Well the problem is that you are not passing the csrf token to the form , you need to pass the csrf token to the render function in order for it to be applied in the form . To accomplish this you need to associate the csrf token to the request.
def get_query(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.isvalid():
return HttpResponseRedirect('/thanks/')
else:
form = QueryForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('results.html', args)
def results(request):
return render_to_response('results.html',{'here':TwitterStream.objects.all() })

Categories