0% found this document useful (0 votes)
1 views

Django Advanced

The document outlines the implementation of various Django class-based views, including TemplateView, ListView, DetailView, CreateView, UpdateView, and DeleteView, along with custom user authentication and registration forms. It provides code snippets for creating and managing models, views, and templates, as well as handling user authentication and permissions. Additionally, it discusses extending the user model and URL configuration for authentication-related views.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Django Advanced

The document outlines the implementation of various Django class-based views, including TemplateView, ListView, DetailView, CreateView, UpdateView, and DeleteView, along with custom user authentication and registration forms. It provides code snippets for creating and managing models, views, and templates, as well as handling user authentication and permissions. Additionally, it discusses extending the user model and URL configuration for authentication-related views.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Preparation

CustomTags

from django import template


from petstragram.main_app.models import Profile

register = template.Library()

@register.simple_tag()
def has_profile():
return Profile.objects.count() > 0

Dates

Class Based Views

TemplateView

class LandingPageView(TemplateView):
# required:
template_name = 'landing_page.html'

# optional:
def get_context_data(self):
context = super(LandingPageView, self).get_context_data()
context.update({
'title': 'Django landing page',
'data': 'Django context data',
})
return context
Generic Views

from django.views.generic

ListView
class TodoslistView(ListView):
# required:
model = Todo
template_name = 'todos/todos_list.html'

# Optional
# context_object_name = "posts" (default: post_list)
# queryset = Todo.objects.all()

DetailView
class TodoDetailsView(DetailView):
# required:
model = Todo
template_name = 'todos/todos_detail.html'

# optional:
# context_object_name = "todo_task" (default: todo / object)

CRUD Views

from django.views.generic

/ basic /
CreateView (вкл. за Регистрация на потребител)
class TodoCreateView(CreateView):
# required:
model = Todo
success_url = reverse_lazy(‘todos list’)
form_class = UserCreateForm # за Регистрация на потр.

# one of these:
template_name = ‘todos/create_view.html’
fields = ‘__all__’

* В модела трябва да се добави метод get_absolute_url()

/ relation /
class CreatePetView(views.CreateView):
form_class = PetCreateForm
template_name = 'pets/pet-add-page.html'

def get_success_url(self):
return reverse_lazy("details user", {
'pk': self.request.user.id,
})

def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs

* get_form_kwargs използваме, за да подадем допълнителни


стойности при създаването на формата (__init__).
Това е необходимо за създаване на релация в самата форма.

● Когато имаме форма за създаване

При създаване на Pet към формата за създаване добавяме и


релация към потребителя (user)

class PetBaseForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
self.user = user

def save(self, commit=True):


pet = super().save(commit=False)
pet.user = self.user
if commit:
pet.save()
return pet

● Когато нямаме форма за създаване, която да ползваме в


CreateView-то:
- подаваме само fields = ()
- подават се допълнителните полета към инстанцията чрез
метода form_valid()

class CreatePhotoView(auth_mixins.LoginRequiredMixin,
views.CreateView):
model = Photo
template_name = 'photos/photo-add-page.html'
fields = ('photo', 'description', 'location', )

def get_success_url(self):
return reverse_lazy('details photo', kwargs={
'pk': self.object.id
})

def form_valid(self, form):


form.instance.user = self.request.user
return super().form_valid(form)

- - - -
UpdateView
class TodoUpdateView(UpdateView):
# required:
model = Todo
success_url = reverse_lazy(‘todos list’)

# one of these:
template_name = ‘todos/update_view.html’
fields = ‘__all__’

DeleteView
class TodoDeleteView(DeleteView):
# required:
model = Todo
success_url = reverse_lazy(‘todos list’)

# one of these:
template_name = ‘todos/delete_view.html’
fields = ‘__all__’

Authorization - Кои сме ние


Authentication - Какво можем да правим
Registration

Extending User Model

Предпочитан метод - Extending AbstractBaseUser /


PermissionsMixin

from django.contrib.auth.base_user import AbstractBaseUser


from django.contrib.auth.models import PermissionsMixin

class CustomUser(AbstractBaseUser, PermissionsMixin):


pass

URL Configuration

● Включваме вградената конфигурация:

path('accounts/', include('django.contrib.auth.urls')),

● или къстъм URLConf:


path('accounts/', include([
path('login/', CustomLoginView.as_view(), name='login'),
path('logout/', logout_then_login, name='logout'),
])),
Ако искаме потребителя да се пренасочи към Login веднага след
Logout:
from django.contrib.auth.views import logout_then_login

path('logout/', logout_then_login, name='logout'),

Authentication Forms
Импортират се от
from django.contrib.auth import forms as auth_forms

Видове:

● за Регистрация
● за Вход

UserCreationForm - за регистрация

class PetstagramUserCreateForm(auth_forms.UserCreationForm):

password1 = forms.CharField(
widget=forms.PasswordInput(
attrs={
"autocomplete": "new-password",
"placeholder": "Password1"
}),
)

password2 = forms.CharField(
widget=forms.PasswordInput(
attrs={
"autocomplete": "new-password",
"placeholder": "Password2"
}),
)

class Meta(auth_forms.UserCreationForm.Meta):
model = PetstagramUser
fields = ('username', 'email')
widgets = {
'username': forms.TextInput(
attrs={
'placeholder': 'Username',
}
),
'email': forms.EmailInput(
attrs={
'placeholder': 'Email'
}
),
}

AuthenticationForm - за вход
class UserLoginForm(auth_forms.AuthenticationForm):
username = auth_forms.UsernameField(
widget=forms.TextInput(
attrs={
"autofocus": True,
"placeholder": "Username",
})
)

password = forms.CharField(
strip=False,
widget=forms.PasswordInput(
attrs={
"autocomplete": "current-password",
"placeholder": "Password"
}
),
)

Authentication Views
ID на текущия потребител (във View): self.request.user.id
ID на текущия потребител (в Template): user.id

!!!
За да достъпи даденото View, потребителят трябва да е логнат
!!!

from django.contrib.auth import mixins as auth_mixins

class CreatePetView(auth_mixins.LoginRequiredMixin,
views.CreateView):
pass

from django.contrib.auth import views as auth_views

LoginView
class CustomLoginView(auth_views.LoginView):
template_name = 'accounts/login.html'
form_class = UserLoginForm
next_page = reverse_lazy(‘index’)

LogoutView
class UserLogoutView(auth_views.LogoutView):
form_class = UserLogoutForm
next_page = reverse_lazy('login user')

PasswordChangeView
class UserLogoutView(auth_views.PasswordChangeView):
template_name = 'accounts/change-password.html'

* като се добави в urls.py задължително path


('password_change_done’)

path('password_change_done/',
RedirectView.as_view(url=reverse_lazy('index')),
name='password_change_done'),

Пренасочване във CBV според нивото на


достъп (dispatch)

★ Ако потребителя, който опитва да достъпи това view, вече е


логнат, ще бъде пренасочен към ‘index’ view- то.

def dispatch(self, request, *args, **kwargs):


if request.user.is_authenticated:
return redirect('index')

return super().dispatch(request, *args, **kwargs)

You might also like