URL after successful logging in Django - python

I have different type of users each with different template.How can I change my URL to
url(r'^something/$', views.login_user, name='login_user'),
from
url(r'^$', views.login_user, name='login_user'),
when logged in.
my views
if user is not None:
if user.is_active:
login(request, user)
if user.groups.filter(name='hod').exists():
return render(request, 'retest/hod.html', {})
elif user.groups.filter(name='principal').exists():
return render(request, 'retest/principal.html', {})
elif user.groups.filter(name='Rep').exists():
return render(request, 'retest/home.html', {})
elif user.groups.filter(name='Ajithzen').exists():
return render(request, 'event/ajithzen.html', {})
elif user.groups.filter(name='graphics').exists():
return render(request, 'event/ashok.html', {})
elif user.groups.filter(name='Event_incharge').exists():
return render(request, 'event/incharge.html', {})
elif user.groups.filter(name='Event_coord').exists():
return render(request, 'event/chair.html', {})
elif user.groups.filter(name='IEEE').exists():
return render(request, 'event/ieee.html', {})
else:
return render(request, 'retest/login.html', {'error_message': 'Invalid login'})
else:
return render(request, 'retest/login.html', {'error_message': 'Your account has been disabled'})
else:
return render(request, 'retest/login.html', {'error_message': 'Invalid login'})
return render(request, 'retest/login.html')
urls.py
url(r'^$', views.login_user, name='login_user'),

You might want something like this in your views:
# views.py
def login_user(request):
if user is not None:
if user.is_active:
login(request, user)
# you have to include a function to retrieve the group that this user belongs to
...
# then, for example if the user belongs to 'hod'
user_group = 'hod' # for example
# use a dictionary of URL names
urls = {
"hod": "user_hod", # this is just an example, you can use any url name of your preference, more about the url names below
"principal": "user_principal",
"Rep" : "user_Rep"
"Ajithzen" : "user_Ajithzen"
"graphics" : "user_graphics"
"Event_incharge" : "user_Event_incharge"
"Event_coord" : "user_Event_coord"
"IEEE": "user_IEEE"
}
# retrieve the url name
url = urls[user_group] # so if user_group was 'hod', you'd get 'user_hod' here
return redirect(url)
else:
return render(request, 'retest/login.html', {'error_message': 'Your account has been disabled'})
else:
return render(request, 'retest/login.html', {'error_message': 'Invalid login'})
return render(request, 'retest/login.html')
def hod_user(request):
return render(request, 'retest/hod.html', {})
def principal_user(request):
return render(request, 'retest/principal.html', {})
def Rep_user(request):
return render(request, 'retest/home.html', {})
def Ajithzen_user(request):
return render(request, 'event/ajithzen.html',{})
def graphics_user(request):
return render(request, 'event/ashok.html',{})
def Event_incharge_user(request):
return render(request, 'event/incharge.html',{})
def Event_coord_user(request):
return render(request, 'event/chair.html',{})
def IEEE_user(request):
return render(request, 'event/ieee.html',{})
The idea here is that your login_user function will authenticate the user, and check the user's group. Based on this group, the function will redirect the user to his/her respective url, using the reverse() method. More about reverse and url names here.
More about redirect here.
Then in your urls.py:
# urls.py
urlpatterns = [
url(r'^login/$', views.login_user, name='login_user'),
# all your URLs for the different groups
url(r'^user/hod/$', views.hod_user, name='user_hod'),
url(r'^user/principal$', views.principal_user, name='user_principal'),
url(r'^user/Rep/$', views.Rep_user, name='user_Rep'),
url(r'^user/Ajithzen$', views.Ajithzen_user, name='user_Ajithzen'),
url(r'^user/graphics/$', views.graphics_user, name='user_graphics'),
url(r'^user/Event_incharge$', views.Event_incharge_user, name='user_Event_incharge'),
url(r'^user/Event_coord/$', views.Event_coord_user, name='user_Event_coord'),
url(r'^user/IEEE$', views.IEEE_user, name='user_IEEE'),
...
]
Here, we have URLs that map each URL to their own view - so each user group should have their own view in your views.py which you can create yourself. Generally, here you can think of your login_user as a way to route your users to their respective pages.

