Problem with a new version of django and python code [duplicate] - python

This question already has answers here:
AttributeError: module 'django.contrib.auth.views' has no attribute 'login'
(2 answers)
Closed 3 years ago.
I'm stuck with Django here, I have added the code of views.py and urls.py below. I'm getting the following error:
This is the error im getting
Please look into it and help me if there is any solution to it.
The error is at the bottom of the image.
views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from .models import Post, Comment
from .forms import PostForm, CommentForm
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
# Create your views here.
class AboutView(TemplateView):
template_name = 'blog/about.html'
class PostListView(ListView):
model = Post
def get_queryset(self):
return
Post.objects.filter(published_date__lte=timezone.now()).order_by('-
published_date')
class PostDetailView(DetailView):
model = Post
class CreatePostView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
class PostUpdateView(LoginRequiredMixin,UpdateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
class PostDeleteView(LoginRequiredMixin,DeleteView):
model = Post
success_url = reverse_lazy('post_list')
class DraftListView(LoginRequiredMixin,ListView):
login_url = '/login/'
redirect_field_name = 'blog/post_draft_list.html'
model = Post
def get_queryset(self):
return
Post.objects.filter(published_date__isnull=True).order_by('created_date')
#login_required
def post_publish(request, pk):
post = get_object_or_404(Post, pk=pk)
post.publish()
return redirect('post_detail', pk=pk)
#login_required
def add_comment_to_post(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('post_detail', pk=post.pk)
else:
form = CommentForm()
return render(request, 'blog/comment_form.html', {'form': form})
#login_required
def comment_approve(request, pk):
comment = get_object_or_404(Comment, pk=pk)
comment.approve()
return redirect('post_detail', pk=comment.post.pk)
#login_required
def comment_remove(request, pk):
comment = get_object_or_404(Comment, pk=pk)
post_pk = comment.post.pk
comment.delete()
return redirect('post_detail', pk=post_pk)
***This is urls.py***
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views
urlpatterns = [
path('', include('blog.urls')),
path('admin/', admin.site.urls),
path('accounts/login/', views.login, name='login'),
path('accounts/logout/', views.logout, name='logout', kwargs=
{'next_page': '/'}),
]
from django.urls import path
from . import views
urlpatterns = [
path('',views.PostListView.as_view(),name='post_list'),
path('about/',views.AboutView.as_view(),name='about'),
path('post/<int:pk>', views.PostDetailView.as_view(), name='post_detail'),
path('post/new/', views.CreatePostView.as_view(), name='post_new'),
path('post/<int:pk>/edit/', views.PostUpdateView.as_view(),
name='post_edit'),
path('drafts/', views.DraftListView.as_view(), name='post_draft_list'),
path('post/<int:pk>/remove/', views.PostDeleteView.as_view(),
name='post_remove'),
path('post/<int:pk>/publish/', views.post_publish, name='post_publish'),
path('post/<int:pk>/comment/', views.add_comment_to_post,
name='add_comment_to_post'),
path('comment/<int:pk>/approve/', views.comment_approve,
name='comment_approve'),
path('comment/<int:pk>/remove/', views.comment_remove,
name='comment_remove'),
]
Please let me know what the mistake is.
The above files are views.py, urls.py for app as well.
Look at the image the error has been mentioned at the bottom.

Based on the error try this url for django login view:
path('login/', views.LoginView.as_view(), name='login'),

Related

Django Login Required Redirect

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/'

Trying a write a simple program and keep getting this error

Error : TemplateDoesNotExist at /1
forms.py
class SpotifyForm(forms.Form):
SpotifyForm = forms.CharField(label= "Spotify Form")
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views import View
from .forms import SpotifyForm
from .api import SpotifyAPI
from .forms import ClientId
class Search(View):
form = SpotifyForm
initial = {"initial" : "Error"}
template_name = "homepage.html"
context = {"form": form}
def get(self, request, *args, **kwargs):
form = self.form(initial = self.initial)
return render(request , self.template_name, self.context)
urls.py
from django.urls import path
from .views import Search
urlpatterns = [
path("1" , Search.as_view())
]
templates directory: spotify_client\spotify_calls\spotify_calls\templates
urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path("" , include("spotify_calls.urls"))
]
Basically, all I am doing is trying to access the Spotify API in the views.py(not done yet), just wanted to render the html to at least see if the form will show but nothing did. Also, all recommendations with class based views will be appreciated since this is my first time
according to the Django docs :
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views import View
from .forms import MyForm
class MyFormView(View):
form_class = MyForm
initial = {'key': 'value'}
template_name = 'form_template.html'
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
# <process form cleaned data>
return HttpResponseRedirect('/success/')
return render(request, self.template_name, {'form': form})

I am trying to solve a circular import error,I spent hours in vain

I get this error: The included URLconf 'liskerproject.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
liskerproject is the root directory and contains the root "urls.py".
Lisk is another directory that contains "url.py"
This is how my root urls look like:
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path,include
from users import views as user_views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('edit/',user_views.edit,name='edit'),
path('',include('Lisk.url')),
path('register/',user_views.register,name='register'),
path('login/',auth_views.LoginView.as_view(template_name='user_templates/login.html'),name='login'),
path('logout/',auth_views.LogoutView.as_view(template_name='user_templates/logout.html'),name='logout')
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is how Lisk.url looks like:
from django.urls import path
from .views import Politics_topic,Questionpolitics,Updatepolitics,Politics_post_details,Deletepoliticspost,Profile,home
from . import views
urlpatterns = [
path('',home,name='home'),
path('about/',views.about,name = 'about Lisk'),
path('interests/',views.interests,name='interests'),
path('profile/',Profile.as_view(template_name='lisk_templates/profile.html'),name = 'profile'),
path('politics_topic/', Politics_topic.as_view(template_name='lisk_templates/politics_topic_template.html'),
name='Politics_topic'),
path('ask_politics/', Questionpolitics.as_view(template_name='lisk_templates/ask_politics_template.html'),
name='ask_politics'),
path('politicspost/<int:pk>/',Politics_post_details.as_view(template_name='lisk_templates/politics_post_details.html'),
name='politics_post_details'),
path('politicspost/<int:pk>/update/',Updatepolitics.as_view(template_name='lisk_templates/ask_politics_template.html'),
name='updatepoliticspost'),
path('politicspost/<int:pk>/delete/',Deletepoliticspost.as_view(template_name='lisk_templates/delete_politics_confirmation.html'),name ='deletepoliticspost')
]
This how Lisk.views look like:
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post, PoliticsPost
from django.contrib.auth.decorators import login_required
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
def home(request):
return render(request, 'lisk_templates/home_template.html')
def about(request):
return render(request, 'lisk_templates/about_template.html')
#login_required
def interests(request):
return render(request, 'lisk_templates/interests_template.html')
class Profile(LoginRequiredMixin,ListView):
model = Post
context_object_name = 'post'
ordering = ['-date_posted']
#POLITICS-------------
class Politics_topic(ListView):
model= PoliticsPost
context_object_name = 'politicsposts'
ordering = ['-date_posted']
class Politics_post_details(DetailView):
model = PoliticsPost
context_object_name = 'politicsposts'
class Questionpolitics(LoginRequiredMixin, CreateView):
model = PoliticsPost
fields =['question','description']
success_url = reverse_lazy('Politics_topic')
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class Updatepolitics(LoginRequiredMixin,UserPassesTestMixin,UpdateView):
model = PoliticsPost
fields = ['question','description']
success_url = reverse_lazy('Politics_topic')
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class Deletepoliticspost(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = PoliticsPost
success_url = reverse_lazy('Politics_topic')
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
#POLITICS-------------
I found a solution guys, it is pretty simple.
I removed
from .views import Politics_topic,Questionpolitics,Updatepolitics,Politics_post_details,Deletepoliticspost,Profile,home
In Lisk.url
I only used from . import views and I called all the functions in views,py with the dot operator.
Don't ask me how it worked, but it did work.

404 Page Not Found "GET /accounts/login/?next=/profile/ HTTP/1.1" 404

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

regist() got an unexpected keyword argument 'template_name'

i got a error that
TypeError at /accounts/regist/
regist() got an unexpected keyword argument 'template_name' .
i can understand there is no variable in my file.
but,in login,no template_name file can be worked.
So,i cannot know how to fix it.
I wrote in urls.py of accounts,
from django.conf.urls import url
from . import views
from django.contrib.auth.views import login, logout
urlpatterns = [
url(r'^login/$', login,
{'template_name': 'registration/accounts/login.html'},
name='login'),
url(r'^logout/$', logout, name='logout'),
url(r'^regist/$', views.regist,
{'template_name': 'registration/accounts/regist.html'},
name='regist' ),
url(r'^regist_save/$', views.regist_save, name='regist_save'),
]
in views.py
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.decorators.http import require_POST
from .forms import RegisterForm
def index(request):
context = {
'user': request.user,
}
return render(request, 'accounts/index.html', context)
#login_required
def profile(request):
context = {
'user': request.user,
}
return render(request, 'accounts/profile.html', context)
def regist(request):
form = RegisterForm(request.POST or None)
context = {
'form': form,
}
return render(request, 'accounts/regist.html', context)
#require_POST
def regist_save(request):
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
return redirect('main:index')
context = {
'form': form,
}
return render(request, 'accounts/regist.html', context)
if i have to define template_name,which file should i write it and how?
Are there differences to make system login page and regist page?
You don't have to specify a template_name when you are using your own function-based view, so just remove the {'template_name': 'registration/accounts/regist.html'} bit from the registration URL.

Categories