how to add more options on django signup generic views? - python

I know that Django has class-based generic views which give us ability to (for instance signup) signup users, but it has a little option and I want to add more fields to it, How can I do it?
Thanks;
In the views.py
from django.views.generic import CreateView
from django.contrib.auth.forms import UserCreationForm
from django.core.urlresolvers import reverse_lazy
class SignUpView(CreateView):
form_class = UserCreationForm
template_name = "profiles/signup.html"
success_url = reverse_lazy('profiles_home')
In the urls.py
urlpatterns = patterns('profiles.views',
url(r'^signup', SignUpView.as_view(), name="profiles_signup"),
)
I want to add E-mail, First and Last name, ... fields.

Related

Login Button not redirecting back to home page

I am not getting redirected back to the homepage for some reason. I checked the creds to make sure it was correct and it was. I am not sure what's going on. I am not sure if I have to make it a button but I did the same thing before and it worked.
urls.py
from django.urls import path
from .views import pplCreate, pplCreate, pplList, pplDetail,pplUpdate,pplDelete,authView
urlpatterns = [
path('login/', authView.as_view(),name='login'),
path('', pplList.as_view(), name='pplLst'),
path('people/<int:pk>', pplDetail.as_view(), name='pplDet'),
path('people-update/<int:pk>', pplUpdate.as_view(), name='pplUpd'),
path('people-create/', pplCreate.as_view(), name='pplCre'),
path('people-delete/<int:pk>', pplDelete.as_view(), name='pplDel'),
]
views.py
from distutils.log import Log
import imp
from .models import People
from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django.contrib.auth.views import LoginView
# Create your views here.
class authView(LoginView):
template_name = 'base/login.html'
fields = '__all__'
redirect_authenticated_user = True
def get_success_url(self):
return reverse_lazy('pplLst')
class pplList(ListView):
model = People
context_object_name = 'people'
class pplDetail(DetailView):
model = People
context_object_name ='cnd'
template_name = 'base/people.html'
class pplCreate(CreateView):
model = People
fields = '__all__'
success_url = reverse_lazy('pplLst')
class pplUpdate(UpdateView):
model = People
fields = '__all__'
success_url = reverse_lazy('pplLst')
class pplDelete(DeleteView):
model = People
context_object_name = 'cnd'
success_url = reverse_lazy('pplLst')
login.html
<h1>Login</h1>
<from method="POST">
{%csrf_token %}
{{form.as_p}}
<input type="submit" value="Login">
</from>
In settings.py file, simply you can add this.
LOGIN_REDIRECT_URL = 'pplLst' #This is path name from urls
Add this in settings.py file, then you will get redirected to home page
Just remove auth view from views and do following way:
In urls.py:
from django.contrib.auth import views as auth_views
path('login/',auth_views.LoginView.as_view(template_name='base/login.html'),name='login'),

AttributeError: 'function' object has no attribute 'as_view',in urls.py

I written this logic in my views.py, and I used class based views, Detail view:
#login_required
class profileView(DetailView):
model = profile
template_name = "users/profile.html"
and in urls.py file I've written this:
from django.urls import path,include
from . import views
from .views import profileView
urlpatterns = [
path('register/',views.register,name="register"),
path('login/',views.login_user,name="login_user"),
path('profile/',profileView.as_view(),name="profile_view"),
]
the django version that I'm using is 3.1 and python version is 3.8.
I hope that someone has an answer to my question.
You can not make use of #login_required for a class-based view, since that returns a function. You use the LoginRequiredMixin [Django-doc]:
from django.contrib.auth.mixins import LoginRequiredMixin
class profileView(LoginRequiredMixin, DetailView):
model = profile
template_name = 'users/profile.html'

Django custom LoginView not logging user in

I'm fairly new to Django, but I'm trying to build a customized authentication system by subclassing the generic Django authentication components. The main issue is that my custom LoginView does not seem to do anything besides refresh the page.
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, ReadOnlyPasswordHashField, AuthenticationForm, UsernameField
from django.utils.translation import gettext, gettext_lazy as _
from .models import CustomUser
BUREAU_CHOICES = [ ('HR', 'Human Resources'),
('CRT', 'Creative'),
('ACC', 'Accounting'),]
class CustomAuthForm(AuthenticationForm):
bureau = forms.ChoiceField(widget=forms.Select, choices=BUREAU_CHOICES)
email = forms.CharField(widget=forms.TextInput(attrs={'autofocus': True, 'placeholder': 'Email'}))
password = forms.CharField(
label=_("Password"),
strip=False,
widget=forms.PasswordInput(attrs={'autocomplete': 'current-password', 'placeholder': 'Password'}),
)
class Meta:
model = CustomUser
fields = ('email', 'password',)
views.py
from django.shortcuts import render
from django.urls import reverse_lazy
from django.contrib.auth.views import LoginView
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import AuthenticationForm
from .forms import CustomAuthForm
class CustomLoginView(LoginView):
form_class = CustomAuthForm
authentication_form = CustomAuthForm
template_name = 'users/login.html'
urls.py
from django.urls import path
from . import views
app_name='users'
urlpatterns = [
path('login/', views.CustomLoginView.as_view(), name='login'),
]
So I've read answers here, here and here which all seem to involve overriding methods from the superclass LoginView. When I rewrite my CustomLoginView to override a method, they are not being called. For example:
views.py
class CustomLoginView(LoginView):
form_class = CustomAuthForm
authentication_form = CustomAuthForm
template_name = 'users/login.html'
def form_valid(self, request):
print(self.request)
return super().form_valid(form)
This does nothing. I can't seem to find any reference to which methods I need to override and within which to place login logic.

'function' object has no attribute 'as_view'