Related

Getting NoReverseMatch error when trying to redirect user after form upload

I am getting the error NoReverseMatch in Django when I try to redirect the user to a new URL after processing a form upload and successfully saving the form.
Here is my views.py
#login_required
def profile(request):
if request.method == 'POST':
profile_form = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile)
files = request.FILES.getlist('resume')
resumes_data = []
if profile_form.is_valid():
for file in files:
try:
# saving the file
resume = profile_form.cleaned_data['resume']
parser = ResumeParser(file.temporary_file_path())
data = parser.get_extracted_data()
resumes_data.append(data)
profile_form.instance.name = data.get('name')
profile_form.instance.email = data.get('email')
profile_form.instance.mobile_number = data.get('mobile_number')
if data.get('degree') is not None:
profile_form.instance.education = ', '.join(data.get('degree'))
else:
profile_form.instance.education = None
profile_form.instance.company_names = data.get('company_names')
profile_form.instance.college_name = data.get('college_name')
profile_form.instance.designation = data.get('designation')
profile_form.instance.total_experience = data.get('total_experience')
if data.get('skills') is not None:
profile_form.instance.skills = ', '.join(data.get('skills'))
else:
profile_form.instance.skills = None
if data.get('experience') is not None:
profile_form.instance.experience = ', '.join(data.get('experience'))
else:
profile_form.instance.experience = None
profile_form.save()
return redirect('users-profile')
except IntegrityError:
messages.warning(request, 'Duplicate resume found')
return redirect('users-profile')
profile_form.save()
messages.success(request, 'Your profile is updated successfully')
# return redirect(reverse('userprofile', kwargs={"id": request.user}))
return redirect('userprofile')
else:
profile_form = UpdateProfileForm(instance=request.user.profile)
return render(request, 'user/resumeprofile.html', {'profile_form': profile_form})
#login_required
def myprofile(request, user_id):
profile = Profile.objects.get(id=user_id)
context = {'profile':profile}
return render(request, 'user/profile.html', context)
And here is my urls.py:
urlpatterns = [
path('', jobs_views.home, name='home'), #this is home function inside the views.py in the jobs folder
path('contact',jobs_views.contact, name='contact'),
# path('jobs/', jobs_views.job_list, name='job-list'),
path('jobs/<slug:slug>', jobs_views.job_detail, name='job_detail'), #slug will help us identify the specific instance of job
path('jobs-search/', jobs_views.job_search, name='job_search'),
path('profile/', jobs_views.profile, name='users-profile'),
path('userprofile/<int:user_id>',jobs_views.myprofile, name='userprofile')
]
The error occurs when I redirect the user to userprofile but I don't get any error when I redirect them to users-profile. Attached is a screenshot of the error message displayed. The Screenshot of the error
Any help will be highly appreciated.
You can go around it by just taking the user id from the request since they are required to be logged in.
In your urls.py paths, change the path userprofile to :
path('userprofile/',jobs_views.myprofile, name='userprofile') # remove id parameter
Then in your myprofile view, change to:
#login_required
def myprofile(request):
user_id = request.user.id
profile = Profile.objects.get(id=user_id)
context = {'profile':profile}
return render(request, 'user/profile.html', context)

How to pass field from submitted form into url in Django?

