Could not pass value in URL query string using Django and Python - python

I need to pass session id in URL query string after login using Django and Python but in my case I am getting some error. My code is below.
def loginsave(request):
"""This function helps to login the user """
if request.method == 'POST':
password = request.POST.get('pass')
uname = request.POST.get('uname')
per = User.objects.all().filter(
Q(password__icontains=password) & Q(uname__icontains=uname)).count()
if per > 0:
user = User.objects.filter(
Q(password__icontains=password) & Q(uname__icontains=uname))
for use in user:
uid = use.id
user_name = use.uname
request.session['id'] = uid
request.session['sess'] = dict(dt=str(datetime.now()),
value='session')
request.session['sess_id'] = 'abcd1234'
return render(request, 'bookingservice/home.html',
{'count': per, 'username': user_name})
else:
return render(request, 'bookingservice/login.html', {})
This is my login function here I am creating session id and I need to pass it over URL. My menu list is given below.
Home
Add Booking
Add Personal Info
I am doing like this but here I am getting the following error.
Exception Value:
Could not parse the remainder: '["sess_id"]' from 'request.session["sess_id"]'
Here I need after login the session id should come over every page URL.

Change
{{request.session["sess_id"]}}
to
{{ request.session.sess_id }}
usually the template language of django works this way. Here a dot in a variable name signifies a lookup.When the template system encounters a dot in a variable name, it tries the following lookups, in this order:
Dictionary lookup. Example: request.session["bar"]
Attribute lookup. Example: request.session.bar
List-index lookup. Example: request.session[bar]
You can find more at docs

You have an error in template, it should read (mind the quotes):
Home
Add Booking
Add Personal Info

Related

Pass a variable to another function and render an html template at the same time in django

We want to access the same variable in every function inside our views.py. Since it is not constant, we cannot use it as a global variable.
Is it possible to pass a variable to another function while also rendering an HTML template? What are the alternatives if none exist?
This is our login function in views.py
def loginpage(request):
errorMessage = ''
# Applicant Login
if request.method=="POST":
if request.POST.get('username') and request.POST.get('pwd'):
try:
currentUser=Applicant.objects.get(username=request.POST['username'],pwd=request.POST['pwd'])
currentUser=Applicant.objects.get(username=request.POST['username'])
first = currentUser.firstname
middle = currentUser.middleinitial
last = currentUser.lastname
AppDashboard = ApplicantDashboardPageView(currentUser, request)
except Applicant.DoesNotExist as e:
errorMessage = 'Invalid username/password!'
return render(request, 'home.html')
The currentUser variable inside our login function is the variable we want to pass in this function
def ApplicantdashboardPageView(currentUser, request):
appPeriod = ApplicationPeriod.objects.all()
exam = ExaminationSchedule.objects.all()
posts = Post.objects.all().order_by('-created_on')
form = PostForm()
name=userNaCurrent
print('from storeCurrentUser', name)
if request.method == "GET":
try:
posts = Post.objects.all().order_by('-created_on')
form = PostForm()
#applicantID=currentUser.id
#applicantNotification = Applicant.objects.get(id=applicantID)
return render(request, 'applicantdashboard.html', context={'UserName' : name, 'posts':posts, 'appPeriod':appPeriod, 'exam':exam})
except ObjectDoesNotExist:
return render(request, 'applicantdashboard.html', context={'UserName' : name, 'posts':posts,})
return render(request, 'applicantdashboard.html', context={'UserName' : name, 'posts':posts, 'appPeriod':appPeriod, 'exam':exam})
I am new to Django so please bear with me if my question seem too basic. Thank you
Store raw user password is a very big flaw in security. Please read more about Django Authentication system https://docs.djangoproject.com/en/4.1/topics/auth/
Basically, to store critical confidential information like passwords you need to at least, encrypt it. But for passwords you don't need to see the raw value of it, isn't it? Therefore, you just need to hash it and compare it every time you need to authenticate the user. Read more here Best way to store password in database
Django Auth system will also help to solve the issue by injecting the current user into a "global" request object so that you can access it everywhere.
You can do the same by keeping those 2 methods in a class and accessing variables by creating objects for it.

Checking whether element is in ManyToMany field in Django

Hi so I have an attend session button that when clicked adds the user to the session. I got it working but I want to add a check to see whether the user is already in the ManyToMany field of attendees before I add them. How would I go about doing that?
Here is my view for it
def attend_session(request):
session = Study.objects.get(pk=request.POST['session_id'])
stud = Student.objects.get(student_user=request.user)
if request.method == "POST":
# Add check here to see if student is already attending
session.attendees.add(stud)
session.save()
return HttpResponseRedirect(reverse('study:sessions'))
You can check with:
from django.shortcuts import get_object_or_404, redirect
def attend_session(request):
session = get_object_or_404(Study, pk=request.POST['session_id'])
stud = get_object_or_404(Student, student_user=request.user)
if request.method == 'POST':
if stud not in session.attendees.all():
session.attendees.add(stud)
return redirect('study:sessions')
Note: It is often better to use get_object_or_404(…) [Django-doc],
then to use .get(…) [Django-doc] directly. In case the object does not exists,
for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using
.get(…) will result in a HTTP 500 Server Error.
Note: You can make use of redirect(…) [Django-doc] instead
of first calling reverse(…) [Django] and
then wrap it in a HttpResponseRedirect object [Django-doc].
The redirect(…) function does not only offer a more convenient signature to do this, it also for example will use the
.get_absolute_url() method [Django-doc]
if you pass it a model object.

