__init__() takes exactly 1 argument (3 given) - django

Error
response = callback(request,*callback_args,**callback_kwargs)
Exception Type: TypeError at /accounts/profile/
Exception Value: __init__() takes exactly 1 argument (3 given)
Here is my code
urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.defaults import *
from django.contrib.auth.views import password_reset, password_reset_done, password_change, password_change_done
from django.views.generic import TemplateView
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('registration.urls')),
(r'^accounts/profile/$', TemplateView, {'template': 'registration/profile.html'}),
(r'^accounts/password_reset/$', password_reset, {'template_name': 'registration/password_reset.html'}),
(r'^accounts/password_reset_done/$', password_reset_done, {'template_name': 'registration/password_reset_done.html'}),
(r'^accounts/password_change/$', password_change, {'template_name': 'registration/password_change.html'}),
(r'^accounts/password_change_done/$', password_change_done, {'template_name': 'registration/password_change_done.html'}),
)
views.py
from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from models import RegistrationProfile
from forms import RegistrationForm
from django.core.context_processors import csrf
def activate(request, activation_key):
activation_key = activation_key.lower() # Normalize before trying anything with it.
account = RegistrationProfile.objects.activate_user(activation_key)
return render_to_response('registration/activate.html',{
'account': account,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS
}, context_instance=RequestContext(request))
c = {} c.update(csrf(request))
def register(request, success_url='/accounts/register/complete/'):
form = RegistrationForm()
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
new_user=RegistrationProfile.objects.create_inactive_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
return HttpResponseRedirect(success_url)
return render_to_response('registration/registration_form.html', {
'form': form
}, context_instance=RequestContext(request))

Your current error is caused by passing TemplateView into your url conf. It should be TemplateView.as_view().
urlpatterns = patterns('',
#...
(r'^accounts/profile/$', TemplateView.as_view(template= 'registration/profile.html')),
#...
)

Related

I'm trying to add a new page in Django but getting 404 error yet I've added urls and views

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?

Why am I getting error 404 in my django project when everything seems correct?

I have two apps in my Django project:basket and store. In root url files I configured the urls.py like this:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('store.urls', namespace='store')),
path('basket/', include('basket.urls', namespace='basket')),
store/urls.py:
from django.urls import path
from . import views
app_name = 'store'
urlpatterns = [
path('', views.all_products, name='all_products'),
path('<slug:slug>/', views.product_detail, name='product_detail'),
path('category/<slug:category_slug>/',
views.category_list, name='category_list')
]
basket/urls.py:
from django.urls import path
from . import views
app_name = 'basket'
urlpatterns = [
path('', views.basket_summary, name='basket_summary'),
path('add/', views.basket_add, name='basket_add'),
]
I am getting an error:
Page not found(404)
Request Method:GET
Request URL:http://127.0.0.1:8000/basket/
Raised by:store.views.product_detail
this is my store/views.py:
from django.shortcuts import get_object_or_404, render
from .models import *
def product_detail(request, slug):
product = get_object_or_404(Product, slug=slug, in_stock=True)
context = {
'product': product,
}
return render(request, 'store/products/detail.html', context)
please help me solve this problem i've been stuck on this for a long time.
Try this way if you want to avoid 404 error:
from django.shortcuts import get_object_or_404, render
from .models import *
def product_detail(request, slug):
try:
product = Product.objects.get(slug=slug, in_stock=True)
context = {
'product': product,
}
except Product.DoesNotExist:
raise ValidationError('Product Does not exist ')
return render(request, 'store/products/detail.html', context
)

My url not reading my function in views.py in DJANGO (found similar question not able to trace my issue)

mysite/urls.py
from django.contrib.auth import views
from django.views.generic.base import TemplateView
urlpatterns = [
url('update_db/(<dbname>)/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
url('mysite/login/', auth_views.LoginView.as_view(),name='login'),
url(r'^fetch/',include('polls.urls')),
url('mysite/logout/$', auth_views.logout, name='logout'),
]
polls.urls.py
from django.conf.urls import url
from . import views
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
urlpatterns = [
url('update_db/(?P<dbname>\w+)/$', login_required(views.MyView.get), name='x'),
url('', login_required(views.IndexView.as_view())),
]
fetch.html
<td>click</td>
polls/views.py
from django.shortcuts import render
from django.views.generic import TemplateView , ListView
from django.views.generic.edit import UpdateView
# Create your views here.
from django.http import HttpResponse
from .models import Item , DbRestorationLogDetails
class MyView(UpdateView):
logger.error('Something went wrong!')
print "THANKS FOR UPDATING"
template_name='fetch.html'
model = DbRestorationLogDetails
fields =['verification_status']
def get(self,request, dbname):
usname=request.user
print usname
print dbname
if request.method == "GET":
dblog = DbRestorationLogDetails.objects.get(dbname=dbname)
dblog.verification_status = 'Verified'
print dblog.verification_status
dblog.save()
#.update(dblogdetails.verification_status = 'Verified')
return HttpResponseRedirect(request.GET.get('next'))
NOTE: NOT able to reach to MyView.get() and no db update happening. I assume my code is not able to read my function.

Django NoReverseMatch Error

I'm trying to develop a blog script with Django. But when I want to show post links, I get NoReverseMatch error.
My views.py
# -*- coding: utf-8 -*-
# Create your views here.
from .models import Yazi, Yorum, Kategori
from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response
from django.template import RequestContext, loader
from django.contrib.sites.models import Site
def Home(request):
try:
posts = Yazi.objects.filter(yayinlanmis=True).order_by('-yayinlanma_tarihi')
except Yazi.DoesNotExist:
raise Http404
site = Site.objects.get_current()
c = RequestContext(request,{
'posts':posts,
'site':site
})
return render_to_response('Penguencik_Yazilar/yazi_list.html', c)
def Detail(request, slug):
post = Yazi.objects.get(slug=slug)
site = Site.objects.get_current()
c= RequestContext(request,{
'posts':post,
'site':site
})
return render_to_response('Penguencik_Yazilar/yazi_detail.html',c)
Urls.py in application folder.
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^$', views.Home,name='index'),
url(r'^/makale/(?P<slug>[0-9A-Za-z._%+-]+)$', views.Detail,name='detail'),
)
Urls.py in project folder
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', include('Penguencik_Yazilar.urls',namespace='blog')),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
And template code. What am I doing wrong?
{% load url from future %}
...
Read
Try to change this:
Read
to:
Read
Cause your view expect slug keyword here (?P<slug>[0-9A-Za-z._%+-]+).

Django - Why doesn't reverse work?

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.