NameError: name 'View' is not defined in views.py - python

I am trying to define a class in views.py which is inheriting generic view. The code is as follows. On running server I get the error that
class UserFormView(View):
NameError: name 'View' is not defined
although I have imported generic. Please let me know the reason.
from django.views import generic
from django.utils import timezone
from django.shortcuts import render, get_object_or_404,render_to_response,redirect
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.contrib.auth import authenticate,login
from django.core.context_processors import csrf
from .forms import UserForm
# Create your views here.
def home(request):
return render(request, 'fosssite/home.html')
def login(request):
c={}
c.update(csrf(request))
return render_to_response('fosssite/login.html',c)
class UserFormView(View):
form_class=UserForm
template_name='fosssite/signup.html'
def get(self,request):
form=self.form_class(None)
return render(request,self.template_name,{'form':form})
#validate by forms of django
def post(self,request):
form=self.form_class(request.POST)
if form.is_valid():
# not saving to database only creating object
user=form.save(commit=False)
#normalized data
username=form.cleaned_data['username']
password=form.cleaned_data['password']
#not as plain data
user.set_password(password)
user.save() #saved to database
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('/loggedin')#url in brackets
else:
return HttpResponseRedirect('/invalid')
def loggedin(request):
return render_to_response('fosssite/loggedin.html',{'fullname':request.user.username})
def logout(request):
auth.logout(request)
return render_to_response('fosssite/logout.html')
def invalid_login(request):
return render_to_response('fosssite/invalid_login.html')
`

You need to either import View explicitly:
from django.views.generic import View
or refer to it as generic.View:
class UserFormView(generic.View):
# ...

The View name needs to be imported. Add the following import statement:
from django.views.generic import View
Or use the already imported generic module in
class UserFormView(generic.View)
# ^

in urls.py
from my_app import views
eg code:
urls.py
from django.conf.urls import url
from django.contrib import admin
from pro1 import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^admin/', admin.site.urls),
]
views.py
from django.shortcuts import render
def home(request):
template="home.html"
context={}
return render(request,template,context)
guess it will solve the problem.

Related

How implement django.views.generic for logoutPage/loginPage if earlier used request?

What is the best practice for migration from request to django.views.generic?
How implement django.views.generic for logoutPage/loginPage if earlier used request?
#This my model.py
from django.db import models
from django.contrib.auth.models import User
#This my view.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import *
from django.contrib.auth import login,logout,authenticate
from .forms import *
from django.views.generic import ListView
def logoutPage(request):
logout(request)
return redirect('/')
def loginPage(request):
if request.user.is_authenticated:
return redirect('home')
else:
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:
print("working")
login(request,user)
return redirect('/')
context={}
return render(request,'book/templates/login.html',context)
You can try the simplest way or a slightly more complicated but giving more possibilities in the future.
If you don't need any modifications (and usually one doesn't at early stage), you can do it directly in your main urls.py file:
from django.contrib.auth import views as auth_views
urlpatterns = [
...
path('login/', auth_views.LoginView.as_view(template_name='book/templates/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]
Alternatively you can create your own classes, that inherit from that views. Obviously, you can set proper path() for each in urls.py.
from django.contrib.auth import views as auth_views
class LoginPage(auth_views.LoginView):
template_name='book/templates/login.html'
...
class LoginPage(auth_views.LogoutView):
...
For both you can set redirect page with variables set in settings.py with wanted path name (it means the name="welcome" part):
LOGIN_REDIRECT_URL = "user_profile"
LOGOUT_REDIRECT_URL = "come_back_please"

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.

Please why is there a circular import error

I am working on a django project, but it returns the included urlconf "myapp.urls"does not appear to have any patterns in it.
I tried checking my views to ensure I imported everything correctly
from django.contrib import admin
from django.urls import path
from .views import home
from accounts.views import login_view
urlpatterns = [
path('admin/', admin.site.urls),
path('',home),
path('accounts/login/', login_view),
]
I expect the site to run and redirect me to the login page
This is my views in the same directory with the urls.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
#login_required
def home(request):
return render(request,"home.html")
This is the views.py for the accounts.
from django.shortcuts import render,redirect
from django.contrib.auth import(
authenticate,
get_user_model,
login,
logout
)
from .forms import UserLoginForm, UserRegisterForm
def login_view(request):
next = request.GET.get('next')
form = UserLoginForm()
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username,password=password)
login(request,user)
if next:
return redirect(next)
return redirect("/")
context = {
'form': form,
}
return render(request, "login.html",context)
When I run your project on Django 2.2, I don't see a circular import. Instead I see the error:
django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form UserRegisterForm needs updating.
Looking at your form, you haven't set fields, you have model = Userfields = [...] instead.
class UserRegisterForm(forms.ModelForm):
...
class Meta:
model = Userfields = [
'username',
'email',
'password',
"c_password"
]
Change it so that you set fields. You can remove 'password' and 'c_password' since you define these on your form separately.
class UserRegisterForm(forms.ModelForm):
...
class Meta:
fields = [
'username',
'email',
]

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

Form not Displaying in Django 1.8

I am making a form using Django 1.8 and Python 3.5
But the form is not showing up,IDK why ?
This are my files respectivel
urlpatterns = [
url(r'^login', 'login.views.login', name='login'),
url(r'^admin/', include(admin.site.urls)),
] + static(settings.STATIC_URL , document_root=settings.STATIC_ROOT)
login/view.py==
from django.shortcuts import render
from .forms import allusers1
# Create your views here.
def login(request):
form1=allusers1()
context = {
"form1": form1
}
return render(request, "login.html",context)
login/forms.py==
from django import forms
from .models import allusers1
class signupform(forms.ModelForm):
class Meta:
model = allusers1
fields = ['name','phoneno']
login/models.py
from django.db import models
# Create your models here.
class allusers1(models.Model):
name=models.CharField(max_length=400)
phoneno=models.CharField(max_length=10)
otp=models.IntegerField()
# def __str__(self):
# return self.name
login.html
{{form1}}
output
allusers1 object
But output should have been Name and ,Email fields for input
WHAT IS THE ERROR ?
Your form is actually named signupform, and not allusers1.
In your views.py, you should import your form like this:
from django.shortcuts import render
from .forms import signupform # <= here
# Create your views here.
def login(request):
form1=signupform() # <= and here
context = {
"form1": form1
}
return render(request, "login.html",context)

Categories