#Reverse for 'user_profile_view' with arguments '(u'Emmanuel',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] :
#project/urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'', include('app.urls', namespace='app')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#app/urls.py
from .views import *
from . import views
from django.conf import settings
from django.conf.urls import url
from django.views.generic import TemplateView
from django.conf.urls.static import static
app_name = 'app'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^accounts/home_page/$', home_page),
url(r'^accounts/home_page/(?P<username>[\w-]+)/$', UserProfileView.as_view(), name='user_profile_view'),
# url(r'^accounts/profile/$', views.user_profile, name='user_profile'),
# url(r'^accounts/profile/edit/$', views.edit_user_profile,
# name='edit_user_profile'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#views.py
class UserProfileView(View):
#method_decorator(login_required)
def get(self, request, user):
if request.user.username == user:
profile = get_object_or_404(User, user=request.user)
return render(request, 'registration/home.html', {'profile': profile})
else:
raise Http404
#login_required
def home_page(request):
return HttpResponseRedirect(
reverse('user_profile_view', args=[request.user.username], current_app='app'))
So what I'm actually trying to do is allow a user login with is name appearing in the url but since the LOGIN_REDIRECT_URL = '/accounts/home_page' cannot take a dynamic parameter like I am using a redirect. But I get this error please what am I doing wrong.
Thanks in advance!!!
#views.py
class UserProfileView(View):
#method_decorator(login_required)
def get(self, request, username):
if request.user.username == username:
profile = get_object_or_404(UserExtended, user=request.user)
return render(request, 'registration/home.html', {'profile': profile})
else:
raise Http404
#login_required
def home_page(request):
return HttpResponseRedirect(
reverse('app:user_profile_view',
args=[request.user.username], current_app='app'))
So I changed the when Followed what #ShanWang said I got the error:
TypeError Exception Value: get() got an unexpected keyword argument 'username'
that as because my def get(self, request, username): was def get(self, request, user): so I changed that and
if request.user.username == user:
to
if request.user.username == username:
That did the trick
Related
Im trying to redirect a user when he isn't logged in the my LoginPage.
I Have Tried Many Different solutions - Like #login_required & request.user.is_authenticated - yet nothing worked...
im leaving my views.py & urls.py so someone can see if they can spot the problem
Thanks For Any Help!
Views.Py:
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render,redirect
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
# Create your views here.
#login_required(login_url='/Login')
def Dashboard(request):
if request.user.is_authenticated:
return render(request, 'home/index.html')
else:
return LoginPage(request)
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:
request.session.set_expiry(86400)
login(request, user)
return redirect('dashboard')
return render(request,'accounts/login.html')
def registerPage(request):
form = UserCreationForm()
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
user = form.cleaned_data.get('username')
messages.success(request, "Account Created for " + user + " Succesfully" )
return redirect('login')
context = {'form': form}
return render(request, 'accounts/register.html', context)
def Admin(request):
return HttpResponseRedirect(reverse('admin:index'))
def Logout(request):
authenticate.logout(request)
logout(request)
return LoginPage(request)
Urls.Py:
from django.urls import path
from. import views
from django.contrib import admin
from django.urls import path, reverse_lazy
from django.views.generic.base import RedirectView
urlpatterns = [
path('',views.LoginPage),
path("Login", views.LoginPage, name="login"),
path("Register", views.registerPage,name="register"),
path("admin", views.Admin, name="admin"),
path("dashboard", views.Dashboard, name="dashboard"),
path('', RedirectView.as_view(url=reverse_lazy('admin:index'))),
path('admin/', admin.site.urls),
path("Login", views.logout, name="logout"),
Hlooo
Instead of this
#login_required(login_url='/Login')
Try this
#login_required(login_url='login')
use small 'l' since you used small 'l' in name = 'login'
This worked in my project , if user is not authenticated he will be
redirected to login page
In your settings.py, try add
LOGIN_URL = '/Login/'
also after logout, send them to the login page
LOGOUT_URL = '/Login/'
Can someone help me in figuring out where I went wrong?
Project URLs
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('trips/',include('trips.urls')),
path('customers/',include('customers.urls')),
path('drivers/',include('drivers.urls')),
path('vehicles/',include('vehicles.urls')),
path('admin/', admin.site.urls),
]
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
App URLs
from django.urls import path
from . import views
urlpatterns = [
path('',views.customers, name='customers'),
path('<int:pk>/', views.customer_details, name='customer_details'),
]
App View
from django.shortcuts import render, get_object_or_404
from .models import *
# Create your views here.
def customers(request):
customers = Customer.objects.all().order_by('id')
return render(request, "customers.html", {'customers': customers, 'custactive': "active"})
def customer_details(request, pk):
customer = get_object_or_404(Customer, pk=pk)
return render(request, "/customer_details.html", {'customer': customer})
How I'm calling the page
<td>{{customer.name}}</td>
I'm hoping to render the template at localhost/customers/id
Help is really appreciated.
In your function customer_details you return :
return render(request, "/customer_details.html", {'customer': customer})
You have to return "customer_details.html" without the / :
return render(request, "customer_details.html", {'customer': customer})
After filling the page should appear 'done', but i have an error message:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/candidate/done.html
The current path, candidate/done.html, didn't match any of these.
Can't configure redirect to 'done' page.
Here views.py:
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import AnketaForm
from .models import Anketa
def anketa_create_view(request):
if request.method == 'POST':
form = AnketaForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('candidate/done.html')
else:
form = AnketaForm()
return render(request, 'candidate/anketa_create.html', {'form': form})
urls.py (apps/candidate)
from django.urls import path
from . import views
urlpatterns = [
path('', views.anketa_create_view, name = 'anketa_create_view'),
]
urls.py
from django.contrib import admin
from django.urls import path, include
from candidate.views import anketa_create_view
urlpatterns = [
path('done/', anketa_create_view),
path('', anketa_create_view),
path('grappelli/', include('grappelli.urls')),
path('admin/', admin.site.urls),
]
you need to give a name to the done url
path('done/', anketa_create_view, name='done'),
and can do with reverse
return HttpResponseRedirect(reverse('done'))
or you can do redirect shortcut
return redirect('done')
Remove in urls.py
path('done/', anketa_create_view)
and replace in views.py
return HttpResponseRedirect('candidate/done.html')
to
return render(request, 'candidate/done.html', {})
I am getting some issues with my urls. I don't have any 'account/' route but i when I want to visit 'login/' and after logging in it should redirect me to my profile... but it is taking me to this route: "http://127.0.0.1:8000/accounts/login/?next=/profile/"
I am sorry if I've posted any unnecessary kinds of stuff:
mainapp.urls
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path, include
from forms.views import RegisterView,LoginView
from django.conf import settings
from django.conf.urls.static import static
from user_profile import views as profile_views
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/',RegisterView.as_view(), name='register'),
path('login/', LoginView.as_view(), name = 'login'),
path('profile/',profile_views.profile,name='profile'),
path('updateprofile/',profile_views.updateprofile,name='update_profile'),
path('',include('blog.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
forms.views(Login/Logout)View
from django.shortcuts import render, redirect,reverse
from django.http import HttpResponse
from django.contrib.auth import authenticate, get_user_model, logout
from django.utils.http import is_safe_url
from django.contrib.auth.decorators import login_required
from django.views.generic import CreateView, FormView
from .models import User
from .forms import RegisterForm,LoginForm
class LoginView(FormView):
form_class = LoginForm #instance
template_name = 'forms/login.html'
success_url = '/profile/'
def User_logout(request):
if request.method == "POST":
logout(request)
return redirect(reverse('login'))
LoginForm:
class LoginForm(forms.Form):
email = forms.EmailField(label='email')
password = forms.CharField(widget=forms.PasswordInput)
def form_valid(self,form):
request=self.request
next_=request.GET.get('next')
next_post=request.POST.get('next')
redirect_path=next_ or next_post or None
email=form.cleaned_data.get('email')
password=form.cleaned_data.get('password')
user=authenticate(username=email, password=password)
if user is not None:
login(request, user)
try:
del request.session['UserProfile.html']
except:
pass
if is_safe_url(redirect_path, request.get_host()):
return redirect(redirect_path)
else:
return redirect("login")
return super(LoginView, self).form_invalid(form)
set a variable in your urls.py of you mainapp as following
appname='mainapp'
now in your login view add following
def get_success_url(self):
return reverse('mainapp:profile')
Currently, in Django 3.2, the reverse method is written this way:
def get_success_url(self):
return reverse('profile')
No need to add appname var in your urls.py
I'm experimenting with Django forms. I'm trying to create a form which will accept the name of a city as input and output coordinates as output. My apps name is rango. I'm having a lot of trouble in URL reverse after accepting the input of the form..
My project/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
import os
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^rango/',include('rango.urls', namespace="rango")),
)
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}), )
My rango/urls.py (rango is the name of the app):
from django.conf.urls import patterns, url
from rango import views
urlpatterns = patterns('',
url(r'^welcome/$', views.index, name='index'),
url(r'^about/$', views.about, name='about_page'),
url(r'^categories/(?P<name_dir>\w+)/$',views.cats,name='cats'),
url(r'^disp_page/(?P<city>\w+)/$',views.geo,name='coods'),
url(r'^disp_page/$', views.disp_page, name='disp_page')
My forms.py:
from django import forms
from rango.models import Page, Category
class PageForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the name of the city.")
#url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.")
#views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
class Meta:
# Provide an association between the ModelForm and a model
model = Page
exclude = ('category','url','views')
My views.py:
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from rango.models import Category,Page
from pygeocoder import Geocoder
from rango.forms import PageForm
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
import operator
# Create your views here.
def geo(request,city):
context = RequestContext(request)
citydata=Geocoder.geocode(city)
codtuple=citydata[0].coordinates
codtuple=list(codtuple)
context_dict = {'cood':codtuple}
return render_to_response('coods.html',context_dict,context)
def disp_page(request):
# A HTTP POST?
if request.method == 'POST':
form = PageForm(request.POST)
# Have we been provided with a valid form?
if form.is_valid():
# Save the new category to the database.
#form.save(commit=True)
city = form.cleaned_data['title']
# context = RequestContext(request)
#citydata=Geocoder.geocode(cityname)
#codtuple=citydata[0].coordinates
#codtuple=list(codtuple)
#context_dict = {'cood':codtuple}
return HttpResponseRedirect(reverse('rango:geo', args=(request,city)))
else:
# The supplied form contained errors - just print them to the terminal.
print form.errors
else:
# If the request was not a POST, display the form to enter details.
form = PageForm()
# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
return render(request, 'disp_page.html', {'form': form})
Basically the disp_page displays the form. I type the name of a city in the form(EX:NEWYORK) and then it has to redirect to the "geo" function in my views.py which would output the coordinates in a different view. This redirection doesn't seem to be happening. Any help is appreciated!!
change this line
url(r'^disp_page/(?P<city>\w+)/$',views.geo,name='coods'),
in rango/urls.py to :
url(r'^disp_page/(?P<city>\w+)/$',views.geo,name='geo'),
and use :
return HttpResponseRedirect(reverse('rango:geo', args=(city,)))