Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx service of type LoadBalancer vs ingress (using nginx-ingress) vs ingress + nginx service of type ClusterIP
We are moving from standalone docker containers architecture to K3s architecture. The current architecture uses a Nginx container to expose multiple uwsgi and websocket services (for django). I'm reading conflicting opinions on the internet over what approach should be used. The options are: Nginx service of type LoadBalancer (Most conf from existing architecture can be reused) Nginx-ingress (All conf from existing architecture will have to be converted to ingress annotations and ConfigMap) Nginx-ingress + nginx service of type ClusterIP (Most conf from existing architecture can be reused, traffic coming into ingress will simply be routed to nginx service) -
Filter objects based on token expiry date and user date_joined using Q and "gt" Django
I want to delete users that haven't activated their accounts when the activation token have expired, activation token expires after 30 minutes. from django.db.models.functions import Now def delete_unactivated_users(): User = get_user_model() expiry = User.date_joined + timedelta(seconds=1800) unactivated_users = User.objects.filter(Q(Now()__gt=expiry) & (Q(is_active = False))) for user in unactivated_users: user.delete() print('<<<User Deleted>>>') user.save I am getting a syntax error on line 5 of the code, I tried using unactivated_users = User.objects.filter(Q(expiry__lt=Now()) & (Q(is_active=False))) but it didn't result in the same meaning. The problem seems to be the placing of Now() and expiry on line 5 -
How we can get the updated data by refreshing the cache using the cache_page in DRF with the same route?
The website is similar in functionality to Twitter and we're using a Django caching mechanism for the feed but when the user created his post he is not able to find his post for the next 10 minutes due to the caching and we want to show the latest results to the user so, how we can show the latest data to the user after creating his post using the same route Here is the urls.py code from django.views.decorators.cache import cache_page from . import views CACHE_TIME=60*10 urlpatterns = [ path('', cache_page(CACHE_TIME)(views.PostListAPIView.as_view()), name="post-list") ] if I call the API --> http://127.0.0.1:8000/v1/posts/ then data will be stored in the cache for the next 10 minutes but I want to refresh after the specific event so, how can I get the updated data before the 10 minutes also, I have found a solution for it if we pass http://127.0.0.1:8000/v1/posts/?{username}=true then we can get the latest data for the user but is there any other better approach or possibility to show the latest data? if yes, then please list the method and some details about it -
Merging multiple migration files into a single migration file in Django
I have multiple migration files in an app. I want to merge all those migration files into a single file using squash command. I want to how to handle circular dependency issue. -
Can I access the child model from the parent?
I have created a productForArt and albomForArt model From producForArt I inherit to albomForArt Making a view based on generic.ListView And I output it in the template, Can I access the number Of Pages field in the template albomForArt models, or in this case Django returns an object of the albomForArt model, but with properties that were inherited from albomForArt? models from django.db import models class productForArt(models.Model): class Meta: verbose_name = u'товар' verbose_name_plural = u'товары' price = models.IntegerField(verbose_name="цена", default=0) title = models.CharField(max_length=300, verbose_name="название товара", null=True) description = models.CharField( max_length=1000,verbose_name="Описание товара", null=True) type = models.ForeignKey('typeProductForArt', on_delete=models.PROTECT) def getType(self): return self.type def __str__(self): return str(self.title) + ' по цене' + str(self.price) + ' шт' class albomForArt(productForArt): numberOfPages = models.IntegerField(default=10,verbose_name="количество станиц" ) class typeProductForArt(models.Model): title = models.CharField(max_length=200, default="none") def __str__(self): return self.title vievs from django.views import View, generic from .models import productForArt class startPage(generic.ListView): model = productForArt template_name = "startPage.html" context_object_name = "productForArt_list" queryset = productForArt.objects.all()[:20] templates {% if productForArt_list %} <section class="productsStartpage"> {% for productForArt in object_list %} <article class="productForArtStartpage"> <h1>{{productForArt.title}}</h1> <p>{{productForArt.description}}</p> {% endif %} </article> {% endfor %} </section> {% else %} <p>товара нету</p> {% endif %} -
Multi screen user input in Django to create one composite order
I am designing a consumer app and I will be writing it in Django. What I would like to be able to do is over a series of templates/screens accept user input. The input from one screen will be relevant to subsequent screen and should be available to the javascript and html in these subsequent screens e.g. I have one lead screen where you choose a type of 1, 2 or 3 and depending on that the javascript on the following screen controls how many pins a user is allowed to drop on a map. At the end of the last user input screen I would like to create an order with a status of ‘payment pending’ with all of the user variables stored on it and then go to a payment screen, and if there is a successful payment set the order to a status of ‘ready to process’. I have looked at some video tutorials about building an e-commerce aplication and read some online resources and I wondered is a ‘context’ the way to do this of is another method such as a session variable or is there another recommended method. Also, is best practice to wait to … -
How to prevent data tampering when form is set as readonly with Django?
INTRO: I have a Django web app which does the following: Allows the user to fill the form After the form is submitted, it shows the form with the previously filled values In step 2, the form fields are set as read-only because they should not be modified. So in my views.py file I have the following information: def insert_data(request): # Get the form from a previous post request (coming from step1) form_one_item = ProductForm(request.POST, request.FILES) # Set the fields as readonly (this is step 2) form_one_item.fields['name'].widget.attrs['readonly'] = True return render(request, 'mypage.html', {'form_one_item':'form_one_item'}) The form therefore looks like this: and it is supposed to be resubmitted through another post request (I know it is confusing but I need to do so). PROBLEM: At first glance, it looks like it is all fine but then I noticed that I can right-click on the field and modify its content: As a matter of fact if I repost the readonly form, the value shown is modified according to what I write into the value field. QUESTION: Are you able to suggest a possible way to keep the readonly option but at the same time to avoid to pass a modified value once I … -
selenium + python + django - web driver locally but not after deployment
When i run app locally this error does not appear ,it appears when i run the live version on heroku Error from heroku :raise WebDriverException( selenium.common.exceptions.WebDriverException: Message: Service /app/.wdm/drivers/chromedriver/linux64/106.0.5249/chromedriver unexpectedly exited. Status code was: 127 from selenium import webdriver from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time import os import requests from pathlib import Path from twilio.rest import Client from webdriver_manager.chrome import ChromeDriverManager account_sid = '' auth_token = '' client = Client(account_sid, auth_token) def download_path(path:str): """add download path """ try: file = open("down_path.txt","w") file.write(path) file.close() except: print("cannot write path") def download(song, artist = None, play_after_downloading = True): """Downloads the video to given directory""" try: file=open("down_path.txt") down_path=file.read() down_path=down_path.strip() file.close() except: down_path = os.getcwd() print("It will not take more than 1 minute if your download speed is good") if artist: song=song+ ' by ' +artist video=song chromeOptions=Options() chromeOptions.add_experimental_option("prefs",{"download.default_directory":down_path}) chromeOptions.add_argument("--headless") #service = Service(executable_path=ChromeDriverManager().install()) #driver = webdriver.Chrome(service=service) driver = webdriver.Chrome(ChromeDriverManager(path=os.getcwd()).install(),options=chromeOptions) wait=WebDriverWait(driver,3) presence = EC.presence_of_element_located visible = EC.visibility_of_element_located driver.get("https://www.youtube.com/results?search_query=" + str(video)) ads =True wait.until(visible((By.ID, "video-title"))) try: driver.find_element(By.XPATH,"//span[contains(@class,'style-scope ytd-badge-supported-renderer') and text()='Ad']") except Exception as e: ads=False if ads: vid = driver.find_element(By.ID,"video-title") vid.click() … -
Django CRUD works but wrong path
@login_required(login_url='/users/login') @permission_required('users.change_user', login_url='users/login') def edit(request, profile_id): try: user = User.objects.get(pk=profile_id) except User.DoesNotExist: raise Http404("Profile does not exist") return render(request, 'UI/edit.html', {'users': user}) def processedit(request, profile_id): user = get_object_or_404(User, pk=profile_id) profile_pic = request.FILES.get('image') try: fname = request.POST.get('fname') lname = request.POST.get('lname') email = request.POST.get('email') position = request.POST.get('position') except (KeyError, User.DoesNotExist): return render(render, 'UI/detail.html', {'user': user, 'error_message': "Problem updating record"}) else: user_profile = User.objects.get(id=profile_id) user_profile.user_fname = fname user_profile.user_lname = lname user_profile.user_email = email user_profile.user_position = position if profile_pic: user_profile.user_image = profile_pic user_profile.save() return HttpResponseRedirect(reverse('users:detail', args=(profile_id,))) from views.py here from edit.html {% extends 'base.html' %} {% block title %} {{ user.user_fname }} {{ user.user_lname }} {% endblock %} {% block content %} {% if error_message %} <p class="alert alert-danger"> <strong>{{error_message}}</strong> </p> {% endif %} <h1> Edit User Profile</h1> <form action="{% url 'users:processedit' user.id %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label>First Name</label> <input type="text" name="fname" id="fname" class="form-control" required value="{{ users.user_fname }}"> </div> <div class="form-group"> <label>Last Name</label> <input type="text" name="lname" id="lname" class="form-control" required value="{{ users.user_lname }}"> </div> <div class="form-group"> <label>Email</label> <input type="text" name="email" id="email" class="form-control" required value="{{ users.user_email }}"> </div> <div class="form-group"> <label>Position</label> <input type="text" name="position" id="position" class="form-control" required value="{{ users.user_position }}"> </div> <div class="form-group"><br> <label>User Image</label><br><br> <input type="file" name="image" id="image"> </div> <br> <button … -
'QuerySet' object has no attribute 'id'
I was building a django project in that I need to create an edit option for a particular model named SchoolDetail. But while fetching the data from this table using id, its showing the above error views.py def SchoolPage(request): school_details = SchoolDetail.objects.all() school_details_pk = school_details.id context = {'school_details': school_details, 'school_details_pk':school_details_pk} return render(request, 'busschool.html', context) models.py class SchoolDetail(models.Model): school_name = models.CharField(max_length=100, blank= True, null=True) school_place = models.CharField(max_length=100, blank= True, null=True) school_email = models.CharField(max_length=100, blank= True, null=True) school_address = models.CharField(max_length=100, blank= True, null=True) school_phone = models.CharField(max_length=15, blank= True, null=True) is_verified = models.BooleanField(default=False) def __str__(self): return self.school_name template enter code here <tbody> {% for i in school_details %} <tr> <td>{{i.school_name}}</td> <td>{{i.school_place}}</td> <td>{{i.school_email}}</td> <td>{{i.school_address}}</td> <td>{{i.school_phone}}</td> <td>{{i.is_verified}}</td> <td><a href="{% url 'schooledit' school_details_pk %}">click</a></td> </tr> {% endfor %} <tbody> -
Keyerror at file in Python Django
KeyError at /file/ It's working on 25% but when I select 50% or 75% it gives this error. Please help. My website https://summarizingtool.org. Keyerror -
Tagged Duplicate Entries After user submits the form Django
can someone help me figure out... I would want to automatically trigger in database if the entries that was posted by a different user is a possible duplicate. if entries like date, time and location are the same... how can I do this? Thank you -
Django - How to force server time on DateTimeField?
I have a datetime field on a model date_time = models.DateTimeField(auto_now_add=True, blank=True, null=True) I need it to be as server time, the problem is when i change local time on pc the field created with the modified time and date. Is it because my server is local (for dev) or is it how datetimefield field works? Thanks! -
Django dumpdata generating
I have a question how to generate dumpdata without this txt on start: [1mLoading .env environment variables...[0m Here is an example: [1mLoading .env environment variables...[0m [ { "model": "auth.permission", "pk": 1, "fields": { "name": "Can add permission", "content_type": 1, "codename": "add_permission" } }, .... I can't find solution, it is annoying, because i want to do a sh script docker-compose exec django pipenv run python manage.py dumpdata --indent 2 > fixtures/test_dumpdata.json Thanks for all help. -
Scheduled tasks in Django to update data in the models (database)
I need to schedule tasks via Pythonanywhere, to update some records in my database. As an example, I do have Events as models: models.py class Events(models.Model): event_title = models.CharField(max_length=300) event_info = models.TextField(max_length=2000) event_date = models.DateField(default=now) event_time = models.TimeField(default='00:00') event_location = models.CharField(max_length=150) event_status = models.CharField(max_length=30, choices=EVENT_STATUS_CHOICES, default='New Event') Also within that Events class in models.py I have the following: def save(self, *args, **kwargs): if date.today() > self.event_date: self.event_status = 'Completed Event' super(Events, self).save(*args, **kwargs) Thanks to that, all events in the past, change their status to Completed. Problem is, you need to refresh the page to have the save function run on the production website. It also drives some other functions, e.g. showing the user the count of active events - this one as well, in order to show the right active number of events, has to be refreshed manually. By scheduling tasks in PA to run overnight, iterating through all Events, and if in the past, changing their status. I created the below file and uploaded it to PA Tasks. tasks.py from .models import Events from datetime import date def verify_events(): all_events = Events.objects.all() for event in all_events: if event.event_date < date.today(): event.event_status = 'Completed Event' event.save() I got an … -
Can i use both django autofield and foreignkey on one field?
so i have specific use case currently the database has a table with one field that acts as both primary key and foreign key (and i have no access to change this as it would break other processes) so what i tried with the models is something like this: class Foos(models.Model): foo_id = models.AutoField(primary_key=True) foo_name = models.CharField(max_length=15) foo_dt = models.DateTimeField() class Bars(models.Model): bar_id = models.AutoField(primary_key=True) bar_id = models.ForeignKey(Foos, db_column='bar_id', on_delete=models.CASCADE, blank=True, null=True, related_name='bars') bar_qty = models.IntegerField() bar_image = models.ImageField() That didn't work as django will keep the last bar_id (the foreignField) and ignore the AutoField, the thing is i need the foreign key to do some reverse lookup like Foos.object.values(bars__bar_qty) so i can get the left outer join query. But someone else need the AutoField. I know django is really strict on it but is there a possible solution? i just need to keep the reverse lookup i am fine with autofield if it is possible but the thing is django return an error not permitted. -
My if statement doesn't work with two str
i'm trying to use Django to build a wikipedia like. When I want to search an article, i type the research in the search input. I collect my research in my views.py in a function. I have a list of different entries stores in the wiki. But when i try to compare with an if statement if the content of the request is in my list, automatically, the case is false. below my silly function just for testing what's happened def search(request): request_dict = json.dumps(request.GET) print(request_dict, type(request_dict)) request_dict = json.loads(request_dict) print(request_dict, type(request_dict)) title = request_dict["q"] print(title, type(title)) for item in util.list_entries(): print(item, type(item)) title = title.casefold() print(item.casefold().encode("utf-8"), title.encode("utf-8")) if item.casefold().encode("utf-8") == title.encode("utf-8"): entry(request, item) else: print("ko") pass and this is the print in my terminal {"q": "html"} <class 'str'> {'q': 'html'} <class 'dict'> html <class 'str'> CSS <class 'str'> b'css' b'html' Django <class 'str'> b'django' b'html' Git <class 'str'> b'git' b'html' HTML <class 'str'> b'html' b'html' Python <class 'str'> b'python' b'html' ko how can i fix that? I know that here json.loads and dumps here doesn't do anything more than request.GET["q"]. I'm so disappointed and try everything that i could to fix this bug -
Django get users who have updated their age field in the last 1 day
How can I get users who do not update their age information in last 1 day? I need to use Django ORM. not For loop. I tried something in the second code block but without success. You can tell by looking at what I've done from simple_history.models import HistoricalRecords class User(AbstractUser): age = models.IntegerField() history = HistoricalRecords() ################################################################################ date_start = timezone.now() - timezone.timedelta(days=1) queryset = User.history.filter(history_user_id__in=users,history_date__lte=timezone.now(),history_date__gte=date_start).annotate( lag=Window( partition_by=[F("id")], expression=Lag("age"), order_by=[F("history_date")], ) ) here what i have to do is compare lag with age and see if it is updated -
How to run multiple manage.py using docker file
I have Django application which has docker file and using below command to bring up the application CMD ["gunicorn", "--bind", ":8000", "--workers", "3", "--worker-class", "uvicorn.workers.UvicornWorker", "myapplication.asgi:application"] Would like to run one more process "task_process" which is present in the below directory structure taskApp/ __init__.py models.py management/ __init__.py commands/ __init__.py task_process.py How to execute task_process after loading an application ? I tried the below shell script command to execute same.. But task_process is not running using below commands in startup.sh #!/bin/sh exec gunicorn --bind :8000 --workers 3 --worker-class uvicorn.workers.UvicornWorker myapplication.asgi:application & exec python manage.py task_process Updated existing Docker file as below RUN chmod +x startup.sh CMD ["./startup.sh"] -
When I add settings folder with settings for different environments, I get CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False
I want to make two files with different settings for dev and prod. I created a python package in the app folder where my settings are, and even if I run the app with old settings, I receive an error: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. Here is my project structure: -
Collection uploaded to Ansible Automation Hub displays all files under Documentation and Plugins
I wrote a collection containing one lookup plugin named res_query. This plugin imports two local libraries (credentials.py, resources.py) from the module_utils directory. Further it uses the common.py document fragment from the directory doc_fragments. After uploading this collection to our Ansible Automation Hub, ALL files (common.py, credentials.py, resources.py, res_query.py, README.md) are displayed under Documentation and Plugins. I expected, that only the README.md and res_query.py should be displayed. What I'am doing wrong? namespace.collname ├── CHANGELOG.md ├── galaxy.yml ├── LICENSE.md ├── meta │ └── runtime.yml ├── plugins │ ├── doc_fragments │ │ └── common.py │ ├── lookup │ │ └── res_query.py │ ├── modules │ └── module_utils │ ├── credentials.py │ └── resources.py └── README.md -
"That username is already taken." but there is no entry in DB
In my environment I'm trying to create a new superuser via python .\manage.py createsuperuser. However, when I enter the name I get the following error: Error: That username is already taken.. So I check the auth_user table in PgAdmin and I can see there are no entries. Moreover, the QuerySet is empty when I do the following: from django.contrib.auth.models import User superusers = User.objects.filter(is_superuser=True) superusers >>> <QuerySet []> I'm using a managed cloud-hosted PostgreSQL server with the postgresql_psycopg2 client, and have checked that all credentials are correct. What am I doing incorrectly? I'm using Django 4.1.2. -
Python Datetime Comparison
I'd like to check if the current date is bigger than a date put in by the user. All dates are converted using strftime('%d/%m/%Y'). But if I compare both dates, I get a wrong result: absenzen.view def absenzen(request): if request.user.is_authenticated: # if user is logged in object_list = Subject.objects.order_by('name') subject_list = [] for subject in object_list: subject_list.append(subject.name) absenzen_local = Absenzen.get_absenzen(student=request.user.id, subjects=subject_list) current_date = datetime.date.today().strftime('%d/%m/%Y') return render(request, 'absenzen.html', {'absenzen': absenzen_local, 'current_date': current_date}) else: # else redirect to login page return redirect('loginForm:login') get_absenzen method def get_absenzen(student, subjects): absenzen_dict = {} for subject in subjects: absenzen_list_complete = [] absenzen_object_list = Absenzen.objects.filter(student=student, subject__name=subject).order_by('-date') for absenz in absenzen_object_list: absenzen_list = [] expire_date = absenz.date + datetime.timedelta(days=10) if absenz.excused: absenzen_list.append('Ja') elif not absenz.excused: absenzen_list.append('Nein') absenzen_list.append(expire_date.strftime('%d/%m/%Y')) absenzen_list_complete.append(absenzen_list) print(absenzen_list_complete) absenzen_dict[subject] = absenzen_list_complete print(absenzen_dict) return absenzen_dict html {% if absenzen %} {% for subject, absenzen in absenzen.items %} <button class="collapsible" type="button">{{ subject }}</button> <div class="content"> {% if absenzen %} <ul> {% for absenzen_list in absenzen %} <div class="content-text"> <li>Entschuldigt: {{ absenzen_list.0 }}</li> {% if absenzen_list.0 == 'Nein' %} {{ absenzen_list.1 }} {{ current_date }} {% if absenzen_list.1 < current_date %} <p><strong>Abgabedatum schon abgelaufen</strong></p> {% else %} <p>--> Abgabadatum: {{ absenzen_list.1 }}</p> {% endif %} {% else %} <p>Abgegeben</p> {% … -
Hiding Django form fields using Jquery but it is not hiding form labels (using crispy forms)
I am trying to hide certain fields in a form based on select field choices. For example for Select field "system_description_1" If option "Direct" is selected following fields should be hidden (also hidden by default on page load), but when "Indirect" is selected the fields should become visible. This function is absolutely working fine using Jquery, but it is still showing the form label, It is hiding the field but not the label of the field how do I hide them ? I want to hide the field label when I hide the field, but show the field label when I unhide or show them. Fields: secondary_circulation_pump_model secondary_circulation_pump_capacity models.py: class Systemprofile(models.Model): SYSTEMDESC1 = ( ('direct', 'Direct'), ('indirect', 'Indirect') ) SECONDARYPUMPMODEL = ( ('grundfos', 'Grundfos'), ('cnp', 'CNP'), ('others', 'Others') ) SECONDARYPUMPCAPACITY = ( ('ltr-hr', 'Ltr/hr'), ('others', 'Others') ) name = models.CharField(max_length=255, null=True) system_description_1 = models.CharField(blank=True, max_length=255, null=True, choices=SYSTEMDESC1) secondary_circulation_pump_model = models.CharField(blank=True, max_length=255, null=True, choices=SECONDARYPUMPMODEL) secondary_circulation_pump_capacity = models.CharField(blank=True, max_length=255, null=True, choices=SECONDARYPUMPCAPACITY) forms.py class CreateSystemprofile(ModelForm): class Meta: model = Systemprofile fields = '__all__' system_profile.html {% extends 'base.html' %} {% load static %} {% block content %} {% load crispy_forms_tags %} <script> function Hide() { if(document.getElementById('id_system_description_1').options[document.getElementById('id_system_description_1').selectedIndex].value == "Direct") { document.getElementById('id_secondary_circulation_pump_model').style.display = 'none'; document.getElementById('id_secondary_circulation_pump_capacity').style.display = … -
how to create unicode slug in bangla language in django from title field
I am getting this error in Django: when i click slingle view page in djanog my slug is insert properly but when i try to view single page this error is shown what to do now: Not Found: /ফবরযর-থক-বস-ভড-দয-হব [25/Oct/2022 10:40:42] "GET /%E0%A6%AB%E0%A6%AC%E0%A6%B0%E0%A6%AF%E0%A6%B0-%E0%A6%A5%E0%A6%95-%E0%A6%AC%E0%A6%B8-%E0%A6%AD%E0%A6%A1-%E0%A6%A6%E0%A6%AF-%E0%A6%B9%E0 %A6%AC HTTP/1.1" 404 5408 Module.py user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) type = models.ForeignKey(Type, on_delete=models.CASCADE, null=True) division = models.ForeignKey(Division, on_delete=models.CASCADE, null=True) district = models.ForeignKey(District, on_delete=models.CASCADE, null=True) upazila = models.CharField(max_length=50, blank=True, null=True) postcode = models.ForeignKey(Postcode, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=50, blank=True, null=True) mobile = models.CharField(max_length=50, blank=True, null=True) postoffice = models.CharField(max_length=50, blank=True, null=True) detail = QuillField(null=True, blank=False) bedroom = models.IntegerField(blank=True, null=True) bathroom = models.IntegerField(blank=True, null=True) veranda = models.IntegerField(blank=True, null=True) drawing = models.BooleanField(blank=True, null=True, default=False) dining = models.BooleanField(blank=True, null=True, default=False) status = models.BooleanField(blank=True, null=True, default=True) rent = models.IntegerField(blank=True, null=True) address = models.CharField(max_length=200, blank=True, null=True) google_location = models.CharField(max_length=500, blank=True, null=True) date = models.DateField(auto_now=False, blank=False, null=False) image = models.FileField(blank=True, default="feature_image.jpg") slug = models.SlugField(null=True, blank=True, allow_unicode=True, unique=True) create_date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.title def save(self, *args, **kwargs): if self.slug is None: slug = slugify(self.title, allow_unicode=True) has_slug = AddPost.objects.filter(slug=slug).exists() count = 1 while has_slug: count += 1 slug = slugify(self.title, allow_unicode=True) + '-' + str(count) has_slug = AddPost.objects.filter(slug=slug).exists() …