I am trying to submit a form, save to database and then show the cleaned_data on a new url. In the form I have a field called job_number. I would like to send the cleaned_data over to 127.0.0.1:8000/quotes/job_number
quote/views.py:
#login_required
def quote_view(request):
data_form = QuoteInformationForm()
if request.method == "POST":
data_form = QuoteInformationForm(request.POST)
if data_form.is_valid():
data_form.save(commit=True)
return redirect('quote')
else:
print('Error')
return render(request, "index.html", {'data_form': data_form})
#login_required
def submitted_quote(request):
return render(request, "quote.html")
urls.py:
urlpatterns = [
path('home/', quote_view, name='home'),
path('quote/', submitted_quote, name='quote'),
Currently all this does is open the form at http://127.0.0.1:8000/home/ using index.html. When I submit it will send the info to the database and redirect me to http://127.0.0.1:8000/quotes. This is fine. Now I just need to show the cleaned data on this url and change the url to include the job_number at the end. How can I do this?
you need to change url pattern like this:
urlpatterns = [
path('home/', quote_view, name='home'),
path('quote/<int:job_number>/', submitted_quote, name='quote'),
]
and submitted_quotes():
#login_required
def submitted_quote(request,job_number):
job = # Get Your job
return render(request, "quote.html", {"job":job})
and :
#login_required
def quote_view(request):
data_form = QuoteInformationForm()
if request.method == "POST":
data_form = QuoteInformationForm(request.POST)
if data_form.is_valid():
data_form.save(commit=True)
return redirect('quote{}'.format(data_form.id))
else:
print('Error')
return render(request, "index.html", {'data_form': data_form})

ValueError in Django Python Forum application

I'm trying to create a form where users can add a new topic within a category. Then the users will be able to comment on each topic. Everything was working up until I tried adding the form page for new_topic
The error I receive:
ValueError at /new_topic/
The view speak_space.views.new_topic didn't return an HttpResponse object. It returned None instead.
Heres the code for my view.py and urls.py files:
view.py
from django.shortcuts import render, redirect
from .models import Category
from .models import Topic
from .forms import TopicForm
def index(request):
"""The home page for speak_space"""
return render(request, 'speak_space/index.html')
def categories(request):
"""Show all categories."""
categories = Category.objects.order_by('date_added')
context = {'categories': categories}
return render(request, 'speak_space/categories.html', context)
def category(request, category_id):
"""Show a single category(tribe) and all of its topics(convos)."""
category = Category.objects.get(id=category_id)
topics = category.topic_set.order_by('-date_added')
context = {'category': category, 'topics': topics}
return render(request, 'speak_space/category.html', context)
def topics(request):
"""Show all topics within a category(tribe)."""
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request, 'speak_space/topics.html', context)
def topic(request, topic_id):
"""Show a single topic(convo/post) and all of it's replies."""
topic = Topic.objects.get(id=topic_id)
entries = topic.entry_set.order_by('-date_added')
context = {'topic': topic, 'entries': entries}
return render(request, 'speak_space/topic.html', context)
def new_topic(request):
"""Add a new conversation topic."""
if request.method != 'POST':
# No data submitted; create a blank form.
form = TopicForm()
else:
# POST data submitted; process data.
form = TopicForm(data=request.POST)
if form.is_valid():
form.save()
return redirect('speak_space:topics')
# Display a blank or invalid form.
context = {'form': form}
return render(request, 'speak_space/new_topic.html', context)
and heres my url file:
from django.urls import path
from . import views
app_name = 'speak_space'
urlpatterns = [
# Home page
path('', views.index, name='index'),
# Page that shows all categories
path('categories/', views.categories, name='categories'),
# Profile page for a category
path('categories/<int:category_id>/', views.category, name='category'),
# Page that shows all topics.
path('topics/', views.topics, name='topics'),
# Detail page for a single topic(conversation)
# Where you go after you click on someones post
path('topics/<int:topic_id>/', views.topic, name='topic'),
# Page for adding a new conversation topic
path('new_topic/', views.new_topic, name='new_topic'),
]
and my forms page:
from django import forms
from .models import Topic
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['text']
labels = {'text': ''}
Your new_topic view doesn't return anything in case of GET request. You shoud make return statement common:
def new_topic(request):
"""Add a new conversation topic."""
if request.method != 'POST':
# No data submitted; create a blank form.
form = TopicForm()
else:
# POST data submitted; process data.
form = TopicForm(data=request.POST)
if form.is_valid():
form.save()
return redirect('speak_space:topics')
# The changes are here, now return will work for all requests types POST and GET
context = {'form': form}
return render(request, 'speak_space/new_topic.html', context)
Deindent the following lines
# Display a blank or invalid form.
context = {'form': form}
return render(request, 'speak_space/new_topic.html', context)
inside your new_topic method.