Using Tagging and Autopopulate with Flask

I am trying to wrap my head around how to use a tagging system with Flask and WTForms.
Basically I have a list of keywords. These keywords have a hierarchy (example: I select Chicago. Illinois and USA get automatically added as additional keywords).
So I'm trying to find a way for users to type into an autopopulating list. This form then produces the keywords and brings it back into flask, where each keyword is used as it's own variable.
With WTForms we need the "id" to bring back into Flask, but in a form like taggle.js or select2 how can we separate each tag into it's own id? Or are there better ways to go about this?
Flask
class ReusableForm(Form):
example4 = StringField('example4')
#app.route("/editor", methods=['GET', 'POST'])
def hello():
form = ReusableForm(request.form)
if request.method == 'POST':
example4 = request.form['example4']
if form.validate():
# Return and do something with each keyword
# tag1 = 'Alaska'
# tag2 = 'Hawaii'
# tag3 = 'California'
You need to use a dynamic form that will accept a variable number of tags being POSTed to Flask.
forms.py:
class TagForm(NoCsrfForm):
tag_id = IntegerField(widget=HiddenInput(), default=0)
tag_name = StringField(widget=HiddenInput(), [InputRequired(), Length(max=256)])
class MyDynamicForm(Form):
some_field = StringField('Foo', [InputRequired()])
some_other_field = TextAreaField('Bar', [InputRequired()])
some_tags = FieldList(FormField(TagForm))
views.py:
#app.route('/')
def index():
form = MyDynamicForm()
if form.validate_on_submit():
if len(form.some_tags.data) >= 1:
# Do something with the received tags.
pass
return render_template('index.html', form=form)
index.html
<input id="some_tags-0-tag_name"></input>
Each input id must use the following syntax: "[some_tags]-[nth tag]-[tag_name]". You should hopefully know best to create inputs and their ids taking into account the js frameworks you have available.
N.B. tag_id = IntegerField(widget=HiddenInput(), default=0) isn't necessary for receiving POSTed input but is useful if you store tags in a database and later want to populate the form with stored tags.

Using objects.get or objects.filter to obtain specific groups to use in form filter

I have created a form that due to segregation requirements needs me to prevent certain users from seeing certain results.
The form works perfectly, but I want to apply a filter that looks at the group of a user and filters the form contents based on the group the user belongs to.
views.py that renders the form with the filter.
def Overtime_Results(request):
employeeGroup = request.user.groups.get(name='Client1' or 'Client2' or 'Client3' or 'Client4')
overtime_data = Overtime.objects.filter(client=employeeGroup)
location = None
if request.method == 'POST':
form = OvertimeForm(data=request.POST)
if form.is_valid():
location = form.data['location']
overtimeid = Location.objects.all()
overtime_data = Overtime.objects.filter(location=location, client=employeeGroup)
else:
form = OvertimeForm()
template_name = "overtime/Overtime_Results.html"
context = {
'form': form,
'location': location,
'overtime_data': overtime_data,
}
return render(request, template_name, context)
This is the filter that checks whether the user belongs to a certain group.
employeeGroup = request.user.groups.get(name='Client1' or 'Client2' or 'Client3' or 'Client4')
I essentially want this to return whichever group the user belongs to, which will subsequently apply this to the forms filter later.
I've tried both filter, get with multiple methods. The above works, but only for Client1. Client2 and subsequentl clients don't work.
Edit: I think I need to use the equivalent to an 'in' statement in SQL. But, I can't seem to figure out how to do this.
The error I'm receiving right now is:
Group matching query does not exist.
When accessing the page with a user that has a valid group assigned that matches the query results.
How about this QuerySet API Field Lookups using "in".
request.user.groups.get(name__in=['Client1' ,'Client2' , 'Client3' , 'Client4'])
Your query boils down to:
request.user.groups.get(name='Client1')
This is because the result of:
'Client1' or 'Client2' or 'Client3' or 'Client4'
Will always be 'Client1'.
If you just want to get all the groups the current user belongs to:
user_groups = request.user.group_set.all()
If your user can only belong to one group, then use:
user_group = request.user.group

python-flask db.session.commit() is not working

The problem is when user tries 'forgot password' option. It creates new reset_key for verification, but the new key is not getting updated into DB.
#app.route('/login/forgot/', methods=['GET', 'POST'])
def forgot():
form = ResetLoginForm(request.form)
#There's no session yet. User just pointing to /login/forgot url.
if request.method == 'POST' and form.validate():
user = User.query.filter_by(email=form.email.data).first()
if not user:
flash('The username or email incorrect')
return render_template('forgot.html', form=form)
reset_key = generate_key() ## this creates a new key, but how update this key into db?
#tried something like
user.reset_key = reset_key
db.session.add(user)
db.session.commit()
#this is not working. Is it due to session is not started or something?
Thanks for any help or hint.
This is because User.query.filter_by(email=form.email.data).first() will return a sqlalchemy.orm.query.Query object. As its doc says:
Query is the source of all SELECT statements generated by the ORM,
both those formulated by end-user query operations as well as by high
level internal operations such as related collection loading. It
features a generative interface whereby successive calls return a new
Query object, a copy of the former with additional criteria and
options associated with it.
So you just get a copied object, so your change will not work;
You can use like this:
user = db.session.query(User).filter_by(email==form.email.data).first()
and then you can change user attrs
user = db.session.query(User).first() solved problem.

Categories