from urllib import parse
from django.urls import resolve
uri = '/api/v1/myapp?my_filter=my_value'
data = parse.urlsplit(uri)
path = data.path
params = dict(parse.parse_qsl(data.query))
viewset = resolve(data.path).func.cls
queryset = viewset.filter_class(data=params).qs
class DocumentOrderView(CsrfExemptMixin, JsonRequestResponseMixin, FormView):
def post(self, request, *args, **kwargs):
self.tree_update(None, self.request_json)
return self.render_json_response({'saved': 'ok'})
@staticmethod
def tree_update(parent_id, children):
for child in children:
Tree.objects.filter(pk=child['id']).update(parent_id=parent_id)
tree_update(child['id'], child.get('children', []))
@reversion.register(fields=['head', 'head_en', 'head_kz',])
class Slide(models.Model):
head = models.CharField(verbose_name='Title', max_length=200, blank=False,)
from django.shortcuts import redirect
class RedirectPermissionRequiredMixin(PermissionRequiredMixin,):
login_url = reverse_lazy('dashboard')
def handle_no_permission(self):
return redirect(self.get_login_url())
# и примешать вместо PermissionRequiredMixin
class UserEditView(RedirectPermissionRequiredMixin, UpdateView):
template_name = 'users/edit_user.html'
form_class = UserEditForm
model = User
permission_required = ('auth.change_user')
class ModelBSerializater(serializers.ModelSerializer):
name_a = serializers.ReadOnlyField(source='modela.name')
class Meta:
model = ModelB
fields = (..., name_a)
...
user.is_active = False
user.save()
context = {'user': user}
current_site = get_current_site(request)
site_name = current_site.name
domain = current_site.domain
use_https = request.is_secure()
token_generator = user_is_active_token_generator
extra_context = {
'domain': domain,
'site_name': site_name,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'user': user,
'token': token_generator.make_token(user),
'protocol': 'https' if use_https else 'http',
}
context.update(extra_context)
mail_message_template = 'путь до registration_email_user_not_is_active.html'
mail_message = render_to_string(mail_message_template, context)
send_mail('activation JustSolve.kz', mail_message, settings.EMAIL_HOST_USER, ['knursultana@gmail.com'])
from django.conf import settings
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six
from django.utils.crypto import constant_time_compare, salted_hmac
from django.utils.http import base36_to_int, int_to_base36
class UserIsActiveTokenGenerator(PasswordResetTokenGenerator):
def check_token(self, user, token):
"""
Check that a password reset token is correct for a given user.
"""
# Parse the token
try:
ts_b36, hash = token.split("-")
except ValueError:
return False
try:
ts = base36_to_int(ts_b36)
except ValueError:
return False
# Check that the timestamp/uid has not been tampered with
if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
return False
return True
def _make_token_with_timestamp(self, user, timestamp):
# timestamp is number of days since 2001-1-1. Converted to
# base 36, this gives us a 3 digit string until about 2121
ts_b36 = int_to_base36(timestamp)
# By hashing on the internal state of the user and using state
# that is sure to change (the password salt will change as soon as
# the password is set, at least for current Django auth, and
# last_login will also change), we produce a hash that will be
# invalid as soon as it is used.
# We limit the hash to 20 chars to keep URL short
key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator"
# Ensure results are consistent across DB backends
joined_timestamp = '' if user.date_joined is None else user.date_joined.replace(microsecond=0, tzinfo=None)
value = (six.text_type(user.pk) +
six.text_type(joined_timestamp) + six.text_type(timestamp))
hash = salted_hmac(key_salt, value).hexdigest()[::2]
return "%s-%s" % (ts_b36, hash)
user_is_active_token_generator = UserIsActiveTokenGenerator()
Dear, {{ user.username }}!<br>
You join to {{ domain }}!<br>
url to activate <a href="{{ protocol }}://{{ domain }}/activate/{{ uid }}/{{ token }}/">{{ protocol }}://{{ domain }}/activate/{{ uid }}/{{ token }}/</a>
welcome!
...
url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
views.activate, name='activate')
...
def activate(request, uidb64=None, token=None,
token_generator=user_is_active_token_generator,
template_name='common/activate.html'):
UserModel = get_user_model()
assert uidb64 is not None and token is not None # checked by URLconf
try:
# urlsafe_base64_decode() decodes to bytestring on Python 3
uid = force_text(urlsafe_base64_decode(uidb64))
user = UserModel._default_manager.get(pk=uid)
except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist):
user = None
if user is not None and user.is_active:
validlink = True
title = _('Link no longer relevant')
elif user is not None and token_generator.check_token(user, token):
user.is_active = True
user.save()
validlink = True
title = _('Account activated')
else:
validlink = False
title = _('Link not correct')
context = {
'title': title,
'validlink': validlink,
}
return TemplateResponse(request, template_name, context)
# Проверки должны находиться в django forms, а не во вьюхе.
validate_email(email)
len(password) >= 5
password != password2
User.objects.filter(username=email, is_active=True).exists()
<div class="comment">
<p id="inf"> {{ comment.name }} {{ comment.created }}</p>
{{ comment.body|linebreaks }}
</div>
$('.comment').remove();
$('#codeajax').append(data);
{% url 'phylosophy' as url %}
<a href='{{ url }}' {% if request.path == url %}class="active"{%endif %}>philosophy</a>
{% block breadcrumbs %}
<div class="breadcrumb"><a href="/">Главная</a></div>
{% endblock %}
{% extends 'base.html' %}
{% block breadcrumbs %}
{{ block.super }}
<div class="breadcrumb"><a href="{% url 'articles:articles' %}">Каталог статей</a></div>
{% endblock %}
{% extends 'articles.html' %}
{% block breadcrumbs %}
{{ block.super }}
<div class="breadcrumb"><a href="{% url 'articles:article_view' article_id=article.id %}">{{ article.title }}</a></div>
{% endblock %}
Class names should normally use the CapWords convention.
from django.contrib.auth.forms import UserCreationForm
import os
from django.contrib.auth.models import User
from django.db import models
def avatar_upload_to(instance, filename):
return os.path.join('uploads', instance.user.username + os.path.splitext(filename)[1])
class UserProfile(models.Model):
user = models.OneToOneField(User, unique=True)
avatar = models.ImageField(upload_to=avatar_upload_to)
info = models.TextField()
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from accounts.models import UserProfile
class SignupForm(UserCreationForm):
username = forms.CharField(
widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'login', }),
max_length=30, label=u'Логин'
)
email = forms.EmailField(
widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Ваша почта', }),
required=True, max_length=254, label=u'E-mail',
)
password1 = forms.CharField(
widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '*****'}),
min_length=6, label=u'Пароль'
)
password2 = forms.CharField(
widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '*****'}),
min_length=6, label=u'Повторите пароль'
)
class Meta:
model = User
fields = ('username', 'email')
class UserProfileSignupForm(forms.ModelForm):
info = forms.CharField(
widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': u'Молод и горяч',}),
required=False, label=u'Пара слов о себе'
)
avatar = forms.FileField(
widget=forms.ClearableFileInput(attrs={'class': 'ask-signup-avatar-input',}),
required=False, label=u'Аватар'
)
def clean_avatar(self):
avatar = self.cleaned_data.get('avatar')
if avatar is None:
raise forms.ValidationError(u'Добавьте картинку')
if 'image' not in avatar.content_type:
raise forms.ValidationError(u'Неверный формат картинки')
return avatar
class Meta:
model = UserProfile
fields = ('info', 'avatar')
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
MEDIA_URL = '/media/'
class Advert(models.Model):
category = models.TextField()
title = models.CharField(max_length=64)
description = models.CharField(max_length=900)
date = models.DateTimeField(auto_now_add=True, null=True)
class AdvertImage(models.Model):
advert = models.ForeignKey(Advert)
photo = models.ImageField(upload_to='uploads/')
class AddAdvertForm(ModelForm):
class Meta:
model = Advert
fields = '__all__'
class AdvertImagesForm(forms.Form):
photos = forms.FileField(widget=widgets.FileInput(attrs={'multiple': True}))
def __init__(self, *args, **kwargs):
if 'request' in kwargs:
self.request = kwargs.pop('request')
super(AdvertImagesForm, self).__init__(*args, **kwargs)
def clean_photos(self):
# Остаются только картинки
photos = [photo for photo in self.request.FILES.getlist('photos') if 'image' in photo.content_type]
# Если среди загруженных файлов картинок нет, то исключение
if len(photos) == 0:
raise forms.ValidationError(u'Not found uploaded photos.')
return photos
def save_for(self, advert):
for photo in self.cleaned_data['photos']:
AdvertImage(photo=photo, advert=advert).save()
class CreateAdvertView(View):
template_name = 'bulletinboard/add_advert.html'
form_class = AddAdvertForm
form_images_class = AdvertImagesForm
model = Advert
def get(self, request):
form = self.form_class()
form_images = self.form_images_class()
return render(request, self.template_name, {'form': form, 'form_images': form_images})
def post(self, request):
form = self.form_class(request.POST)
form_images = self.form_images_class(request.POST, request.FILES, request=request)
if form.is_valid() and form_images.is_valid():
advert = form.save()
form_images.save_for(advert)
return HttpResponseRedirect('/')
return render(request, self.template_name, {'form': form, 'form_images': form_images})
FILE_UPLOAD_HANDLERS = (
'название_аппликейшена.uploadhandler.MemoryFileUploadHandler',
'название_аппликейшена.uploadhandler.TemporaryFileUploadHandler',
)
from io import BytesIO
import os
from django.core.files.uploadedfile import TemporaryUploadedFile, InMemoryUploadedFile
from django.core.files.uploadhandler import FileUploadHandler, StopFutureHandlers
from django.conf import settings
import pytils
import re
def translify(value):
value = pytils.translit.translify(u"%s" % value)
value = re.sub("[\W]", "_", value.strip())
return value
def transliteration_file_name(file_name):
name, ext = os.path.splitext(file_name)
return '{0}{1}'.format(translify(name), ext)
class TemporaryFileUploadHandler(FileUploadHandler):
"""
Upload handler that streams data into a temporary file.
"""
def __init__(self, *args, **kwargs):
super(TemporaryFileUploadHandler, self).__init__(*args, **kwargs)
def new_file(self, field_name, file_name, content_type, content_length, charset=None, content_type_extra=None):
file_name = transliteration_file_name(file_name)
super(TemporaryFileUploadHandler, self).new_file(field_name, file_name, content_type,
content_length, charset, content_type_extra)
self.file = TemporaryUploadedFile(self.file_name, self.content_type, 0, self.charset, self.content_type_extra)
def receive_data_chunk(self, raw_data, start):
self.file.write(raw_data)
def file_complete(self, file_size):
self.file.seek(0)
self.file.size = file_size
return self.file
class MemoryFileUploadHandler(FileUploadHandler):
"""
File upload handler to stream uploads into memory (used for small files).
"""
def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
"""
Use the content_length to signal whether or not this handler should be in use.
"""
# Check the content-length header to see if we should
# If the post is too large, we cannot use the Memory handler.
if content_length > settings.FILE_UPLOAD_MAX_MEMORY_SIZE:
self.activated = False
else:
self.activated = True
def new_file(self, field_name, file_name, content_type, content_length, charset=None, content_type_extra=None):
file_name = transliteration_file_name(file_name)
super(MemoryFileUploadHandler, self).new_file(field_name, file_name, content_type,
content_length, charset, content_type_extra)
if self.activated:
self.file = BytesIO()
raise StopFutureHandlers()
def receive_data_chunk(self, raw_data, start):
"""
Add the data to the BytesIO file.
"""
if self.activated:
self.file.write(raw_data)
else:
return raw_data
def file_complete(self, file_size):
"""
Return a file object if we're activated.
"""
if not self.activated:
return
self.file.seek(0)
return InMemoryUploadedFile(
file=self.file,
field_name=self.field_name,
name=self.file_name,
content_type=self.content_type,
size=file_size,
charset=self.charset,
content_type_extra=self.content_type_extra
)