Passing user auth status in view - python

I am using Django Cookiecutter as template. And by default in urls.py there is following url:
url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'),
and because i need to pass some additional parameters in it i wanted to use it as:
url(r'^about/$', index, name='about'),
Where index is from my views, but when i use the view, my system does not recognise that user is logged in, should i somehow pass user in my index too or what am i doing wrong?
What i am doing in my view:
def index(request):
return render_to_response('pages/about.html', {
'categories': Category.objects.all(),
'posts': Post.objects.all()[:5]
})

I solved it by using render instead of render to response so the method after change looks like this:
def index(request):
categories = Category.objects.all()
posts = Post.objects.all()[:5]
context = {'categories': categories, 'posts': posts}
return render(request, 'pages/home.html', context)

Related

How to order URLs in Django? I am getting `Page Not Found` error because of misplaced urls?

I am getting below error when I want to add a project or go to project_create URL.
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/project/add/
Raised by: projects.views.project_detail_view
the URL says /project/add/ that according to the view it must open project_create_view but the error is raised by detail view projects.views.project_detail_view.
This is the URL:
path('project/<slug:project_slug>/delete/',
project_delete_view, name='project_delete'),
path('project/<slug:project_slug>/update/',
project_update_view, name='project_update'),
path('project/<slug:project_slug>/',
project_detail_view, name='project_detail'),
path('projects/list/', all_projects_view, name='all_projects'),
path('project/add/', project_create_view, name='project_create'),
path('administration/', administration, name='administration'),
path("", home, name='home'),
if I comment this line path('project/<slug:project_slug>/',project_detail_view, name='project_detail'), then project_create URL goes to right view and right template. Why is this happening? I used different name, url and view name. Why is this happening?
Edit: I added both views
#login_required
def project_create_view(request):
if not request.user.is_superuser:
raise PermissionDenied
if request.method == 'POST':
form = ProjectForm(request.POST, request.FILES)
if form.is_valid():
title = form.instance.title
form.save()
project = get_object_or_404(Project, title=title)
messages.success(request, 'Project created successfully.')
return redirect(project.get_absolute_url())
form = ProjectForm()
return render(request, 'projects/project_create.html', {'form': form})
def project_detail_view(request, project_slug):
project = get_object_or_404(Project, slug=project_slug)
session_key = 'project_views{}'.format(project.slug)
if not request.session.get(session_key, False):
Project.objects.filter(id=project.pk).update(
visit_count=F('visit_count') + 1
)
request.session[session_key] = True
context = {
'project': project
}
return render(request, 'projects/project_detail.html', context)
Dynamic URLs must be on the bottom of the list,
urlpatterns = [
# Fixed URLs
path("", home, name='home'),
path('administration/', administration, name='administration'),
path('project/add/', project_create_view, name='project_create'),
path('projects/list/', all_projects_view, name='all_projects'),
# Dynamic URLs
path('project/<slug:project_slug>/',
project_detail_view, name='project_detail'),
path('project/<slug:project_slug>/delete/',
project_delete_view, name='project_delete'),
path('project/<slug:project_slug>/update/',
project_update_view, name='project_update'),
]
Ref: Django URL routing
You can order it by app, or by path, for example if you have more than one that starts with project you may group them in a different url pattern list.
projecturls =[
# your project path urls
]
urlpatterns =[
path('project/', include(projecturls)),
# ...
]

Django: redirect to view with parameters

