I'm getting the TypeError 'str' object is not callable in my Django Project when i access the url "localhost:8000/adminPonto" of the project (i'm brazillian). It follows below the codes of urls.py (within the error lies) and adminApp.views (code related to urls.py and, consequently, to the error):
urls.py
# -- coding:iso-8859-1 --
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
import baterPonto.views
import adminApp.views
import PontoCOSGEM.views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Sistema de Ponto
(r'^ponto/$',baterPonto.views.index), # Pagina inicial da administracao do registro de ponto
(r'^ponto/registrar/$',baterPonto.views.registrar_ponto),
# Administracao do Ponto
(r'^adminPonto/$',adminApp.views.loginIndex), # Formulario de login da admin. de ponto
(r'^adminPonto/login/$',adminApp.views.entrar), # Pagina de login da admin. de ponto
(r'^adminPonto/logout/$',adminApp.views.sair), # Pagina de logout da admin. de ponto
(r'^adminPonto/index/$',adminApp.views.index), # Pagina inicial do sistema de adm.
# Gerencia de Funcionarios
(r'^adminPonto/funcionarios/$',adminApp.views.funcionariosIndex), # Menu de gerência dos funcionarios
'''(r'^adminPonto/funcionarios/search/$',adminApp.views.funcionariosSearch), # Procura por funcionario
(r'^adminPonto/funcionarios/add/$',adminApp.views.funcionariosAdd), # Adiciona funcionarios
(r'^adminPonto/funcionarios/edit/$',adminApp.views.funcionariosEdit), # Edita funcionarios
(r'^adminPonto/funcionarios/delete/$',adminApp.views.funcionariosDelete), # Apaga funcionarios
(r'^adminPonto/funcionarios/list/$',adminApp.views.funcionariosList), # Lista todos os funcionarios'''
# Relatorio de Ponto
(r'^adminPonto/relatorios/$',adminApp.views.relatorioIndex), # Menu de relatorio de ponto (por funcionario ou de todos)
# Examples:
# url(r'^$', 'PontoCOSGEM.views.home', name='home'),
# url(r'^PontoCOSGEM/', include('PontoCOSGEM.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
)
views.py
# -- coding: iso-8859-1 --
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth import authenticate, login, logout
def userLoged(request,url):
insertMessage = False
testUser = ""
try:
testUser = request.session['user']
except KeyError:
insertMessage = True
message = "É preciso estar logado para acessar esta página."
return render_to_response('loginAdmin.html',locals(),context_instance=RequestContext(request));
if testUser is not None:
return render_to_response(url,locals(),context_instance=RequestContext(request));
else:
insertMessage = True
message = "É preciso estar logado para acessar esta página."
return render_to_response('loginAdmin.html',locals(),context_instance=RequestContext(request));
def loginIndex(request):
return render_to_response('loginAdmin.html',locals(),context_instance=RequestContext(request))
def entrar(request):
insertMessage = False
message = "Erro. Usuário ou Senha incorretos."
lg = "Usuario"
passwd = "Senha"
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
request.session['user'] = user
return render_to_response('indexAdmin.html',locals(),context_instance=RequestContext(request));
else:
insertMessage = True
return render_to_response('loginAdmin.html',locals(),context_instance=RequestContext(request));
def sair(request):
insertMessage = True
message = "Saída realizada com sucesso."
logout(request)
return render_to_response('loginAdmin.html',locals(),context_instance=RequestContext(request));
def index(request):
userLoged(request,'indexAdmin.html')
# Gerência de funcionarios
def funcionariosIndex(request):
userLoged(request,'funcionarioIndex.html')
'''def funcionariosSearch(request):
def funcionariosAdd(request):
def funcionariosEdit(request):
def funcionariosDelete(request):
def funcionariosList(request):'''
# Gerência de relatórios
def relatorioIndex(request):
return HttpResponse("Menu de escolha de relatorios")
# Create your views here.
Honestly, I can't get see errors in code above, and i don't know why this error is occurring.
Does anyone, so, knows why the 'str' object is not callable is appearing?
Multiline comments like '''comment text''' can cause troubles.
Try commenting five lines from
'''(r'^adminPonto/funcionarios/search/$',adminApp.views.funcionariosSearch), # Procura por funcionario
with '#' and tell if it helps.
Related
contact/views.py
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import ContactForm
def contactView(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, ['admin#example.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
# return redirect('success')
return redirect('PostList') #another view from another app
return render(request, "contact.html", {'form': form})
# def successView(request):
# return HttpResponse('Success! Thank you for your message.')
contact/urls.py
from django.contrib import admin
from django.urls import path
from .views import contactView
urlpatterns = [
path('contact/', contactView, name='contact'),
# path('success/', successView, name='success'),
]
blog/views.py
from django.views import generic
from .models import Post, PostImage
# Create your views here.
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'index.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
# Add in a QuerySet of all the books
# context['image_list'] = PostImage.objects.all()
# context['image_list'] = self.get_object().postimage_set.all()
context['image_list'] = PostImage.objects.filter(post__slug=self.kwargs.get('slug'))
return context
blog/urls.py
from . import views
from django.urls import path
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
]
I need the following in the SIMPLEST DRY manner possible; how do I write this redirect inside contact/views.py?
return redirect('PostList') #another view from another app
PostList is a class-based view from another app called blog. It is the homepage essentially.
for reference..
https://ordinarycoders.com/blog/article/django-messages-framework
In your project folder (eg, my_project/my_project) you should have a urls.py with something like this
path("admin/", admin.site.urls),
path("", include("blog.urls")),
path("", include("contact.urls"))
This allows django to look through all url files in the order listed. So long as all your url names and patterns are unique, then your view should be able to simply do
from django.shortcuts import redirect
from django.urls import reverse
return redirect(reverse('home'))
'home' being the name value of the ListView.
(NB: if you have various applevel urls.py files with path(''... django will take the first one it hits)
I'm a newbie trying to add an a new page but get the following error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/study
Using the URLconf defined in student_management_system.urls, Django tried these URL patterns, in this order:
I've added a function for the page in Views.py and also added the path in URLS.py.
StudentViews.py ---> in student management app folder:
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages
from django.core.files.storage import FileSystemStorage # To upload Profile Picture
from django.urls import reverse
import datetime # To Parse input DateTime into Python Date Time Object
from student_management_app.models import CustomUser, Staffs, Courses, Subjects, Students, Attendance, AttendanceReport, \
LeaveReportStudent, FeedBackStudent, StudentResult
def study(request):
return render(request, "student_template/study.html")
Views.py ---> in student management app folder:
# from channels.auth import login, logout
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, redirect
from django.contrib import messages
from student_management_app.EmailBackEnd import EmailBackEnd
def home(request):
return render(request, 'index.html')
def loginPage(request):
return render(request, 'login.html')
def doLogin(request):
if request.method != "POST":
return HttpResponse("<h2>Method Not Allowed</h2>")
else:
user = EmailBackEnd.authenticate(request, username=request.POST.get('email'), password=request.POST.get('password'))
if user != None:
login(request, user)
user_type = user.user_type
#return HttpResponse("Email: "+request.POST.get('email')+ " Password: "+request.POST.get('password'))
if user_type == '1':
return redirect('admin_home')
elif user_type == '2':
# return HttpResponse("Staff Login")
return redirect('staff_home')
elif user_type == '3':
# return HttpResponse("Student Login")
return redirect('student_home')
else:
messages.error(request, "Invalid Login!")
return redirect('login')
else:
messages.error(request, "Invalid Login Credentials!")
#return HttpResponseRedirect("/")
return redirect('login')
def get_user_details(request):
if request.user != None:
return HttpResponse("User: "+request.user.email+" User Type: "+request.user.user_type)
else:
return HttpResponse("Please Login First")
def logout_user(request):
logout(request)
return HttpResponseRedirect('/')
URLS.py ---> in student management app folder:
from django.urls import path, include
from . import views
from .import HodViews, StaffViews, StudentViews
urlpatterns = [
path('', views.loginPage, name="login"),
path('student_view_result/', StudentViews.student_view_result, name="student_view_result"),
path('study/', StudentViews.study, name="study"),
]
Urls.py for the whole system:
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from student_management_system import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('student_management_app.urls')),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
How could I resolve this error? And why it reported this error?
This is my site urls:
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('boards.urls'))
]
And this is my app urls:
urlpatterns = [
path('',views.home,name='home'),
path('boards/<int:pk>',views.board_topic,name='board_topic'),
path('boards/<int:pk>/new/',views.new,name='new_topic')
]
This is the Views for app:
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse,Http404
from .models import Board
# Create your views here.
def home(request):
board = Board.objects.all()
return render(request,'home.html',{
'board':board,
})
def board_topic(request,pk):
# try:
# board = Board.objects.get(pk=pk)
# except:
# raise Http404
board = get_object_or_404(Board,pk=pk)
return render(request,'topics.html',{
'board':board
})
def new(request,pk):
boards = get_object_or_404(Board, pk=pk)
return render(request, 'new_topic.html', {
'board' : boards
})
when I try to go to http://127.0.0.1:8000/boards/1/new/ then this error occurs:
enter image description here
please help me.
Here's how I was able to get rid of my error
In my app's url:
urlpatterns = [
path('',views.home,name='home'),
path('boards/<int:pk>',views.board_topic,name='board_topic'),
path('boards/<int:pk>/new/',views.new,name='new_topic')
]
In the second path I was using name= 'board_topic'
and in my templates file i was using url as href = ' url "board.pk board_topics" '
so that was why i was getting that error .
THANK YOU TO EVERYONE WHO RESPONDED
for god sake I can't understand why I'm getting this error, it looks to be simple stuff but I've made a lot of modifications now and don't know what exactly caused this:
(from Traceback):
File "C:\Users\Lucas Cyrne Ferreira\Desktop\django- tutorial\mysite\contas\urls.py", line 2, in <module>
from . import views
File "C:\Users\Lucas Cyrne Ferreira\Desktop\django-tutorial\mysite\contas\views.py", line 38
else:
^
SyntaxError: invalid syntax
from django.shortcuts import render, redirect, HttpResponse
from contas.forms import (
RegistrationForm,
EditPerfilForm,
)
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
def home(request):
return render(request, 'contas/home.html')
def register(request):
if request.method=='POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect(reverse('home:home'))
else:
form = RegistrationForm()
args = {'form':form}
return render(request, 'contas/reg_form.html', args)
def view_perfil(request):
args = {'user': request.user}
return render(request, 'contas/perfil.html', args)
def edit_perfil(request):
if request.method=='POST':
form = EditPerfilForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect(reverse('home:perfil')
else:
form = EditPerfilForm(instance=request.user)
args = {'form':form}
return render(request, 'contas/edit_perfil.html', args)
def trocar_password(request):
if request.method=='POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
return redirect(reverse('home:perfil')
else:
return redirect(reverse('home:trocar_password'))
else:
form = PasswordChangeForm(user=request.user)
args = {'form': form}
return render(request, 'contas/trocar_password.html', args)
My contas\urls.py:
from django.urls import path
from . import views
from django.contrib.auth.views import (
login,
logout,
PasswordResetView,
PasswordResetDoneView,
PasswordResetConfirmView,
PasswordResetCompleteView,
)
app_name = 'contas'
urlpatterns = [
path('', views.home, name='home'),
path('login/', login, {'template_name': 'contas/login.html'}, name='login'),
path('logout/', logout, {'template_name': 'contas/logout.html'}, name='logout'),
path('register/', views.register, name='register'),
path('perfil/', views.view_perfil, name='view_perfil'),
path('perfil/edit/', views.edit_perfil, name='edit_perfil'),
path('trocar-password/', views.trocar_password, name='trocar_password'),
path('reset-password/', PasswordResetView.as_view(), {'template_name': 'contas/reset_password.html', 'post_reset_redirect': 'contas:password_reset_done'},
name='reset_password'),
path('reset-password/done/', PasswordResetDoneView.as_view(), name='password_reset_done'),
path('reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/',
PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
path('reset-password/complete/', PasswordResetCompleteView.as_view(), name='password_reset_complete'),
]
Please help me guys, I was in the middle of a namespace tutorial... now I'm stuck on this.
You've got a missing closing parenthesis in line 39:
return redirect(reverse('home:perfil') # missing )
I'd definitely recommend using a linter such as flake8 in your project and finding a plugin for whatever code editor or IDE you use. It will find errors like and save you a lot of grief in the long run.
I'm trying to make a view redirect to another view so user's can't access it without a condition being met. In this case, a successful password change. I also want to achieve this using HttpResponseRedirect.
Now, I've never used reverse before, but I figured that this is the way to do that. Problem is that I can't get reverse to work. I get the following error:
ViewDoesNotExist at /account/password/
Could not import findadownload.main.views.foo. View does not exist in module findadownload.main.views.
# URLS
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
#SANDY
from findadownload.sandy.views import *
#TRIVIARIA
from findadownload.trivia.views import *
from findadownload.accounts.views import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'findadownload.main.views.presidium_home', name='presidium_home'),
(r'^web/$', 'findadownload.main.views.web'),
(r'^web/developers/$', sandy_developers),
#SANDY (for findadownload!)
(r'^get/sandy/$', get_sandy),
(r'^get/sandy/download/$', get_sandy_download),
(r'^sandy/register/$', sandy_registration),
(r'^sandy/complete/$', sandy_complete),
(r'^web/shared/$', sandy_shared_files),
(r'^web/remove/all/$', sandy_remove_all),
(r'^web/remove/(?P<file_id>\w+)/$', sandy_remove_file),
(r'^about/$', 'findadownload.main.views.about'),
(r'^pytech/$', 'findadownload.main.views.pytech'),
(r'^pytech/aboutus$', 'findadownload.main.views.pytech_about'),
(r'^pytech/services$', 'findadownload.main.views.pytech_services'),
(r'^pytech/support$', 'findadownload.main.views.pytech_support'),
(r'^pytech/contactus$', 'findadownload.main.views.pytech_contact'),
(r'^pytech/sitemap$', 'findadownload.main.views.pytech_sitemap'),
(r'^pytech/search/$', 'findadownload.main.views.pytech_search'),
(r'^presidium', 'findadownload.main.views.presidium_home'),
#TRIVIARIA
(r'^register/$', register),
(r'^login/$', login_view, {'template': 'trivia/registration/login.html'}),
(r'^logout/$', logout_view),
(r'^trivia/$', submit_question, {'template': 'trivia/trivia_questions.html'}),
(r'^challenges/$', submit_question, {'template': 'trivia/trivia_challenges.html'}),
(r'^question/thanks/$', question_thanks),
(r'^question/answer/$', submit_answer),
(r'^question/answer/result/(\d+)/(.*)/$', answer_result),
(r'^question/answer/challenge/$', challenge_answer),
(r'^account/$', upload_avatar),
(r'^account/password/$', password_change),
url(r'^account/password/success/$', 'findadownload.accounts.views.password_success'),
(r'^(?P<username>\w+)/$', view_user_profile, {'template': 'trivia/trivia_view_user_questions.html'}),
(r'^(?P<username>\w+)/trivia/$', view_user_profile, {'template': 'trivia/trivia_view_user_questions.html'}),
(r'^(?P<username>\w+)/challenges/$', view_user_profile, {'template': 'trivia/trivia_view_user_challenges.html'}),
#FILE SHARING
(r'^web/share/(?P<file_id>\w+)/$', sandy_download),
(r'^web/report/(?P<file_id>\w+)/$', sandy_file_report),
(r'^web/like/(?P<file_id>\w+)/$', like_download),
#OTHER
(r'^web/profile/$', 'findadownload.main.views.web_profile'),
(r'^web/edit/$', 'findadownload.main.views.web_edit'),
(r'^trivia/$', 'findadownload.main.views.trivia_home', {'template': 'trivia/registration/index.html'}),
(r'^web/get/$', 'findadownload.main.views.web_get'),
(r'^web/progress/$', 'findadownload.main.views.web_progress'),
(r'^web/foo/$', 'findadownload.main.views.foo'),
(r'^web/search/$', 'findadownload.main.views.web_search'),
(r'^web/logout/$', 'findadownload.main.views.web_logout'),
(r'^web/resend/$', 'findadownload.main.views.web_resend'),
(r'^web/home/$', 'findadownload.main.views.web_home'),
(r'^web/history/$', 'findadownload.main.views.web_history'),
(r'^web/verify/(?P<link>\w+)/$', 'findadownload.main.views.web_activate'),
(r'^web/help/(?P<username>\w+)/$', 'findadownload.main.views.web_help'),
(r'^web/welcome/(?P<username>\w+)/$', 'findadownload.main.views.welcome'),
(r'^web/terms/$', 'findadownload.main.views.web_terms'),
(r'^web/privacy/$', 'findadownload.main.views.web_privacy'),
(r'^web/signup/$', 'findadownload.main.views.web_signup'),
(r'^web/login/$', 'findadownload.main.views.web_login'),
(r'^test$', 'findadownload.main.views.test'),
# url(r'^findadownload/', include('findadownload.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
if 1:
urlpatterns += patterns('',
url(r'^uploads/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
'show_indexes': True,
}),
)
urlpatterns += staticfiles_urlpatterns()
# VIEWS
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from findadownload.accounts.forms import *
from django.contrib.auth.models import User
from django.contrib import auth
from findadownload.accounts.models import *
from django.core.urlresolvers import reverse
from findadownload.trivia.models import *
def password_success(request):
return render_to_response('trivia/trivia_password_success.html')
def password_change(request):
if request.user.is_authenticated():
# if for is submitted
if request.method == 'POST':
form = PasswordForm(user=request.user, data=request.POST)
# for the avatar part
if form.is_valid():
cd = form.cleaned_data
request.user.set_password(cd['confirm_password'])
request.user.save()`enter code here`
# redirect to profile page after POST
return HttpResponseRedirect(reverse('findadownload.accounts.views.password_success'))
else:
form = PasswordForm(user=request.user)
# render empty form
return render_to_response('trivia/trivia_password_change.html', {'form': form},
context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/login/?next=%s' % request.path)
You have to specify name kwargs in you url, in this case :
url(r'^account/password/success/$', 'findadownload.accounts.views.password_success', name = 'password_success')
Then use reverse like this :
return HttpResponseRedirect(reverse('password_success'))
What you pass in reverse is the name kwarg on urlpatterns.
EDIT:
Can i see the rest of your urls.py. I think the problem is not on reverse, because Django can't find view named foo.