I am trying to set up navigation with Django, however, each time I try to navigate it goes back to the same page again.
Please help, any advice will be appreciated. Thank you!
views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
#from django.contrib.auth import views as auth_views
#from . import views
# Create your views here.
def login(request):
return render(request, 'login.html')
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
#username = form.cleaned_data.get('username')
#raw_password = form.cleaned_data.get('password1')
#user = authenticate(username=username, password=raw_password)
#login(request, user)
return redirect('/templates')
else:
form = UserCreationForm()
return render(request, 'templates/signup_form.html', {'form': form})
in Project the file called
urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^login/', include('website.urls')),
url(r'^signup/', include('website.urls')),
url(r'^admin/', admin.site.urls),
]
in the app website urls.py
from django.conf.urls import url
from django.contrib.auth.views import login
from . import views
#
urlpatterns = [
url(r'^', views.login, name=''),
url(r'^login/', login, {'template_name': 'templates/login.html'}),
url(r'^signup/', views.signup, name = 'signup')
#url(r'^login/$', index,{{'template_name': 'templates/index.html' }})
]
The URL patterns are matched from top to bottom. Your first urlpattern is matching anything it sees, so django sends all requests to views.login.
Try putting that row at the bottom of the list
urlpatterns = [
url(r'^login/', login, {'template_name': 'templates/login.html'}),
url(r'^signup/', views.signup, name = 'signup')
url(r'^', views.login, name=''),}})
]
Related
I try to build a login function for my page. To edit the urls.py as followed, it keeps printing this:
cannot import name 'login' from 'django.contrib.auth.views'
How could I deal with the problem?
from django.contrib.auth.views import login
from django.urls import path
from . import views
app_name = "users"
urlpatterns = [
path("login/",
login,
{"template_name": "users/login.html"},
name="login"),
]
Since django-1.11, the login, logout, etc. function-based views have been rewritten to class-based views: the LoginView [Django-doc] and LogoutView [Django-doc] classes, as is specified in the release notes. The "old" function-based views could still be used, but were marked as deprecated.
In django-2.1, the old function-based views have been removed, as specified in the release notes.
You can write it like:
from django.contrib.auth.views import LoginView
from django.urls import path
from . import views
app_name = "users"
urlpatterns = [
path('login/',
LoginView.as_view(
template_name='users/login.html'
),
name="login"
),
]
try this
app_name = 'users'
urlpatterns = [
url(r'^login/$', LoginView.as_view(template_name='users/login.html'), name='login'),
]
You can try with this code:
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'users'
urlpatterns = [
# Login page.
path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
]
#Willem Van Onsem's answer worked for me. On an implementation note, if you rather keep your view code separate from urls (also if you have some processing to do), you would write your urls.py like this (based on a per-app urls.py file in your app folder which means you have to include it in the overall urlpatterns of the project's urls.py file which is in the same folder as your settings.py file, with the syntax path('', include('users.urls')),):
from django.urls import path
from .views import (
login_view
)
app_name = "userNamespace"
urlpatterns = [
path('login/', loginView.as_view(), name="login-view"),
]
and over in your views.py file you would have something like this:
from django.shortcuts import render
from django.contrib.auth.views import (
LoginView,
)
from users.models import User
class login_view(LoginView):
# The line below overrides the default template path of <appname>/<modelname>_login.html
template_name = 'accounts/login.html' # Where accounts/login.html is the path under the templates folder as defined in your settings.py file
Can try this to create a login form
# views page
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login
from django.contrib import messages
def loginPage(request):
if request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.info(request, 'Username or Password is incorrect')
context = {}
return render(request, 'accounts/login.html', context)
#urls
urlpatterns = [
path('login/', views.loginPage, name='login'),,
]
I try to build a login function for my page. To edit the urls.py as followed, it keeps printing this:
cannot import name 'login' from 'django.contrib.auth.views'
How could I deal with the problem?
from django.contrib.auth.views import login
from django.urls import path
from . import views
app_name = "users"
urlpatterns = [
path("login/",
login,
{"template_name": "users/login.html"},
name="login"),
]
Since django-1.11, the login, logout, etc. function-based views have been rewritten to class-based views: the LoginView [Django-doc] and LogoutView [Django-doc] classes, as is specified in the release notes. The "old" function-based views could still be used, but were marked as deprecated.
In django-2.1, the old function-based views have been removed, as specified in the release notes.
You can write it like:
from django.contrib.auth.views import LoginView
from django.urls import path
from . import views
app_name = "users"
urlpatterns = [
path('login/',
LoginView.as_view(
template_name='users/login.html'
),
name="login"
),
]
try this
app_name = 'users'
urlpatterns = [
url(r'^login/$', LoginView.as_view(template_name='users/login.html'), name='login'),
]
You can try with this code:
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'users'
urlpatterns = [
# Login page.
path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
]
#Willem Van Onsem's answer worked for me. On an implementation note, if you rather keep your view code separate from urls (also if you have some processing to do), you would write your urls.py like this (based on a per-app urls.py file in your app folder which means you have to include it in the overall urlpatterns of the project's urls.py file which is in the same folder as your settings.py file, with the syntax path('', include('users.urls')),):
from django.urls import path
from .views import (
login_view
)
app_name = "userNamespace"
urlpatterns = [
path('login/', loginView.as_view(), name="login-view"),
]
and over in your views.py file you would have something like this:
from django.shortcuts import render
from django.contrib.auth.views import (
LoginView,
)
from users.models import User
class login_view(LoginView):
# The line below overrides the default template path of <appname>/<modelname>_login.html
template_name = 'accounts/login.html' # Where accounts/login.html is the path under the templates folder as defined in your settings.py file
Can try this to create a login form
# views page
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login
from django.contrib import messages
def loginPage(request):
if request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.info(request, 'Username or Password is incorrect')
context = {}
return render(request, 'accounts/login.html', context)
#urls
urlpatterns = [
path('login/', views.loginPage, name='login'),,
]
I am newbie Django dev, I have a bit problem about urls config. I want to make url http://localhost:8000/user-auth/register/
In my project, there is user_auth app with below urls:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^register$', views.register),
]
In register this url within urls in my site:
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^polls/', include('polls.urls')),
url(r'^user-auth/', include('user_auth.urls')),
]
In my view user_auth/views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .forms import RegisterForm
def register(request):
if request.method == 'POST':
response = HttpResponse()
response.write("<h1>Thanks for registering</h1></br>")
response.write("Your username:" + request.POST['username'])
response.write("Your email" + request.POST['email'])
return response
registerForm = RegisterForm()
return render(request, 'user_auth/register.html', {'form':registerForm})
In my user_auth/forms.py
from django import forms
class RegisterForm(forms.Form):
username = forms.CharField(label='Username', max_length=100)
password = forms.CharField(widget=forms.PasswordInput)
email = forms.EmailField(label='Email')
When I access to the link http://localhost:8000/user-auth/register/, the console announce "Not Found: /user-auth/register/". I dont know reason why and where. Could you please help me on this problem?. Tks
Page not found (404)
Request Method: POST
Request URL: http://127.0.0.1:8000/accounts/register/accounts/register
views.py :
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from custom_user.forms import CustomUserCreationForm
from django.contrib import auth
from django.http import HttpResponseRedirect
#Create your views here
def home(request):
return render(request, "home.html")
def login(request):
c = {}
c.update(csrf(request))
return render(request, "login.html", c)
def about(request):
context = locals()
template = 'about.html'
return render(request,template,context)
#login_required
def userProfile(request):
user = request.user
context = {'user': user}
template = 'profile.html'
return render(request,template,context)
def auth_view(request):
username = request.POST.get['username', '']
password = request.POST.get['password', '']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return HTTpResponseRedirect('account/login')
else:
return HTTpResponseRedirect('account/login')
def register(request):
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect ('accounts/register_success.html')
else:
form = CustomUserCreationForm()
args = {'form': form}
return render(request, 'accounts/register.html', args)
def register_success(request):
return render(request, 'accounts/register_success.html')
def logout(request):
auth.logout(request)
return render(request, 'logout.html')
when i try to register a new user this error is raised . i manage to create my own custom registration form. i still cannot register any new user . is this error means that my registration form is not authenticate ? can someone explain why i get this error please ? im confused . help me please :(
urls.py :
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url, include
from django.contrib import admin
from profiles import views as profiles_views
from contact import views as contact_views
from checkout import views as checkout_views
from register import views as register_views
urlpatterns = [
url(r'^admin/',include(admin.site.urls)),
url(r'^$', profiles_views.home, name='home'),
url(r'^profile/$', profiles_views.userProfile, name='profile'),
url(r'^about/$', profiles_views.about, name='about'),
url(r'^checkout/$', checkout_views.checkout, name='checkout'),
url(r'^contact/$', contact_views.contact, name='contact'),
url(r'^accounts/register/$', register_views.register, name='register'),
url(r'^accounts/register_success/$', register_views.register_success, name='register_success'),
url(r'^accounts/', include('allauth.urls')),
url(r'^auth/', include('django.contrib.auth.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root= settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)
Form.valid() should be inside the post indentation
So, I'm trying to create a table filled with contacts in Python/Django. When I attempt to run the program, I get the above error message ("ImportError: Could not import 'edit_contact'. The path must be fully qualified.")
Here is the views.py I'm using:
from contacts.models import Contact
#, Address, Telephone
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404, render
from django.template import Context, loader
from django.forms.models import inlineformset_factory
from django.template import loader, Context, RequestContext
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
# Create your views here.
def index(request):
#return HttpResponse("Hey! You can see contacts here!")
contact_list = Contact.objects.all().order_by('last_name')
return render_to_response('contacts/index.html', {'contact_list': contact_list},
RequestContext(request))
def detail(request, contact_id):
c = get_object_or_404(Contact, pk=contact_id);
def new_contact(request):
print "new_contact"
#AddressInlineFormSet = inlineformset_factory(Contact,
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
contact = form.save()
return HttpResponseRedirect(reverse('contacts.views.detail', args=(contact.pk,)))
else:
form = ContactForm()
return render_to_response("contacts/form.html",{
"form": form,
}, RequestContext(request))
def edit_contact(request, contact_id):
contact = Contact.objects.get(pk=contact_id)
if request.method == "POST":
form = ContactForm(request.POST, instane=contact)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('contacts.views.detail', args=(contact.pk,)))
else:
form = ContactForm(instance = contact)
return render_to_response("contacts/form.html", {
"form": form,
}, RequestContext(request))
This is the urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<contact_id>\d+)/$', 'detail', name='contactdetailsurl'),
url(r'^new/$', 'new_contact', name='newcontacturl'),
url(r'^(?P<contact_id>\d+)/edit/$','edit_contact', name='editcontacturl'),
]
And the error is pointing to this line in my site_base.html file:
<li id="tab_first"><a href="
{% url contacts.views.index %}
"><i class="icon-book"></i> Contacts</a></li>
Let me know if you need any more info. Thanks!
The error is telling you that you should use the full path to the view, for example 'contacts.views.edit_contact' (assuming the app is called contacts).
However, using strings in your URL patterns is deprecated in Django 1.8, and not supported in Django 1.10+. You should using callables instead. You are already using the callable views.index for your index URL pattern.
I would convert the rest of your URL patterns as follows:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<contact_id>\d+)/$', views.detail, name='contactdetailsurl'),
url(r'^new/$', views.new_contact, name='newcontacturl'),
url(r'^(?P<contact_id>\d+)/edit/$', views.edit_contact, name='editcontacturl'),
]