I am trying to use class based views, and get a strange error. The way I'm using the view seems to be the normal way:
ingredients/models.py:
from django.db import models
from django.utils import timezone
class Ingredient(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
def get_prices():
purchases = self.purchase_set.all()
prices = [purchase.price for purchase in purchases]
ingredients/views.py:
from django.shortcuts import render, render_to_response, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic.edit import CreateView
from .models import Ingredient, Purchase
def IngredientCreateView(CreateView):
model = Ingredient
fields = ['all']
ingredients/urls.py:
from django.conf.urls import patterns, include, url
from ingredients.views import IngredientCreateView
urlpatterns = patterns('',
url(r'^new_ingredient$', IngredientCreateView.as_view(), name='new-ingredient'),
)
I get
AttributeError at /ingredients/new_ingredient
'function' object has no attribute 'as_view'
I am on django 1.8.5. Why won't this view work? Thank you
IngredientCreateView should be a class.
So your views.py replace:
def IngredientCreateView(CreateView):
with:
class IngredientCreateView(CreateView):
In my case, the problem was that I tried to use a #decorator on the class-based view as if it was a function-based view, instead of #decorating the class correctly.
EDIT: From the linked page, here is a way to apply #login_required to a class-based view:
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
#method_decorator(login_required, name='dispatch')
class ProtectedView(TemplateView):
IngredientCreateView is a function, not a class.
The following line
def IngredientCreateView(CreateView):
should be replace with
class IngredientCreateView(CreateView):
def Some_def_View(CreateView):
#should be replaced with
class SomeClassView(CreateView)
In addition to what is already said here, Check the file name and class name if it is same then you might have to import the class properly.
File name /api/A.py
class A:
//some methods
In your main class
//App main class
from api.A import A
I faced the same problem but this solution worked for me..
in views.py file in viewclass you can use viewsets instead of CreateView
from rest_framework import viewsets
class YourClassView(viewsets.ModelViewSet):
in urls.py file you can use this routing pattern
from django.conf.urls import url
from rest_framework import routers
router = routers.DefaultRouter()
router.register('books',YourClassView)
urlpatterns = [
path('', include(router.urls)),
path('admin/', admin.site.urls)
]

Django get_absolute_url NoReverseMatch zero patterns tried

I've been trying for days now to use get_absolute_url and whenever I click on the view on site button in the admin page or click submit on my add form page, I get this error:
NoReverseMatch at /admin/r/14/3/ (or NoReverseMatch at /blogs/add/)
Reverse for 'blog_detail' with arguments '()' and keyword arguments '{'pk': 3}' not found. 0 pattern(s) tried: []
If I go to mysite/blog/3 I do get the blog details page just fine as I have it set up. So I know the page works, but it seems like its not trying to find it since it says zero patterns tried.
Docs I'm looking at are:
https://docs.djangoproject.com/en/1.7/topics/class-based-views/generic-editing/
https://docs.djangoproject.com/en/1.7/ref/models/instances/#get-absolute-url
My code (what I think is relevant at least. If more info is needed let me know please)
blogs.models.py
from django.contrib.auth.models import User
from django.conf import settings
from django.db import models
from django.core.urlresolvers import reverse
from audit_log.models.fields import CreatingUserField, CreatingSessionKeyField
class Blog(models.Model):
created_by = CreatingUserField(related_name = "created_categories")
created_with_session_key = CreatingSessionKeyField()
created_time = models.DateTimeField(auto_now_add=True)
blog_title = models.CharField('Blog Title', max_length=200)
short_description = models.TextField('Short Description', max_length=140)
blog_image = models.CharField('Image', max_length=200)
youtube_link = models.URLField('YouTube', max_length=200)
external_site_link = models.URLField('Website', max_length=200)
full_blog = models.TextField(max_length=10000)
def get_absolute_url(self):
return reverse('blog_detail', kwargs={'pk': self.pk})
def __unicode__(self):
return self.blog_name
urls.py
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^blogs/', include('blogs.urls', namespace='blogs')),
)
blogs.urls.py
from django.conf.urls import patterns, url
from blogs import views
urlpatterns = patterns('',
url(
regex=r'^$',
view=views.BlogListView.as_view(),
name='blog_list'
),
url(
regex=r'^(?P<pk>\d+)/$',
view=views.BlogDetailView.as_view(),
name='blog_detail'
),
url(
regex=r'^add/$',
view=views.BlogCreate.as_view(),
name='blog_add'
),
url(
regex=r'^(?P<pk>\d+)/$',
view=views.BlogUpdate.as_view(),
name='blog_update'
),
url(
regex=r'^(?P<pk>\d+)/delete/$',
view=views.BlogDelete.as_view(),
name='blog_delete'
),
)
blogs.views.py
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.views.generic import DetailView
from django.views.generic import RedirectView
from django.views.generic import UpdateView
from django.views.generic import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
# Only authenticated users can access views using this.
from braces.views import LoginRequiredMixin
from .models import Blog
class BlogDetailView(DetailView):
model = Blog
class BlogListView(ListView):
model = Blog
class BlogCreate(LoginRequiredMixin, CreateView):
model = Blog
fields = ['blog title', 'short_description', 'blog_image',
'youtube_link', 'external_site_link', 'full_blog']
class BlogUpdate(LoginRequiredMixin, UpdateView):
model = Blog
fields = ['blog title', 'short_description', 'blog_image',
'youtube_link', 'external_site_link', 'full_blog']
class BlogDelete(LoginRequiredMixin, DeleteView):
model = Blog
success_url = reverse_lazy('blog_list')
you need to address url with namespace blogs like this:
return reverse('blogs:blog_detail', kwargs={'pk': self.pk})

Categories