Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a custom signal in django?
I have been searching for a guide to write my own custom signals in django. Django documentation does a good job of giving details of individual topic, but does not give a working example of the same, and I can't seem to understand how to write my own custom signals. I searched online on various sites but it still does not ring any bells :P. Can anyone give a complete working example of the same? Thanks in advance. Regards. -
Django+Django-REST+AngularJS or maybe just AngularJS?
I pretty much a beginner and I am tasked to translate an Excel tool to a web based program. So pretty soon I favored Python since I think it's easy to use and is used extensively for calculations of all sorts. So I looked into the Django. Now I also needed to show graphs. "Coding for entrepreneurs" advised to use the Django-REST framework for this, so I looked into that also. Now I made a very limited functionality REST API. I.e. still very possible to trash this and go into a different direction... My thinking here is to detach the backbone (REST API) which solely deals with the bare bone information. And next I would like to connect this to a nice user interface. So I am now starting to look into AngularJS. Now AngularJS seems to be much more than a shiney front, and again has quitte the learning curve to master it. So it has been quitte a journey, I feel like I pull a string and just get more string. I am now wondering if it's just possible to write the whole applications using just AngularJS? Or am I on a viable and doable path devising a … -
Use Pillow resize with an ImageField
I am new to python and trying to use ImageField in my model. I have some images in files separate from my Django Project that I want to upload. So I have a Django model class Product(models.Model): img_thumbnail = models.ImageField(upload_to='products_images', blank=True, null=True) In my conversion code which uploads images, I want to generate thumbnails at a specific height so I can not use: img = Image.open(file_path) img.thumbnail() Instead, I calculate the necessary width and resize it using Pillow. img = Image.open(file_path) h_percent = (75/ float(img.size[1])) if h_percent < 1: width = int((float(img.size[0]) * float(h_percent))) img = img.resize((width, base_height), Image.ANTIALIAS) filename = os.path.basename(file_path) That works fine but when I tried to save that to an ImageField, I get an error: AttributeError: 'JpegImageFile' object has no attribute 'content' product.img_thumbnail.save(filename, img, True) Searching the web, I found reference to SimpleUploadedFile. So write the resized image with a suffix. I received another error; : 'charmap' codec can't decode byte 0x81 in position 251: character maps to file_root, file_ext = os.path.splitext(file_path) new_file_name = file_root + '_thumbnail' + file_ext img.save(new_file_name) filename = os.path.basename(file_path) with open(new_file_name) as infile: _file = SimpleUploadedFile(filename, infile.read()) So what should I do here? I am using Python 3.6 with Django 2.0 Thanks … -
How to serialize in Django Rest Framework with custom fields?
Let's say my model is: class Contact(models.Model): email = models.CharField(max_length=50) I want to have a serializer that receives multiple fields and then combine them to create an email. For example: class ContactSerializer(serializers.Serializer): first = serializers.CharField() second = serializers.CharField() third = serializers.CharField() It would convert {"first": "user", "second": "example", "third": "org"} to a new Contact object with the email 'user@example.org'. What should I do? -
Django: Rendering a table with 2 objects of variable size in HTML template
I've a bit of a dilemma here, and I'm not sure how best to approach it. I need to create a table of all objects in model "Chamber" and all objects in (ForeignKey related) model "ChamberProperties", except that the items in model "ChamberProperties" are user defined and not limited. Say model "Chamber" has 2 objects in it: class Chamber(models.Model): chamber_name = models.CharField(max_length=100) With: Object 1: chamber_name: Lab Object 2: chamber_name: Production And the properties of the chambers are set up by the managers on site, so we don't know what they'll end up putting there. And the model "ChamberProperties" can have many related objects in it: class ChamberProperty(models.Model): chamber = models.ForeignKey(Chamber, on_delete=models.CASCADE) property_name = models.CharField(max_length=50) property_value = models.CharField(max_length=100) And for ChamberProperties: For example Chamber "Lab" may have: **ChamberProperties**: 1. Charge: 100v 2. Last test: yesterday 3. Scientist: Tom But Chamber "Production" may have many more: **ChamberProperties**: 1. Charge: 100000v 2. Error: 2018-02-19 11:55 3. Site: XK-1 4. Production: Foo 5. Risk: High My problem is in creating a table that shows all properties for all chamber in a HTML table. Both in constructing the HTML table itself and with filtering in the view. The table layout I was given is … -
Django celery beat with Django as backend
I'm trying to set up Django-celery-beat in order to create periodic tasks. My configuration is as follows: from celery import Celery import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') celery = Celery(broker="django-db") celery.autodiscover_tasks() CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' CELERY_ENABLE_UTC = True CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers.DatabaseScheduler' I'm trying to use Django as database and run both the beat service and the workers. When I launch the workers like this: celery -A monitoring worker --loglevel=DEBUG --app=config.settings.local ... I get: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@django-db:5672//: [Errno 8] nodename nor servname provided, or not known. And when I try it when beat: celery -A monitoring beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler --app=config.settings.local I get this error: ERROR/MainProcess] beat: Connection error: [Errno 8] nodename nor servname provided, or not known. Trying again in 4.0 seconds... I'd like to be able to create periodic tasks through the Django admin but I'm stuck at this point so any help is welcome. -
Type Error with Django POST-Method
I'm pretty new to Django. I know that we had this topic before, but I couldn't find a solution in my research. I just want to POST a simple todo with a form but for some reason I get this Type Error: "TypeError at /todo/add/ expected string or bytes-like object" Hope you guys can spot my mistake. The Model: from django.db import models from datetime import* import time from django.utils.timesince import timesince from django.urls import* class Task(models.Model): task_title = models.CharField(max_length=50) complete = models.BooleanField(default=False) def get_absolute_url(self): return reverse('todo:detail', kwargs={'pk':self.pk}) def __str__(self): return self.task_title The Form: from django import forms class TodoForm(forms.Form): task_title = forms.CharField(max_length=50, widget=forms.TextInput(attrs{'class':'formcontrol','placeholder': 'Enter todo e.g. Delete junk files', 'aria-label' : 'Todo', 'aria-describedby' : 'add-btn'})) The View: @require_POST def addTodo(request): form = TodoForm(request.POST) print(form.errors) print(request.POST['task_title']) if request.method == 'POST': if form.is_valid(): new_todo = Task(task_title=request.POST['task_title']) new_todo.save() print('DONE') return redirect('index') The urls: from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ # match list, url(r'^$', views.index, name='index'), url(r'^add/$', views.addTodo, name='add'), # match id goes to detail view url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), ] The template: <div class="sidebar"> <form action="{% url 'add' %}" method="POST" role="form"> {% csrf_token %} <div class="form-group"> <div class="input-group"> {{ form.errors }} {{ form.task_title }} … -
Django 2 url path matching negative value
In Django <2 the normal way of doing this is to use regex expression. But it is now recommended in Django => 2 to use path() instead of url() path('account/<int:code>/', views.account_code, name='account-code') This looks okay and works well matching url pattern /account/23/ /account/3000/ However, this issue is that I also want this to match negative integer like /account/-23/ Please how do I do this using path()? -
Rendering in Django 2.0.2
Could anybody help me, please? Django documantation says that 'render_to_response' is not used starting from the 2nd version. I can't display list on my template. For the model: class Partners(models.Model): title = models.CharField(max_length=256) description = models.TextField(blank=True) image = models.ImageField(upload_to="pictures", blank=True) link = models.URLField(max_length=128, blank=True) def __str__(self): return self.title i tried both of 2 methods: def partners(request): partners_list = Partners.objects.all() return render(request, 'partners.html', {'partners_list': partners_list}) and def partners(request): partners_list = Partners.objects.all() return TemplateResponse(request, 'partners.html', {'partners_list': partners_list}) Template is: {% for partners in partners_list %} <div class="col-sm-2" id="partners"> <div class="card"> <img class="card-img-top" src="{{partners.image.url}}" alt="Card image cap"> <div class="card-block"> <h4 class="card-title">{{partners.title}}</h4> <p class="card-text">{{partners.description}}</p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">Cras justo odio</li> </ul> <div class="card-block"> <a href="{{partners.link}}" class="card-link">Card link</a> </div> </div> </div>{% endfor %} Urls are: urlpatterns = [ path('admin/', admin.site.urls), path(r'', headpage, name='headpage'), path(r'about/', about, name='about'), path(r'partners/$', partners, name='partners'), ] What i do wrong? List of partners isn't displayed..Thank's a lot for your help! -
Ensure that a path to a dir is a Django project
For the last two days I am struggling with the following question: Given an absolute path (string) to a directory (inside my file system or the server, it doesn't matter), determine if this dir contains a valid Django project. First, I thought of looking for the manage.py underneath, but what if some user omit or rename this file? Secondly, I thought of locating the settings module but I want the project root, what if the settings is 2 or more levels deep? Third, I thought of locating the (standard) BASE_DIR name inside settings, but what if the user has not defined it or renamed it? Is there a way to properly identify a directory as a valid Django project? Am I missing something? -
Django admin: TypeError on any post request
I created a new Django (v. 1.11) project and using python manage.py createsuperuser I created a user. I can log in to the admin section on localhost:8888/admin with this user account. However, I cannot do anything else: whenever I trigger a POST request other than the login page, I get the following error: TypeError at /admin/... slice indices must be integers or None or have an __index__ method ("..." can be replaced for example by auth/group/add/), but this behavior is general, not specific to this request The following traceback suggests problem with parsing the CSRF token from the page, but I didn't have such issues on other pages within my application apart from admin. Traceback: File "/usr/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 178. response = middleware_method(request, callback, callback_args, callback_kwargs) File "/usr/local/lib/python2.7/site-packages/django/middleware/csrf.py" in process_view 298. request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') File "/usr/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py" in _get_post 126. self._load_post_and_files() File "/usr/local/lib/python2.7/site-packages/django/http/request.py" in _load_post_and_files 299. self._post, self._files = self.parse_file_upload(self.META, data) File "/usr/local/lib/python2.7/site-packages/django/http/request.py" in parse_file_upload 258. return parser.parse() File "/usr/local/lib/python2.7/site-packages/django/http/multipartparser.py" in parse 198. data = field_stream.read(size=read_size) File "/usr/local/lib/python2.7/site-packages/django/http/multipartparser.py" in read 369. out = b''.join(parts()) File "/usr/local/lib/python2.7/site-packages/django/http/multipartparser.py" in parts 364. emitting = chunk[:remaining] Exception Type: TypeError at /admin/auth/group/add/ Exception Value: slice indices must … -
I am trying to transfer data from one table to another in django. How can I do that?
class Project(models.Model): extra_1_label = models.TextField(blank=True, null=True) extra_2_label = models.TextField(blank=True, null=True) extra_3_label = models.TextField(blank=True, null=True) extra_1 = models.TextField(blank=True, null=True) extra_2 = models.TextField(blank=True, null=True) extra_3 = models.TextField(blank=True, null=True) class project2(models.Model): name = models.TextField(blank=True, null=True) value = models.TextField(blank=True, null=True) trying to move data from table project to project2, label should be in name column and extra_1,2,3 should in value column. -
django rest framework an always sorting field
I want to have a fixed sorting field applied to all custom sortings. To be more specific imagine we have a list of employees, if user choose this form be sorted by hire_date, I want the result be sorted by hire_date and employee_id together. I mean each ordering should be ordered by employee_id inside! For example if we have 5 employees hired today, if hire_date is the sorting field, these 5 be sorted by employee_id and for the other days the same story. using the following is not the cure. It only sorts them on employee_id when no ordering is set: queryset = models.Employee.objects.order_by('id') And this one's result is same as previous: filter_backends = (CustomFilterSetBackend, filters.OrderingFilter) custom_filters = ( ........ ) ordering_fields = (............) ordering = ('id',) tnx a million -
Django 2: TemplateDoesNotExist even if files placed properly
I have encountered interesting problem on Django 2. In my settings.py I have written this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] After that I have created folder templates in my projects root folder. Then I have created app with name front and added it into my settings.py INSTALLED_APPS: Inside my views.py I have added this view: def index(request): return render(request, 'front/index') I have assigned its url like this: url(r'^$', views.index, name='index'), When I'm trying to access to this view I get this error: TemplateDoesNotExist at / front/index Why this happening? Did I miss something? -
Django request URL gets appended
i visit admin interface and try to add support user in django.its a form with user name and email. the form data is posted successfully. after successful post request i have to redirect to 127.0.0.1:8000/admin/auth/user/. however at 127.0.0.1:8000/add_support_user if user exists already,url is changed like this 127.0.0.1:8000/add_support_user/add_support_user and again i make request if user already exists its like this 127.0.0.1:8000/add_support_user/add_support_user/add_support_user(gets appended every time) support_User_form and when new user is created url is changed like this 127.0.0.1:8000/add_support_user/add_support_user so it shows 500 error page that '127.0.0.1:8000/add_support_user/add_support_user' doesnt exists error_page. what mistake am i making here? URLS.PY url(r"^add_support_user/", AddSupportUserView.as_view(), name = 'support_user'), VIEWS.PY class AddSupportUserView(CsrfExemptMixin, View): def get(self, request): form_class = AddSupportUserForm return render(request, 'add_support_user.html', { 'form': form_class, }) def post(self, request): form_class = AddSupportUserForm username = request.POST.get('username') email = request.POST.get('email') try: user_obj = User.objects.get(username=username) return render(request, 'add_support_user.html', {'errors': 'User already exits', 'form': form_class}) except User.DoesNotExist: user_obj = User.objects.create_user(username=username, email=email, is_staff=True, is_superuser=False) user_obj.set_password(email) user_obj.save() group_obj = Group.objects.get(name='support_group') user_obj.groups.add(group_obj) return HttpResponseRedirect('/admin/auth/user/') CHANGE_LIST.HTML {% extends "admin/change_list.html" %} {% block object-tools-items %} {{ block.super }} <li> <a href="{% url 'support_user' %}" class="grp-state-focus addlink">Add Support User</a> </li> {% endblock %} ADD_SUPPORT_USER.HTML {% extends 'admin/base.html' %}{% block content %} <h1>Add Support User</h1> <form role="form" action="add_support_user/" method="post"> {% csrf_token … -
haystack search not indexing multivaluefield django
I am trying to use manytomanyfield for fetch searching but when I am trying to update index, it shows no attribute error #search_index.py class ProductCreateModelIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True,template_name='search/indexes/catalogue/product_text.txt') user = indexes.CharField(model_attr='user',faceted=True ) title = indexes.EdgeNgramField(model_attr='title') description = indexes.CharField(model_attr='description',null = True) category = indexes.CharField(model_attr='category',faceted=True ) brand = indexes.CharField(model_attr='brand_name',faceted=True ) availability_regions = indexes.MultiValueField(faceted=True ) model = indexes.EdgeNgramField(model_attr='model_name',null = True) def prepare_availability_regions(self, obj): return [ availability_regions.name for a in obj.availability_regions_set.all()] when I am trying to update it shows me this return [ availability_regions.name for a in obj.availability_regions_set.all()] AttributeError: 'ProductCreateModel' object has no attribute 'availability_regions_set' here is my product_text.txt {{object.title}} {% for a in availability_regions %} {{ a }} {% endfor %} {{object.category}} {{object.model_name}} {{object.brand_name}} {{ object.description|default:"" }} I just follow the tutoria, I don't know how to do it in right way, would you tell me the right way to do it and where can i find the documentation of this ? -
Django 1.11 - xadmin app, charts widget parameters
I'm using the xadmin app, specifically trying to work with the included charts plugin. How do I start adding data from my database / models into the chart? The official xadmin documentation is incomplete. I have looked through the Django docs regarding widgets and plugins, but they weren't useful for determining how this specific implementation works. Can someone help point me in the right direction - I want to start adding parameters, so is there an explanation somewhere covering how this might be done? These are the default parameters - so it's picking up the response model belonging to my survey app, and I'd like to start populating it with data from my model / database. Example of model fields in my Survey app: class Response(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) survey = models.ForeignKey(Survey, related_name="responses") user = models.ForeignKey(User, null=True, blank=True) interview_uuid = models.CharField(_(u"Interview unique identifier"), max_length=36) class Answer(models.Model): question = models.ForeignKey(Question, related_name="answers") response = models.ForeignKey(Response, related_name="answers") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) body = models.TextField(blank=True, null=True) @property def values(self): if len(self.body) < 3 or self.body[0:3] != "[u'": return [self.body] values = [] raw_values = self.body.split("', u'") nb_values = len(raw_values) for i, value in enumerate(raw_values): if i == 0: value … -
How to print a HttpResponse in a while loop and then append onto it for each loop?
Okay so I have this view: def fight(request): monster = Monster.objects.get(pk=request.POST['monster']) user = Profile.objects.get(pk=2) while monster.health > 0 and user.health > 0: monsterattack = random.randint(monster.minattack, monster.maxattack) userattack = random.randint(user.attack*.75, user.attack*1.5) user.health = user.health - monsterattack monster.health = monster.health - userattack HttpResponse('Player attacked for: %s\n Monster attacked for: %s\n' % (userattack, monsterattack)) return HttpResponse('You are fighting %s\n Player Health: %s \n Monsters Health: %s' % (monster.name, user.health, monster.health)) I was wondering if there was a way that i could have the first HttpResponse print to the template every time it looped and then have the second while loop print after the while loop has finished. -
Django API : Create Serializer Issue
I'm working on my Django web application and I'm beginning API part. I have a Create Serializer class like this : class IndividuCreateSerializer(serializers.ModelSerializer) : class Meta : model = Individu fields = [ 'Etat', 'Civilite', 'Nom', 'Prenom', 'Sexe', 'Statut', 'DateNaissance', 'VilleNaissance', 'PaysNaissance', 'Nationalite1', 'Nationalite2', 'Profession', 'Adresse', 'Ville', 'Zip', 'Pays', 'Mail', 'Telephone', 'Image', 'CarteIdentite', ] def create(self, validated_data): obj = Individu.objects.create(**validated_data) IdentityIndividuResumeView.get_context_data(obj.id) return obj In this class, I have my create function which should redirect to IdentityIndividuResumeView class when my person is created. class IdentityIndividuResumeView(LoginRequiredMixin, TemplateView) : template_name = 'Identity_Individu_Resume.html' model = Individu def get_context_data(self, **kwargs) : context_data = super(IdentityIndividuResumeView, self).get_context_data(**kwargs) id = self.kwargs['id'] personne = get_object_or_404(Individu, pk=id) NIU = lib.Individu_Recherche.NIUGeneratorIndividu(personne) personne.NumeroIdentification = NIU ... But I don't overcome to pass argument in my function get_context_data. I'm getting this issue : File "/Users/valentin/Desktop/Identity/api/serializers.py" in create 80. IdentityIndividuResumeView.get_context_data(obj.id) File "/Users/valentin/Desktop/Identity/views.py" in get_context_data 228. context_data = super(IdentityIndividuResumeView, self).get_context_data(**kwargs) Exception Type: TypeError at /Api/Identification/create/ Exception Value: super(type, obj): obj must be an instance or subtype of type -
Django Delete CBV with confirmation pop-up and multiple success url
In my case, an instance Model can be delete from: a ListView inherited View a DetailView inherited View By default, when a delete view is called: the get function calls 'confirm_delete' template. Instead I want a pop-up/modal to appear, and if delete is clicked in the modal will delete the object if the delete operation is on a ListView, after delete the user will remain on ListView and the ListView content will be updated if the delete operation is on a DetailView, after delete the user will be redirected to the ListView or another page(depending on other rules) -- So I want to know how to do Ajax calls on delete, how to have conditional success urls in delete, based of where I am before the action. -
How to integrate django apps with trac and vice versa? Is there any possibilities for that..?
Integration of trac and Django frameworls. To use the auth used in trac in django and intergrate their apps and plugins. -
Django Python - adding value to TimeField
I'm creating a basic model through the Django framework in Python, which demonstrates an offer on a product which will expire after 3 hours. This is my current model: class Offers(models.Model): product_id = models.CharField(max_length=10) original_price = models.CharField(max_length=5) discounted_price = models.CharField(max_length=5) offer_started = models.TimeField(auto_now_add=True, blank=True) offer_expires = ????????? (NB: The date is not important, which is why I have used a TimeField). Is there a simple way to automatically set the "offer_expires" field to 3 hours after the time in the "offer_started" field? Or if not linked to this field directly, the time that the entry is added? Many thanks! -
"Backend not found" django social auth
When I'm trying process social authorization with Google or Facebook, I get this error without trace for both socials. [Backend not found][1] Someone can find an mistake in social_django settings? settings INSTALLED_APPS = [ ... 'social_django', ... ] MIDDLEWARE_CLASSES = [ ... 'social_django.middleware.SocialAuthExceptionMiddleware' ] TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] AUTHENTICATON_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.google.GoogleOAuth2', 'users.backends.AuthBackend', ) SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_FACEBOOK_KEY = '...' SOCIAL_AUTH_FACEBOOK_SECRET = '...' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY ='...' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '...' urls.py urlpatterns = [ url('', include('social_django.urls', namespace='social')), ... ] template <a href="{% url 'social:begin' backend='google-oauth2' %}">FB</a> <a href="{% url 'social:begin' backend='facebook' %}">GOOGLE</a migrations all OK Applying social_django.0001_initial... OK Applying social_django.0002_add_related_name... OK Applying social_django.0003_alter_email_max_length... OK Applying social_django.0004_auto_20160423_0400... OK Applying social_django.0005_auto_20160727_2333... OK Applying social_django.0006_partial... OK Applying social_django.0007_code_timestamp... OK Applying social_django.0008_partial_timestamp... OK -
__get__() method without owner, instance parameters DJANGO
Quick question about something I am struggling with. Reading the Python-documentation, __get__ is defined with the necessary parameters: object.__get__(self, instance, owner) I am currently learning about writing custom middleware within Django. In the official Django documentation, an example of a middleware-class has a method: def __call__(self, request): How is this possible? How can the middleware- __call__ take request and skip instance and owner? Thank you! -
Django strange SlugField validation, error not raised before clean()
django 2.0 I have a django model, with a slug as primary key from django.core.validators import validate_slug class MyModel(models.Model): # with slug field alias = models.SlugField(max_length=200, primary_key=True, unique=True) # or charfield with slug validator (should be exactly the same) alias = models.CharField(max_length=200, primary_key=True, unique=True, validators=[validate_slug]) The problem i have, in my form i have a clean method, to validate the values of multiple fields, not individually. This method should theoretically be called after the clean_fields method, but with the SlugField, it seems the field validation is not raised before the form's clean() method. My forms.py: class MyForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' def clean(): cleaned_data = super().clean() cleaned_data['alias'] # key error with SlugField return cleaned_data To resume, with the CharField with validate_slug, everything works as intented, validation error is raised in my form, before the clean() method But with SlugField, the validation error is not raised and i got a key error because the field is missing, because not valid, even if the exception was not raised. To trigger the validation error i use accented characters, 'ééé', but allow_unicode is set to False by default.