I am using Django authentication. Whenever a user logs in, I want to redirect him to /profile/user_id, being user_id a number. I can get the value of user_id by request.user.profile.id. In settings.py I have LOGIN_REDIRECT_URL = 'app_1:index'
app_1/urls.py:
url(r'^profile/$', views.index, name='index'),
# ex: /profile/5/
url(r'^profile/(?P<user_id>[0-9]+)/$', views.profile, name='profile'),
app_1/views.py (things I've also tried are commented):
def index(request):
userid = request.user.profile.id
#return render(request, 'app_1/index.html', context)
#return profile(request, request.user.profile.id)
#return render(request, 'app_1/user_prof.html', {'user': request.user.profile.id})
#return redirect(profile, user_id= request.user.profile.id)
return redirect('profile', user_id=userid)
def profile(request, user_id):
user = get_object_or_404(Profile, pk=user_id)
return render(request, 'app_1/user_prof.html', {'user': user})
I must be missing something because this should be easy but I'm stuck on it. Thanks in advance.
EDIT: The error I'm getting is Reverse for 'profile' not found. 'profile' is not a valid view function or pattern name.: http://dpaste.com/270YRJ9
Try using this instead
from django.urls import reverse
return redirect(reverse('profile', kwargs={"user_id": userid}))
Or this:
return redirect('app_1:profile', user_id=userid)

How do I add user data to url in Django?

I've got a function based view in Django called userView
#login_required(login_url='/login/')
def userView(request):
user = None
if request.user.is_authenticated():
user = request.user
user_id = user.pk
return render(request, "user_view.html", {'user': user})
and here's my URL for it
urlpatterns = [
url(r'^user/', userView, name='user'),
]
After my user has logged in, I'd like him to see his pk number in the URL. I.e., if the user's PK is 3 and the user directs their browser to www.myapp.com/user, the URL in the address bar should change to www.myapp.com/user/3/. How do I make that happen? I'm aware I need to edit the RegEx for the URL into
url(r'^user/(?P<user_id>[0-9]+)/$', userView, name='user')
but how do I pass the PK number to the URL?
I am not a Django expert but my guess is you want to redirect the user to his 'home page' after he is logged in. That can be done using the redirect() method
#login_required(login_url='/login/')
def userLoginView(request):
if request.user.is_authenticated():
return redirect("/user/{0}".format(request.user.pk), user=request.user)
And then define a second view that will render the home page
def userView(request, user_id=None, user=None):
return render(request, "user_view.html", {'user': user})
Also your url patterns should be as follows
urlpatterns = [
url(r'^user/', userLoginView, name='userlogin'),
url(r'^user/(?P<user_id>[0-9]+)/$', userView, name='user')
]

Django 1.9 : Passing arguments from urls.py to a class view

I am creating a small web application as a mini project of mine to learn the Django framework. I'm on Version 1.9.4, on OS X. I'm trying to pass a string in the URL that will be sent to a class-based view, and it will return a different template based on the URL. To my knowledge, doing (?P) will allow the input of dynamic text. \w is for characters, and writing <name> will pass it as a variable. Is this configured right, or is this is not the correct way to do it?
The reason I'm concerned is that the Django documentation uses method views, while I am using class-based views.
urls.py
from django.conf.urls import url
from . import views
app_name = 'xyz'
urlpatterns = [
url(r'^create/(?P<ty>\w+)$', views.ArticleView.as_view(), name='article-form'), #.as_view() to turn Class into View
]
views.py
class ArticleCreate(View):
l = {
'weapon': WeaponForm,
'map': MapForm,
'operator': OperatorForm,
'gadget': GadgetForm,
'skin': SkinForm
}
ty = ty.lower()
template_name = 'xyz/create_article_form.html'
def get(self, request):
return render(request, self.template_name)
def post(self, request):
pass
The arguments that are being passed to the url should be "catched" within the view inside the relevant function, for example:
def get(self, request, ty):
ty = ty.lower()
return render(request, self.template_name)

unable to redirect to some view in Django python

AoA,
I am trying to redirect to some view, but failed to do so.
here is the code
views.py
def logout(request):
c = {'username': 'Create Account', 'status': ''}
c.update(csrf(request))
response = render_to_response("home.html",c)
response.delete_cookie('id')
request.session['id'] = 'None'
return redirect('/home/')
def home(request):
#some code here
return render_to_response('blah blah')
urls.py
url(r'^home/$', 'contacts.views.home_Page'),
url(r'^logout/$', 'contacts.views.logout'),
the above code redirect me to -- let's suppose current URL(127.0.0.1/account)
it redirects me to (127.0.0.1/account/home) but i want to redirect to 127.0.0.1/home
how can I redirect to specific view ?
redirect(to[, permanent=False], *args, **kwargs) returns an HttpResponseRedirect to the appropriate URL for the arguments passed. You need to return the HttpResponseRedirect object in the view function.
BTW, you should try to avoid hardcoding urls in you code, instead you should use view names.
e.g:
urls.py:
url(r'^home/$', home, name='home_view')
...
view.py:
def logout(request):
...
redirect('home_view')
django provides a built-in logout that you should use:
from django.shortcuts import redirect
from django.contrib.auth import logout
def log_out(request):
logout(request)
return redirect('home')
Now 'home' can be many things; but the easiest way to make sure its pointing to the right place is to name your urls. So in your urls.py:
url(r'home/$', home, name='home')

Categories