When I run my server I get a type error message telling me that:
my view must be callable or a list/tuple
and from what I gathered django version differs and for clarity sake, I am using django latest version... Anyways here's my views.py and urls.py for my project:
url.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^login/$',
'django.contrib.auth.views.login',name='login'),
url(r'^logout/$',
'django.contrib.auth.views.logout',name='logout'),
url(r'^logout-then-login/$',
'django.contrib.auth.views.logout_then_login',name='logout_then_login'),
]
views.py
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from .forms import LoginForm
from django.contrib.auth.decorators import login_required
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(username=cd['username'],password=cd['password'])
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled account')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'account/login.html', {'form': form})
#login_required
def dashboard(request):
return render(request,
'account/dashboard.html',{'section': 'dashboard'})
Try changing your url patterns to below:
urlpatterns = [
url(r'^login/$',
django.contrib.auth.views.login,name='login'),
url(r'^logout/$',
django.contrib.auth.views.logout,name='logout'),
url(r'^logout-then-login/$',
django.contrib.auth.views.logout_then_login,name='logout_then_login'),
]
From the docs for latest django version, the views are function and not strings.
Related
Working on a simple project using Django 3.2 and the loqin_required decorator is not working.
When I close the server and re-open it again, it works the first time but not anymore.
It used to work very well, but I'm not sure what I changed in the code that it doesn't work anymore.
views.py
from django.http.response import HttpResponse
from django.shortcuts import render, redirect
from django.utils import timezone
from django.db.models import Count
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.contrib import messages
from .models import *
from .models import __str__
from .forms import CreateUserForm
# Create your views here.
#login_required(login_url='login/')
def home(request):
count_item = todo.objects.count()
all_items = todo.objects.all().order_by("created")
context = {'all_items': all_items, 'count_item':count_item}
return render(request, 'html/home.html', context)
#login_required(login_url='login/')
def add_todo(request):
current_date = timezone.now()
new_item= todo(content = request.POST["content"])
new_item.save()
return redirect('/')
#login_required(login_url='login/')
def delete_todo(request, todo_id):
item_to_delete = todo.objects.get(id=todo_id)
item_to_delete.delete()
return redirect('/')
def login_user(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
# print('USER:', user)
if user is not None:
login(request, user)
return redirect('/')
return render(request, 'html/login.html')
def logoutUser(request):
logout(request)
return redirect('login/')
def register_user(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.save()
user = authenticate(request, username=user.username, password=request.POST.get('password1'))
print("USER:",user)
if user is not None:
login(request, user)
return redirect('/')
context = {'form':form}
return render(request, 'html/register.html', context)
urls.py
from django.urls import path
from django.views.generic.base import RedirectView
from . import views
app_name = 'todo'
urlpatterns = [
path('', views.home, name="home"),
path('add_todo/', views.add_todo),
path('delete_todo/<int:todo_id>/', views.delete_todo),
path('login/', views.login_user, name='login'),
path('logout/', views.logoutUser, name='logout'),
path('register/', views.register_user, name="register"),
]
Any suggestion or response would appreciate it
Thanks!
If you are logging out the user just by redirecting, you're not actually logging them out. You have to use the logout function of the authentication framework, with the logout() function, or you can use logout_then_login view from django if all you want to do is send users back to the login page.
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=''),}})
]
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
Currently, im trying to make it so that I can complete a question on a page then when it's submitted to the database the next page will load. furthermore, every time I point it towards the templates folder it is piggybacking off the original one meaning that it can't find the new HTML page.
My idea is that when question1 is completed it will link to question2 where the def question2 code will execute and so on. But the forms won't display correctly and I believe it is due to the def question2 not running correctly.
def question1(request):
question_form1 = QuestionForm1()
if request.method == 'POST':
form = QuestionForm1(request.POST)
if form.is_valid():
form.save() # saves to database
return HttpResponse('question2.html')
else:
return render(request, 'music/failed.html')
return render(request, 'music/question1.html', locals())
def question2(request):
question_form2 = QuestionForm2()
if request.method == 'POST':
form2 = QuestionForm2(request.POST)
if form2.is_valid():
form2.save() # Saves to database
return render(request, 'music/question3.html', locals())
else:
return render(request, 'music/failed.html')
return render(request, 'music/question2.html', locals())
Edit:Added Urls.py
from django.conf.urls import url
from . import views
app_name = 'music'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^register/$', views.register, name='register'),
url(r'^login_user/$', views.login_user, name='login_user'),
url(r'^logout_user/$', views.logout_user, name='logout_user'),
url(r'^question1/$', views.question1, name='question1'),
url(r'^question2/$', views.question2, name='question2'),
]
from django.http import HttpResponseRedirect
from django.urls import reverse
# delete following line
return HttpResponse('question2.html')`
# replace with this one
return HttpResponseRedirect(reverse('view_name_here'))
# or if you are using any namespaces for your url
return HttpResponseRedirect(reverse('namespace:view_name_here'))
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'),
]