Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to correctly add a custom '--dry-run' argument to a Django Extensions `runjob` command?
I have a custom Django management job created using django_extensions that deletes old database records. To avoid unintended deletions, I want to add a --dry-run argument to simulate deletions without actually removing data. However, when I execute the command with: uv run python manage.py runjob delete_recordings --dry-run I receive this error: manage.py runjob: error: unrecognized arguments: --dry-run Here's how my simplified job class currently looks: from django_extensions.management.jobs import HourlyJob import logging logger = logging.getLogger(__name__) class Job(HourlyJob): @classmethod def add_arguments(cls, parser): parser.add_argument( '--dry-run', action='store_true', help='Execute the job in simulation mode without deleting any data.', default=False, ) def execute(self, *args, **options): dry_run = options.get('dry-run', False) if dry_run: logger.info("Executing in DRY-RUN mode.") # Logic here to delete records or simulate deletion based on dry_run I followed the Django Extensions documentation to add a custom argument (--dry-run). I expected that when running the command with --dry-run, it would recognize the argument and simulate the operation, logging the intended deletions without performing them. However, the command line returns an error indicating that the argument is not recognized. It seems that Django Extensions isn't picking up the custom argument defined in my job class. What is the correct way to add a custom argument (--dry-run) to … -
assign a custom field order_sl
I'm working with a Django model where I need to assign a custom field order_sl that should increment from the last existing value with a specific filter. Here's what I'm doing currently: prev_ordr = Order.objects.filter(abc).values("order_sl").first() if prev_ordr: new_order_sl = prev_ordr.get("order_sl") else: new_order_sl = 100000 ins.order_sl = F("order_sl") + (new_order_sl + 1) ins.save() ins.refresh_from_db() But I believe this approach is problematic: It pulls the last value into Python instead of handling it in the DB. It’s not thread-safe and likely to break under race conditions if multiple inserts happen at the same time. I'm using PostgreSQL, and I want to ensure that each new row gets a unique, sequential order_sl based on the highest existing value or a dedicated sequence. The order_sl field is not the primary key, and I don’t want to make it an AutoField. ❓ What’s the best, Django-safe, PostgreSQL-optimized way to handle this? Would a raw SQL sequence be better? Or should I use select_for_update() with a transaction block? Thanks! -
Understanding F expression in Django
What I have done is - prev_ordr = Order.objects.filter(abc).values("order_sl").first() if prev_ordr: new_order_sl = prev_ordr.get("order_sl") else: new_order_sl = 100000 ins.order_sl = F("order_sl") + (new_order_sl + 1) ins.save() ins.refresh_from_db() return But I'm not sure about this, this is loading the previous value into the python and not directly managing the database (i think so), as it should be in the case of F expression and it may fail race condition. Can you let me know the correct way, I have to increase the value by 1 (from the last row) in the new row. Thanks -
Django DisallowedHost Error Despite Domain Being in ALLOWED_HOSTS
Problem Description I'm getting a DisallowedHost error in my Django production environment, even though the domain is clearly listed in my ALLOWED_HOSTS setting. I am using traefik. Error Message: django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'api.tuitionwave.com'. You may need to add 'api.tuitionwave.com' to ALLOWED_HOSTS. Current Configuration: My production.py settings file includes: ALLOWED_HOSTS configuration ALLOWED_HOSTS = ["api.tuitionwave.com", "localhost", "127.0.0.1", "django"] # Trust proxy headers USE_X_FORWARDED_HOST = True USE_X_FORWARDED_PORT = True # Security settings SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True) What I've Tried Verified that api.tuitionwave.com is explicitly listed in ALLOWED_HOSTS List item Confirmed the settings file is being loaded correctly Checked that there are no whitespace issues in the domain name And here is my traefik.yml File details http: routers: web-router: rule: "Host(`api.tuitionwave.com`)" entryPoints: - web middlewares: - redirect service: django web-secure-router: rule: "Host(`api.tuitionwave.com`)" entryPoints: - web-secure middlewares: - default-headers service: django tls: # https://docs.traefik.io/master/routing/routers/#certresolver certResolver: letsencrypt -
How to intercept a form submit in websocket connection?
I have "inherited" a piece of code from a chat application. I would like to add some custom checks on the user input upon submission, allowing the submit to be aborted on client side if necessary. I have created a submit handler javascript function in order to execute the checks and transformations, including preventDefault as first instruction: async handleSubmit(event) { event.preventDefault(); // Prevent default form submission ... I have linked the handler to the form: <form class="pg-chat-input-bar" ws-send @submit="handleSubmit($event)" enctype="multipart/form-data" > Yet, no matter what, the form is submitted immediately when the submit button is pressed. The server receives the form in parallel to / before the handler being executed. I can assess that the handler is triggered and does what it is supposed to do but unfortunately the form has already been submitted. I tried @submit.prevent, @submit.stop and even combined both but it doesn't change the outcome. I found many posts asking to capture/intercept/interrupt a form submit but the solutions are as simple as what I tried. What am I doing wrong? As I am not starting from scratch I would prefer modify the code as little as possible and use what is already there. Could it be related … -
How to compare a DecimalField value in Django templates for conditional logic?
I'm working on a Django project where users have an Account model with a DecimalField named account_balance. I'm trying to conditionally show a KYC verification link if the user's balance is exactly 100, and show an error if it's less than that. Here’s my setup: class Account(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) account_balance = models.DecimalField(max_digits=10, decimal_places=2) class KYC(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField() views.py: def settings(request): kycs = KYC.objects.filter(user=request.user) context = { "kycs": kycs, } return render(request, 'public_pages/settings.html', context) template: {% for kyc in kycs %} <p>Your identity is important to the community</p> {% if kyc.user.account.account_balance == 100 %} <a href="{% url 'Kyc_Form' kyc.slug %}">Update KYC</a> {% elif kyc.user.account.account_balance < 100 %} <div class="alert alert-danger"> You need at least 100 coins before applying for KYC. </div> {% endif %} {% endfor %} But this block never renders either the button or the error message. The only thing I see is the static text: <p>Your identity is important to the community</p> I tried printing the balance outside the logic: <p>Balance: {{ kyc.user.account.account_balance }}</p> And it shows something like 100.00. I assume it's a Decimal issue. How can I properly compare a DecimalField like account_balance in the Django template to check … -
Will requests to my site lag and work slowly in django while waiting for celery results?
I use django to create pdf to docx converter using pdf2docx library, and I need to wait a celery task to done and get result from it. Will my site lag and work slowly if a lot of users use it, and how can i do it better? here my views and celery code views.py ''' from django.shortcuts import render from django.http import JsonResponse, HttpResponse from django.http.request import HttpRequest import tempfile import os from .forms import FileUploadForm from django.views.decorators.csrf import csrf_protect from . import tasks from celery.result import AsyncResult @csrf_protect def main_page(request: HttpRequest): if request.method == "GET": # get form = FileUploadForm(request.POST, request.FILES) context = { "form": form } return render(request, 'main/main_page.html', context) if request.method == 'POST' and request.FILES.get('file'): form = FileUploadForm(request.POST, request.FILES) if form.is_valid(): # get file file = request.FILES['file'] size_limit = 2 * 1024 * 1024 # save pdf with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file: if file.size > size_limit: for chunk in file.chunks(): temp_file.write(chunk) else: temp_file.write(file.read()) temp_pdf_path = temp_file.name # start convertor task task: AsyncResult = tasks.convert_pdf_to_docx.delay(temp_pdf_path) # get docx path temp_docx_path = task.wait(timeout=None, interval=0.5) converted_file_name = str(file).replace(".pdf", "") # read docx file and set it in response with open(temp_docx_path, 'rb') as docx_file: file_data = docx_file.read() response = HttpResponse(file_data, … -
django-celery-results: error ModuleNotFoundError: No module named 'django_celery_results'
I try to run "celery -A myproj worker -l info" and it gives me the error ModuleNotFoundError: No module named 'django_celery_results'. All dependencies are installed (django, celery, django-celery-results, redis). I tried to run it with admin rights, but it didn't help as well. I tried changing the python version from 3.13 to 3.11, but also without result. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_celery_results',] -
How to store the refresh token in HttpOnly cookie with Google OAuth2 (PKCE flow) in Django?
I'm using Django with drf_social_oauth2 and oauth2_provider for Google OAuth2 authentication. I’ve successfully implemented the PKCE authorization flow. Step 1: Frontend redirects to: GET /api/v1/o/authorize/?client_id=<client_id>&response_type=code&redirect_uri=http://127.0.0.1:5173/callback&code_challenge=<challenge>&code_challenge_method=S256 Step 2: Frontend exchanges code at: POST /api/v1/o/token/. Backend responds with: { "access_token": "...", "expires_in": 36000, "refresh_token": "...", ← this is what I want to move into a cookie ... } My configuration: # urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("api/v1/o/", include("oauth2_provider.urls", namespace="oauth2_provider")), ] # settings.py (snippets) INSTALLED_APPS = [ ... 'oauth2_provider', 'social_django', 'drf_social_oauth2', ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.google.GoogleOAuth2', 'drf_social_oauth2.backends.DjangoOAuth2', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '<your-client-id>' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '<your-client-secret>' REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "oauth2_provider.contrib.rest_framework.OAuth2Authentication", "drf_social_oauth2.authentication.SocialAuthentication", ), } LOGIN_REDIRECT_URL = "/" What works: PKCE is working. Google OAuth2 authorization is integrated using social-auth-app-django and drf-social-oauth2. I can extract the original Google access_token from the user's social_auth.extra_data. What I want: I want to store the refresh_token in a secure HttpOnly cookie instead of returning it in the JSON response — to reduce XSS risks. I would be grateful for any advice, code examples on how to solve this, or references to sources where a solution can be found. -
celery chord callback executes before tasks completes
I have a celery workflow, as presented in the above image. I am facing a scenario where the parent_task_callback is executed before all the sub_parent_task callbacks are executed. None of these tasks has ignore_result set to false nor have I globally set it to false. What am I missing? The code looks like this: @app.task def sub_parent_task(): chord(child_tasks_list)(sub_parent_task_callback.si()) @app.task def parent_task(): chord(sub_parent_tasks_list)(parent_task_callback.si()) -
How to handle error reporting and validation of uploaded files using django-formset?
Short version I'm using django-formset to create a contact form that includes a file upload field. When an incorrect file is selected, no error message is shown. When uploading the form with an incorrect file, the field is cleared and a "Please either submit a file or check the clear checkbox, not both" error is thrown for this field, which is inaccurate. Because the field is cleared I cannot validate it anymore and return a descriptive error message. Is there any documentation that describes how this should be handled? Long version I want to custom validate file uploads while using django-formset. Initially, I'm mainly looking to validate image files, but later other types as well. Problem one Error messages do not show when selecting invalid files. Upon selecting a file that is too large, nothing happens (no errors are shown, no POST request is sent, GUI is not updated). Here I would at least expect a message to display "File size is too big" or so. When selecting a file with an invalid extension, a POST request is sent and the GUI is updated to show the selected file (with or without a valid thumbnail). However, no error message is … -
UnicodeDecodeError when connecting to PostgreSQL using psycopg2, despite UTF-8 encoding everywhere
I'm trying to connect to a local PostgreSQL database using psycopg2 in Python. Here's the code I'm using: import psycopg2 params = { 'dbname': 'database_name', 'user': 'user_name', 'password': 'mypassword', 'host': 'localhost', } for k, v in params.items(): print(f"{k}: {v} (type={type(v)}, encoded={v.encode('utf-8')})") try: conn = psycopg2.connect(**params) print("Connexion OK") conn.close() except Exception as e: print("Connexion Erro") print(type(e), e) The printed output confirms that all parameters are strings and UTF-8 encoded. However, I still get the following error: Connexion Erro <class 'UnicodeDecodeError'> 'utf-8' codec can't decode byte 0xe9 in position 103: invalid continuation byte I also checked the server and client encoding on PostgreSQL using: SHOW server_encoding; SHOW client_encoding; Both return UTF8. Given that all inputs are UTF-8 and the database is configured for UTF-8, I don't understand why this error occurs. Has anyone encountered this before or has an idea of where this byte 0xe9 might come from? What else should I check? -
Seeking a Clear Roadmap for Learning Python and PHP as a Junior Developer (with Remote Work Goals) [closed]
Seeking a Clear Roadmap for Learning Python and PHP as a Junior Developer (with Remote Work Goals) Body: Hello everyone, I’m a junior developer currently learning both Python and PHP, and I find myself a bit confused about which path to focus on or how to organize my learning. I'm still a student, and my primary goal is to gain enough skills to start working remotely from home — ideally through freelancing platforms or remote internships. I'm looking for a clear and structured roadmap that can guide me in becoming job-ready in either or both languages (Python with frameworks like Django or Flask, and PHP with Laravel). I’d like to understand: What steps should I take to build a solid backend skill set? What technologies or tools should I prioritize (e.g. databases, APIs, deployment)? Should I focus on one language or is it okay to learn both in parallel? What kind of projects should I build to gain real-world experience? What are the best freelancing platforms or websites for beginners? How can I showcase my skills effectively to land small jobs or internships? If anyone has a well-organized learning roadmap, or professional advice based on your own experience starting out … -
What are web servers exactly and why do we use app servers if we have web servers?
I am new to the field of devops i always get confused between app servers and web server (mostly with app servers). Also why do we need app servers if we have web servers. please explain me both the concepts in easy language but in a technical way so that i can map properly by using examples of uswgi and nginx as app and webs servers respectively -
How can I create a grouped set of elements for Grouped Radio Buttons
How can I create a set of elements to place in views? GROUPED_CHOICES I have a list of elements. [m1-x, m2-x] - the number of repetitions of each group name - the number of elements to group [m1,m1, m1, m1, m2, m2 ] - all group names that must belong to the choices elements. [q, w, e, r, t, y] - choices elements [(‘q’, 'q), (‘w’, ‘w’), (‘e’, ‘e’),(‘r’, 'r), (‘t’, ‘t’), (‘y’, ‘y’)] I took this from chatgpt. but I don't know yet how to create such a set of elements. GROUPED_CHOICES = [ ('Fruits', [ ('apple', 'Apple'), ('banana', 'Banana'), ]), ('Vegetables', [ ('carrot', 'Carrot'), ('lettuce', 'Lettuce'), ]), ] from django import forms class FoodForm(forms.Form): food = forms.ChoiceField( choices=GROUPED_CHOICES, widget=forms.RadioSelect ) {% for group_label, group_choices in form.food.field.choices %} <fieldset> <legend>{{ group_label }}</legend> {% for choice_value, choice_label in group_choices %} {# Get the radio input manually using the field's id_for_label logic #} {% with field_id=form.food.auto_id %} {% set widget_id = field_id|string + '_' + choice_value %} {% endwith %} <label for="{{ widget_id }}"> <input type="radio" name="{{ form.food.name }}" value="{{ choice_value }}" id="{{ widget_id }}" {% if form.food.value == choice_value %}checked{% endif %}> {{ choice_label }} </label><br> {% endfor %} </fieldset> … -
How to get mutual followers (mutual friend) for users - Django
How do I get mutual followers (friends of friends) with request.user to be displayed for each users posts, I was able to display the count for mutual followers for each users posts on newsfeed. How can I get it done? What I tried: I was able to do this but I do not think it is the best way because when I use slice to show three mutual users images it does not work properly for all users. This is what I tried: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) profile_pic = models.ImageField(upload_to='UploadedProfilePicture/', default="ProfileAvatar/avatar.png", blank=True) following = models.ManyToManyField( 'Profile', # Refers to the User model itself symmetrical=False, # If A follows B, B doesn't automatically follow A related_name='followers', # Reverse relationship: get followers of a user blank=True, ) class Post(models.Model): poster_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, blank=True,null=True) def following_view(request): posts = Post.objects.filter( Q(poster_profile__profile__followers__user=request.user)).order_by("?").distinct() mymutual_followers = request.user.profile.following.filter(id__in=request.user.profile.following.values_list('id', flat=True)) {% for post in posts %} {% for user_following in mymutual_followers %} {% if user_following in post.poster_profile.profile.following.all|slice:"3" %} <img src="{{ user_following.profile_pic.url }}" class="hover-followers-img"/> {% endif %} {% endfor %} {% endfor %} The code above is what I tried and it worked, but add slice:"3" to show just 3 images do not work properly for some users, so … -
How can I insert additional text elements through a loop into the set of choices form elements in the template?
How can I move the iterable value (radio) from the outer loop to the inner one, bypassing the inner loop iteration? How can I get the value (radio) of the outer loop. I have a nested loop that generates additional fields. The value from the outer loop. I plan to get the value from the outer loop not 30 times - but how many times in the outer loop 5 times. How can I skip the inner iteration? I have been thinking for several days how to make such a scheme. I have a choices field. I am trying to insert section names between them. I can just have 25 choices elements. And I want to divide them into groups. For example, into several groups and implement names for each group. Something similar to a table with categories. In the example in the figure, from 1 to 11 these are choices elements and between them the name of the group by which they are divided. Moreover, each time the number of choices elements is different, as is the grouping. How can I insert additional text elements through a loop into the set of choices form elements in the template? <fieldset> … -
Job hunting advice for a self-taught dev feeling stuck
I'm a self-taught full-stack web developer. I've been learning and building projects for about a year now using technologies like Python (Django) and React.js. Now that I feel somewhat confident with my skills, I think it's time to start looking for a job. But here's my problem, I genuinely don't know how to start the job hunting process. It feels overwhelming, and to be honest, I'm a bit frightened to take that first step. I’ve been procrastinating because I feel uncertain, and when I spoke with a friend who’s also learning, he said he feels the same way. I'm not sure what I should be doing right now: Should I be applying to junior roles directly? Do I need to work more on open source? How do I know when I’m “ready”? What’s the best way to approach recruiters or companies? If any of you have gone through this stage or have tips on how to get started with the job hunt—especially as a self-taught developer, I’d really appreciate your advice. -
DRF I need object/instance-level premissions granted but view/model-level permissions denied
I have a rather simple backend and API with two user types, User and Admin. I have created groups and permissions in Django. The Admin should CRUD everything and the User should only view and edit itself. I've used DjangoModelPermissions in DRF and it works as expected for view/model-level permissions. This looks like this. class MyAppModelPermissions(permissions.DjangoModelPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['GET'] = ['%(app_label)s.view_%(model_name)s'] For object/instance-level permissions, I added a Custom Permission that just has the has_object_permission() method and checks if the requesting user is the object being accessed. It looks like this: class UserAccessPermission(permissions.BasePermission): def has_object_permission(self, request, view, obj): if (request.user == obj) or (get_user_role(request.user) in ("admin",)): return True else: return False Now, since in DRF, view/model-level permissions are checked first, and if allowed, object/instance-level permissions can be checked, it is allways allowed for any user, say, user with id=4, to view all other user's data when accessing the list of users, ie: api/users/. That's because that perimssion needs to be allowed for a user to be able to access its own data (ie: api/users/4/). I've managed to "resolve" this by adding a check in the list() method of the User ModelViewSet, so that if a user tries to … -
Django PWA offline template not showing
why my django pwa offline template is not showing i checked everthing is in its position and also there is to typo mistakes my offline.html is in write path templates/patients/offline.html and i also added PWA_APP_OFFLINE_TEMPLATE = 'patients/offline.html' in my settings.py and also in my project urls.py `urlpatterns = [ path('admin/', admin.site.urls), path('',include('patients.urls')), path('', include('pwa.urls')), ]` my pwa is working fine but online my offline template is not showing i checked in devtools in chrome and in application my service worker and manifest.json is good and activated and in also cache storage i see that /offline/ anyone can help to solve this issue -
How can I move an iterable value from an outer loop to an inner loop without iterating through the inner loops?
How can I move the iterable value (radio) from the outer loop to the inner one, bypassing the inner loop iteration? How can I get the value (radio) of the outer loop. I have a nested loop that generates additional fields. The value from the outer loop. I plan to get the value from the outer loop not 30 times - but how many times in the outer loop 5 times. How can I skip the inner iteration? <fieldset> <legend>{{ form_2.name_working.label }}</legend> {% for radio in form_2.name_working %} {% for i in kol_vo_iteracii_categ|get_range %} <a>Cat</a> <div class="myradio"> {{ radio }} </div> {% endfor %} {% endfor %} </fieldset> -
How to use Django Q objects with ~Q() inside annotate(filter=...) to exclude a value?
I'm refactoring a legacy Django Job to use annotate with filtered Count aggregations instead of querying each record individually (avoiding the N+1 problem). I want to count the number of related EventReport objects per Store, excluding those where status="C". So I wrote something like: stores_with_monitoring_enabled.annotate( total_cards=Count( 'eventreport', filter=Q( eventreport__event_at__gte=day_30_days_ago_start, eventreport__event_at__lte=yesterday_end ) & ~Q(eventreport__status='C') ), # ... etc But Django raised SyntaxError: positional argument follows keyword argument. I also tried: # ... etc filter=Q( eventreport__event_at__gte=start_date, eventreport__event_at__lte=end_date ) & ~Q(eventreport__status="C") # ... etc But I'm unsure if this is the correct pattern inside annotate()'s filter. I expected to get only related objects where `status != "C" without any errors. PS: I looked into other solutions on StackOverflow and the suggestions on this one: How do I do a not equal in Django queryset filtering?, but I could'nt get it working when using Q() alongside ~Q() with other kwargs. What’s the best approach to express status != 'C' inside a Count(..., filter=...) clause? -
How to use CustomUser with dj_rest_auth to sign up with email and password
How to use CustomUser with dj_rest_auth to register with email and password. I have the source code below, but the username information is required during the sign-up process. I would like to know how to sign up with only the email, password1, and password2 information. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'rest_framework', 'dj_rest_auth', 'dj_rest_auth.registration', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_framework.authtoken' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'allauth.account.middleware.AccountMiddleware' ] SITE_ID = 1 AUTH_USER_MODEL = 'accounts.CustomUser' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_SIGNUP_FIELDS = ['email', 'password1', 'password2'] ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_VERIFICATION = 'none' REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'accounts.serializers.CustomRegisterSerializer', } accounts/models.py from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email accounts/serializers .py from dj_rest_auth.registration.serializers import RegisterSerializer class CustomRegisterSerializer(RegisterSerializer): def get_cleaned_data(self): return { 'email': self.validated_data.get('email', … -
Slug is not created correctly due to using django parler
I have a problem creating a slug based on the title and pk, due to the use of parler. I'm using Parler for multilinguality in my API, and when I try to create a slug like title-pk I'm getting various bugs. My model: class Events(TranslatableModel): ... translations = TranslatedFields( title=models.CharField(max_length=255, verbose_name=_("Event title")), body=MDTextField(verbose_name=_("Event body")), ) slug = models.SlugField(blank=True, max_length=255, verbose_name=_("Event slug")) ... So, I tried using the save() method, but I got a slug like -None or -pk. def save(self, *args, **kwargs): if not self.slug: title = self.safe_translation_getter("title", language_code="uk") base_slug = slugify(title) self.slug = f"{base_slug}-{self.pk}" super().save(*args, **kwargs) I also used a signal, which also did not work. @receiver(post_save, sender=Events) def generate_slug_after_translation(sender, instance, **kwargs): if not instance.slug: uk_title = instance.safe_translation_getter("title", language_code="uk") if uk_title: base_slug = f"{uk_title}-{instance.pk}" instance.slug = slugify(base_slug)[:255] instance.save(update_fields=["slug"]) What did I do wrong, and what should I do next? -
Take a long time I load the Django library using PyCharm
Why does it take a long time I load the Django library using PyCharm? steps: I had created a New Project import django, but prompt error Install django Package in Interpreter it doesnt take long time I install other package. Is there something wrong with settings?