How do I pass a dictionary from one view to another in Django using session?

I have used session to pass dict from one view to another. But it shows this error. I want to create multiple templates submit form.
my views.py
def view_qr_code(request, *args, **kwargs):
# here i wanna retrive session data
context = {
'code': 'qrcode'
}
return render(request, 'add_send_product.html', context)
def send_product_add(request):
form = SendProductForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
instance = form.save(commit=False)
data_dict = instance.__dict__
print data_dict
request.session['s'] = data_dict
return redirect('/qr-code/')
else:
messages.error(request, "Form is not valid")
context = {
'form': form,
'headline': 'Delivery Item'
}
return render(request, 'add_send_product.html', context)
urls.py
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^send-product/add/$', views.send_product_add, name='add_send_product'),
url(r'^qr-code/$', views.view_qr_code, name='qr_code'),
]
Don't serialize the model instance. Serialize the form's cleaned_data.
(I'm not sure what you are doing here, since you never save the instance anyway. If you did, I would say that you should just store the ID of the newly-created instance in the session.)
As you don't want to save data in send_product_add() method so you just store request.POST data in your session variable
def view_qr_code(request, *args, **kwargs):
# here i wanna retrive session data
data_dict = request.session.get('saved')
del data_dict['csrfmiddlewaretoken'] # middleware is not same here so
context = {
'code': 'qrcode'
}
return render(request, 'add_send_product.html', context)
def send_product_add(request):
form = SendProductForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
request.session['saved'] = request.POST
return redirect('/qr-code/')
else:
messages.error(request, "Form is not valid")
context = {
'form': form,
'headline': 'Delivery Item'
}
return render(request, 'add_send_product.html', context)

How to pass in variables with a redirect?

So I have a signup on my base.html, then the form redirects to a signup page.
def signIn(request):
if request.user.is_authenticated():
context = {
"extendVar":"baseLoggedIn.html",
}
return HttpResponseRedirect("out")
if request.user.is_authenticated()==False:
# form=SignUpForm(request.POST or None)
if request.method=="POST":
email=request.POST.get('email','')
password = request.POST.get('password','')
user = auth.authenticate(username=email,password=password)
print(email)
print(password)
print(user)
if user is not None:
print("notNone")
auth.login(request,user)
return HttpResponseRedirect("out")
else:
print("None quàlol")
context={
"failure":"Password and e-mail did not match",
}
return HttpResponseRedirect("out") #redirects to base.html
context = {
"extendVar":"baseNotLoggedIn.html",
}
return render(request, "base.html",context)
the only problem is, when I do this, it redirects to the home page, but the home page doesn't have any errors, and I can't figure out a way to display the error that the password + email did not match, since i'm redirecting.
You need to pass your message as part of context, and your HttpResponseRedirect does not take any context as a parameter, so you need to return render(request, "base.html", context) instead of HttpResponseRedirect. Then you can access the "failure" key from context.
Also, keep your code clean!
def sign_in(request):
if request.user.is_authenticated():
context = {
"extendVar":"baseLoggedIn.html",
}
return HttpResponseRedirect("out")
else:
if request.method == "POST":
form = SignUpForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = auth.authenticate(username=email, password=password)
print(email)
print(password)
print(user)
if user:
print("notNone")
auth.login(request, user)
return HttpResponseRedirect("out")
else:
print("None quàlol")
context={
"failure":"Password and e-mail did not match",
}
return render(request, "base.html", context)
else: # form invalid, pass as variable back to user with form errors
return render(request, "base.html", {'form': form}
context = {
"extendVar":"baseNotLoggedIn.html",
}
return render(request, "base.html",context)

Categories