I have done this tutorial as it explained here:
and here
but there is some points that i can not understand.
When i log in using a facebook account i can get access also easily to my admin page and i want it to be happened (because it is not secure), so is there a way to fix that ?
If i want to bring that registred user to another template, i can do it only whith direct_to_template method in my url dispatcher, here is an example:
url(r'^tags$', direct_to_template, {'template' : 'user.html' }),
is there another way to do it.
Finally to be more clear, here is some snippets of my project:
urls.py
urlpatterns = patterns('',
#All Auth URLS
url(r'^accounts/', include('allauth.urls')),
url(r'^accounts/profile/', direct_to_template, { 'template' : 'profile.html' }),
#nav urls
url(r'^$','fb.views.home', name="home"),
url(r'^tags$', direct_to_template, {'template' : 'tags.html' }),
views.py
def home(request):
return render_to_response("base.html", locals(), RequestContext(Context))
base.html
.....
{% block body %}
{% block content %}
{% if user.is_authenticated %}
{{ user.username }} <p> you are logged in </p>
<p><a href="/accounts/logout/" >Logout </a></p>
{% else %}
<p> you are not authenticated : </p>
<a href="/accounts/facebook/login/" >Login with Facebook </a>
{% endif %}
{% endblock content %}
{% endblock body %}
...
profile.html
...
{% block content %}
{% if user %}
<h1>Welcome, {{user.first_name}}</h1>
<p>Following is the Extra information that facebook has provided to allauth:</p>
{% for account in user.socialaccount_set.all %}
<p>First Name: {{ account.extra_data.first_name }}</p>
<p>Last Name: {{ account.extra_data.last_name }}</p>
<p>Profile Link: {{ account.extra_data.link }}</p>
{% endfor %}
{% endif %}
Go to tags
{% endblock content %}
{% endblock body %}
tags.html
{{user.socialaccount_set.all.0.get_avatar_url}} <br/>
{{user.socialaccount_set.all.0.uid}} <br/>
{{user.socialaccount_set.all.0.get_provider_account }} <br/>
Finally thanks in advance for your help .
The secrect is:
After logging in, the user was hiding in the request object, so view shoukd be like this:
def home(request):
user = request.user
return render_to_response("base.html", locals(), RequestContext(Context))
Now, the problem is resolved, but i wonder why the Context User object was anounymous.
i am asking this question because that last user object woiuld have the same value of the request user in a simple authentication
Related
I'm trying to pass an object's id through the url, but its not able to find the page even after it tries the path when it goes through its patterns
Error:
Using the URLconf defined in GroomingService.urls, Django tried these URL patterns, in this order:
admin/
[name='Home']
appointment-Maker/
account/
admin-home
view_appointment/<id>/
login/ [name='Login Page']
registration/ [name='Registration Page']
logout [name='Logout Page']
The current path, adminview_appointment/21/, didn’t match any of these.
GroomingService.urls
#urls
urlpatterns = [
path('admin/', admin.site.urls),
path('', Home_view, name="Home"),
path('appointment-Maker/', include('appointmentApp.urls')),
path('account/', include('accountApp.urls')),
path('admin-home', include('adminApp.urls')),
path('view_appointment/<id>/', viewAppointment_view), #this is the page it is not finding
path('login/', Login_view, name='Login Page'),
path('registration/', Registration_view, name='Registration Page'),
path('logout', Logout_view, name='Logout Page')
]
adminApp/views.py viewAppointment_view
def viewAppointment_view(request, id):
appointments = Appointment.objects.get(id = id)
context = {
'appointments' : appointments
}
return render(request, "admin_templates/viewappointment.html", context)
templates/admin_templates viewappointment.html
{% extends 'base.html' %}
{% block content %}
<a>appointment view</a>
{% endblock %}
templates/admin_templates adminhome.html (the link is clicked through this page)
{% extends 'base.html' %}
{% block content %}
<a>this is the admin page</a>
<br>
{% for a in appointments %}
Client name:{{a.client_dog_name}}<br> {% comment %} this is the link that is clicked {% endcomment %}
{% endfor %}
<br>
<a>find month</a>
<form method="POST">
{% csrf_token %}
{{ monthyear }}
<button class="btn btn-primary" type="submit">click</buttom>
</form>
{% endblock %}
If I'm missing anything please let me know, I had the path at the adminApp/urls.py earlier
urlpatterns = [
path('', views.adminhome_view, name="Admin Home"),
]
but moved it to where it was trying to find the urls. I have no idea why this might not be working.
It should be view_appointment/{{a.id}}, not adminview_appointment/{{a.id}}, but it is better to make use of the {% url … %} template tag [Django-doc]. You can give the view a name:
path('view_appointment/<int:id>/', viewAppointment_view, name='view_appointment'),
and then refer to it in the template:
Client name:{{a.client_dog_name}}<br>
I did use django pagination, but there is a problem with urls, here is my urls.py:
url(r'^/blog/$', blog_view.main, name='blog'),
url(r'^/blog/page/(?P<page_id>\d{0,9})$', blog.post, name='blog_page'),
My views.py:
def post(request, page_id=None):
posts = Posts.objects.all()
pageid = page_id
return render(request, 'base.html', {'posts': posts, 'pageid': pageid,})
My base.html which use bootstrap:
{% url 'blog_page' as blog_page %} # Blog page need follow patterns
<ul>
{% for post in posts %}
<li {% if request.path == htt://myblog.com/blog/page/5 %} class="active" {% endif %}>{{ post.title }}</li> # When I put blog_page django shows error. Help me how to put something to fix this condition.
{% endfor %}
</ul>
As stated in the documenation on HttpRequest objects,
HttpRequest.path is
A string representing the full path to the requested page, not including the scheme or domain.
Example: "/music/bands/the_beatles/"
(emphasis mine).
So, in your test, leave out the scheme (which you, btw, incorrectly wrote as htt://) and domain parts:
<li {% if request.path == /blog/page/5 %} class="active" {% endif %}>{{ post.title }}</li>
I am trying to obtain a url to a view that renders an image so I can use it in an img tag with href.
But my {% url viewname object_id %} is not working. Here are the specifics:
my urls.py:
hydrourlpatterns = patterns('',
url(r'^graphs/$','hydro.views.graphs',name='graphs'),
url(r'^graphs/new/$', 'hydro.views.add_graph', name='add_graph'),
url(r'^graphs/(?P<graph_id>\d+?)/$', 'hydro.views.single_graph', name='graph_detail'),
url(r'^graphs/graphImage/(?P<graph_id>\d+?)/$', 'hydro.views.render_graph', name='graphImage')
)
my template(url: localhost/graphs/(graph_id)/):
{% extends "subpage.django" %}
{% block content %}
{% if graph %}
<h3> {{ graph.name }} </h3>
<h1> {% url 'graphImage' graph_id %} </h1>
{% endif %}
{% endblock %}
The error I keep getting is ViewDoesNotExsist.
Could not import hydro.views.add_site.
View does not exist in module hydro.views.
You use hydro.views.add_site somewhere else in your urls.py. Comment this url line or create add_site view in the hydro.views.
EDIT: You don't pass graph_id variable to the template so change {% url %} call to:
{% url 'graphImage' graph.id %}
Please, I am creating a web app, when a user log in, he/she can see other users, and can click on the user's username to view that user's profile. But I am finding it difficult to display other users profile except the currently logged in user. Kindly help me on how to go about this. I would prefer a function based view.
views
def profile(request, username):
context = {
'userprofile': User.objects.get(username=username),
}
return render_to_response('profile.html',context)
profile.html
Name: {{ userprofile.get_full_name }}
Username: {{ userprofile.username }}
urls
url(r'^/profile/(?P<username>\w+)/$', auth(profile), {}, name='chat_history')
what I don't know is how apply this url on a username. As in this:
home.html
{% if messages %}
{% for message in messages %}
{% if message.sender == user %}
<p> {{ message.sender }} >
{{ message.receiver }} : <br/>
{{ message.message }}
<sub>{{ message.creation_date }}</sub>
</p>
{% endif %}
{% endfor %}
{% else %}
{% trans 'No chat history of you and this user' %}
{% endif %}
Have got no idea what 'xxxxx' should be
Probably importing User model from django.contrib.auth and passing it to your views could help.
Can someone please explain in details how to make a registration and authentication in as easy words as possible ? I made authentication (login) with django.contrib.auth but what I want to get is a full register(social/non)+login. Already saw the django-allauth, django-social-auth, django-social but still can't get it working without hacking a lot. Heard that django-registration and django-profiles can make it a lot easier, but i can't handle it. For example,
~/.virtualenvs/plinter/lib/python2.7/site-packages/registration/backends/default/urls.py
needs a small hack to work:
# from django.views.generic.simple import direct_to_template
from django.views.generic import RedirectView
...
RedirectView.as_view(url='/registration/activation_complete.html'),
# direct_to_template,
# {'template': 'registration/activation_complete.html'},
...
The DjangoBook gives simple examples of Contact and search forms. But i can't expand it on user registration and login.
So can anyone give kis example of working registration and login?
Update
Here is a simple example of login. Now django-allauth or social auth or registration2 are in consideration...
Update2
django-allauth seems to be the best solution for easier authentication. Add correctly apps in settings, register fb/google/etc apps and register through admin and use template inheritance to change default pages design.
THIS is a very good tutorial about login & Co. It explains very well how to perform login by ourself ad override existing django login pages.
UPDATE:
Here Overview for Registration and Login. For more details go to the link.
To Register:
Views and URLs
Go to the lower site folder (where the settings.py file is) and open
the views.py file. At the top make sure the following imports are
included. Add them if not:
from django.shortcuts import
render_to_response from django.http import HttpResponseRedirect from
django.contrib.auth.forms import UserCreationForm from
django.core.context_processors import csrf
Below that add the following functions (you can put them after the
Login functions):
def
register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register/complete')
else:
form = UserCreationForm()
token = {}
token.update(csrf(request))
token['form'] = form
return render_to_response('registration/registration_form.html', token)
def registration_complete(request):
return render_to_response('registration/registration_complete.html')
Open the urls.py file in the site folder (same folder as
settings.py). Below urlpatterns = patterns('', insert the following
lines.
# Registration URLs
url(r'^accounts/register/$', 'simplesite.views.register', name='register'),
url(r'^accounts/register/complete/$', 'simplesite.views.registration_complete',
name='registration_complete'),
Templates We will assume your site already has a templates
directory and a base.html file with the navigation bar. Open the
base.html file and in the nav element add a navigation menu link to
the login page
register
If one does not already exist, go to the templates folder and create
a folder inside it named registration. Create a file called
registration_form.html, save it to the templates/registration folder,
then populate it with the following:
{% extends "base.html" %} {% block title %}Register{%
endblock %} {% block content %}
<h2>Registration</h2>
<form action="/accounts/register/" method="post">{% csrf_token %}
{{form.as_p}} <input type="submit" value="Register" />
</form>
{% endblock %}
Create a file called registration_complete.html, save it to the
templates/registration folder, and populate it with the following:
{% extends "base.html" %} {% block title %}You are
Registered{% endblock %} {% block content %}
<h2>Thank you for Registering</h2> <p>Please Login</p>
{% endblock %}
To Login:
Views and URLs Open the views.py file in the lower site folder (where the settings.py file is). If there isn't one then create and
save it. At the top of the file insert the following import: from
django.shortcuts import render_to_response Below that you only need to
add one function rendering the loggedin page. The other functions
(login and logout) are in the views.py file in the Django Auth folder.
def loggedin(request):
return render_to_response('registration/loggedin.html')
# Optionally, if you want to show their username when they login then call their username in the view. Change the loggedin function to:
def loggedin(request):
return render_to_response('registration/loggedin.html',
{'username': request.user.username})
Open the urls.py file in the site folder (same folder as settings.py).
Below urlpatterns = patterns('', insert the following lines.
# Auth-related URLs:
url(r'^accounts/login/$', 'django.contrib.auth.views.login', name='login'),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', name='logout'),
url(r'^accounts/loggedin/$', 'simplesite.views.loggedin', name='loggedin'),
With simplesite being the name of the folder that holds the views.py
file that you are calling. Open the settings.py file and at the bottom
insert LOGIN_REDIRECT_URL = '/accounts/loggedin/'. Django's default
is to redirect to /accounts/profile when you log in, which is fine if
you have an profile page at that url. If not you need to change your
settings default for the Login redirect url to the one holding your
loggedin.html page.
Templates
We will assume your site already has a templates directory and a
base.html file with the navigation bar. Open the base.html file and in
the nav element add a navigation menu link to the login page login Add a logout link too logout Create a directory called
registration inside the templates folder. If you do this through the
command line, type mkdir registration Create a file called login.html,
save it to the templates/registration folder, and populate it with the
following:
{% extends "base.html" %}
{% block title %}Log In{% endblock %}
{% block content %}
<form method="post" action="{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="login" />
</form>
{% endblock %}
{{ form.as_table }} uses the Django Forms module to create the form.
You can create an unformatted form by using {{ form }} without the
HTML table tags, or have each field put inside paragraph tags with {{
form.as_p }}, or as an unordered list {{ form.as_ul }}. Optionally, you
can also lay out your own form structure and use the form field tags
as follows:
{% extends "base.html" %}
{% block title %}Log In{% endblock %}
{% block content %}
<form method="post" action="{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
{% if form.errors %}
<p>Your Username or Password were not entered correctly. Please try again.</p>
{% endif %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
<td>{{ form.username.errors }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
<td>{{ form.password.errors }}</td>
</tr>
</table>
<input type="submit" value="login" />
</form>
{% endblock %}
Create a file called loggedin.html, save it to the
templates/registration folder, and populate it with the following:
{% extends "base.html" %}
{% block title %}Logged In{% endblock %}
{% block content %}
<h2>You are logged in</h2>
{% endblock %}
If you want to display the username, you would make the adjustment to
the view discussed in the views section. Then change the loggedin.html
template to the below (change the wording as you see fit):
{% extends "base.html" %}
{% block title %}Logged In{% endblock %}
{% block content %}
<h1>Welcome {{username}}</h1>
<p>Thank you for logging in.</p>
<p>Logout</p>
{% endblock %}
Create a file called logged_out.html, save it to the
templates/registration folder and populate it with the following:
{% extends "base.html" %}
{% block title %}Logged Out{% endblock %}
{% block content %}
<h2>Logged out!</h2>
<p>Log back in</p>
{% endblock %}
Trix's approach worked for me, but the logout link was redirecting to the admin logout, instead of logged_out.html.
To fix the redirect, I added a next option to the href:
Logout
In templates/registration:
Renamed logged_out.html to loggedout.html; the underscore caused it to still route to the admin logout page.
In views.py:
def loggedout(request):
return render_to_response('registration/loggedout.html')
And finally, in urls.py:
url(r'^myapp/loggedout/$', 'myapp.views.loggedout', name='loggedout'),