Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError at /dashboard/profiles/create/ Field 'id' expected a number but got []
Hey engineers I have been trying to fetch model choices through the view so that I can render them in the template to make it easy for the users, but I swear it has given me some hard times I thought its because I had no items in the database but even when I added them the error persisted. Please give me ideas I am sure with you it will work here is my model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to = '', default = path_and_rename, blank=True) provider = 'provider' requester = 'requester' user_types = [ (provider, 'provider'), (requester, 'requester'), ] user_type = models.CharField(max_length=155, choices=user_types, default=requester) first_name = models.CharField(max_length=255, default='') last_name = models.CharField(max_length=255, default='') GENDER_MALE = 'Male' GENDER_FEMALE = 'Female' OTHER = 'Other' GENDER_CHOICES = [ (GENDER_MALE, 'Male'), (GENDER_FEMALE, 'Female'), (OTHER, 'Other'), ] gender = models.CharField(max_length=15, choices=GENDER_CHOICES, blank=True) email = models.EmailField(default='none@email.com') phonenumber = models.CharField(max_length=15, default='') #blank=True, null=True birth_date = models.DateField(default='1975-12-12') residential_address = models.CharField(max_length=255, default='') village = models.CharField(max_length=255, default='') city = models.CharField(max_length=255, default='') state = models.CharField(max_length=255, default='') country = models.CharField(max_length=255, default='') education_background = models.CharField(max_length=255, default='') single = 'single' married = 'married' statuses = [ (single, 'single'), (married, 'married'), ] marrital_status = models.CharField(max_length=255, choices=statuses, default='single') USD = 'United States … -
Django Rest Framework: backend not found
I'm trying to create and authentication with github account to DRF. why i get 404 error and can't get to github authentication page? I provided the code extracts. If any information is required or you have any questions please let me know. Here's the views.py class BookViewSet(ModelViewSet): queryset = Book.objects.all() serializer_class = BooksSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] permission_classes = [IsAuthenticated] filterset_fields = ['price'] search_fields = ['name', 'author_name'] ordering_fields = ['price', 'author_name'] def auth(request): return render(request, 'oauth.html') And here's the settings.py # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'social_django', 'store', ] 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", ] ROOT_URLCONF = "books.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": ['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", ], }, }, ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'books_db', 'USER': 'books_user', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', 'TEST': { 'NAME': 'test_finance', }, } } AUTHENTICATION_BACKENDS = ( 'social_core.backends.github.GithubOAuth2', 'django.contrib.auth.backends.ModelBackend', ) REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } SOCIAL_AUTH_POSTGRES_JSONFIELD = True SOCIAL_AUTH_GITHUB_KEY = '-some github key' SOCIAL_AUTH_GITHUB_SECRET = 'git secret' My urls.py router = SimpleRouter() router.register(r'book', BookViewSet) urlpatterns = [ … -
User activity concept using django
I need to make a feature which shows if user is active or not (like on facebook). What is the best and most common way to do this? My concept looks like this: When the user logs in or refreshes the JWT token, it starts a javascript loop which sends f.e. every 3 minutes post request which sets inside User model object current date. Then if another user will enter that user's profile he will get the date from User object and check if current date minus the date from User object < 3 min - if so, it means that user is active, else user is not active. Is it a good way? Should I use websockets for it? I am using DRF and React. -
Django - User model last active column
How can I make a column in my AbstractUser Model that has the date of the last time the user logged in the app? -
form associated with the model not submitting to database
I'm newbie in the Python. I made a landing page that has a form with sending a phone number, but it does not get into the database. Form associated with the model Models.py: from django.db import models from phonenumber_field.modelfields import PhoneNumberField class CallOrder(models.Model): first_name = models.CharField(max_length=50, blank=True, verbose_name='First name') phone = PhoneNumberField(null=False, blank=False, unique=False, verbose_name='Phone') email_field = models.EmailField(blank=True, verbose_name='Email') message = models.TextField(max_length=400, blank=True, verbose_name='Comments') created_at = models.DateTimeField(auto_now=True, verbose_name='Created at') class Meta: verbose_name = 'Call order' verbose_name_plural = 'Call orders' Views.py: from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import CallOrderForm def base(request): header_menu_button = {'': 'Home', 'qui_sommes_nous': 'Qui sommes nous', 'nos_services': 'Nos services', 'avis': 'Avis', 'contacts': 'Contacts', 'faq': 'FAQ', 'partenaires': 'Partenaires'} content_body = {'qui_sommes_nous': 'qui_sommes_nous_content', 'nos_services': 'nos_services_content', 'avis': 'avis_content', 'contacts': 'contacts_content', 'faq': 'faq_content', 'partenaires': 'partenaires_content'} form = CallOrderForm() return render(request=request, template_name='repair_service/base.html', context={'title': 'Mr.Ginzby', 'header_menu_button': header_menu_button, 'content_body': content_body, 'form': form}) def call_back(request): if request.method == 'POST': form = CallOrderForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/thanks/') else: form = CallOrderForm() return render(request, 'repair_service/base.html', {'form': form}) Html: <form action="" method="post"> {% csrf_token %}<br> {{ form.as_p }} <div class="d-grid gap-2"><input type="submit" value="Submit" class="btn btn-success"></div> </form> -
Get Kwargs through an intermediate page
I have a model (grade) inside another model (homework) which is inside another model (activity) and when I submit the grade of a homework and try to get back to activty I loose the id of the activity. How do I get the right kwargs to get back to activity after submiting a grade? Or any other solution you may think about. Thanks in advance. Views.py def grade_homework(request, id): if not request.user.is_authenticated: return render(request, "auctions/login.html") try: activity = Activity.objects.get(id=id) except Activity.DoesNotExist: activity = None try: hw_upload = Hw_upload.objects.get(id=id) except Hw_upload.DoesNotExist: hw_upload = None if request.method == 'POST': form = Hw_gradeForm(request.POST, request.FILES or None) if form.is_valid(): hw_grade = form.save(commit=False) hw_grade.grader = request.user hw_grade.hw_upload = Hw_upload.objects.get(id=id) hw_grade.save() url = reverse('activity', kwargs={'id': id}) return HttpResponseRedirect(url) Urls.py path("auction/course/module/activity/<str:id>", views.activity, name="activity"), path("grade_hw/<int:id>", views.grade_homework, name="grade_hw"), -
How to get an access token django with linkedin api as a variable?
I have been trying to work with the linkedin API for some time now and for whatever reason I'm having some trouble with the access token. I have retrieved my access token through some youtube video where I copied and pasted a url after I logged in, but I am getting the following error when I try and use that access token. enter image description here I'm not totally sure, but I think I have to call the access token within my program and have as a variable so it doesn't expire, but I'm not sure how to fix that error. Any help would be appreciated, thanks! -
Is it possible to invoke sound from the JS file in Django's HTML template without Ajax?
I'm in the middle of migrating a site to Django framework. Almost all JS scripts works, except those related to sound. I have a play/pause button for a song and some sounds invoked when the mouse is hovering over particular buttons. For just those files I received from the console: Of course, those files are in /static/hangman_game folder. Other static files (js, css) work. Is it possible to somehow activate those functions related to playing sound/music without Ajax? Function in Django's template html is onclick="togglePlay(). Variables and functions used in JS file: var yes = new Audio("yes.wav"); var no = new Audio("no.wav"); var myAudio = new Audio('John Jacob Niles - The Maid Freed From The Gallows (1940).mp3'); function togglePlay() { if (isPlaying) { myAudio.pause() } else { myAudio.play(); } }; myAudio.onplaying = function() { isPlaying = true; }; myAudio.onpause = function() { isPlaying = false; }; function checkIt(num) { var matched = false; for (i=0; i<lengthPass; i++) { if(pass.charAt(i) == letters[num]) { //// alert(i); //Test pass1 = pass1.setCharacter(i, letters[num]); matched = true; } } if(matched == true) { yes.play(); var element = "let" + num; document.getElementById(element).style.background = "#003300"; document.getElementById(element).style.background = "#00C000"; document.getElementById(element).style.background = "3px solid #00C000"; document.getElementById(element).style.background = "default"; updatePass(); … -
Django to eval(uate) a formula and calculate the result
In my Django model I have a field with a field, which captures a reference. Through templating, I replace {{val-x}} by the respective value. To identify bigger or smaller I use if(int(x<250))*500 e.g., to have it do 1x500 in the case x is smaller than 250. In the end, I use eval to calculate the output. But I understand, this is not the best practice. I am looking for a way to store formulas and update them dynamically. How can I best go about this? E.g. for object X, I store the code "Y+Z". Y and Z values however, are time-dependent, and need to be looked up for the respective period. What would be the most appropriate approach to do such? tldr: I want my Django object to capture certain rules and refer to other object in order to calculate it's value. What is the best way to go about? -
Django application with SPA elements. How is it created?
I understand how to create full spa sites using django drf, but I often see regular sites implemented with spa elements. How are they created? What tools are used, etc. -
Django makemigrations doesn't work with UndefinedColumn error
This is what I got when I run makemigrations on python3.8 and django 3.2.12 Traceback (most recent call last): File "/home/ubuntu/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.UndefinedColumn: column "type" does not exist I even tried cleaning up my db but still got this error. I have no idea what column "type" refers to. The message doesn't even tell which table it is from. And doesn't makemigrations not do anything with the db? I tried on my other projects and not facing this issue. Know what is the cause? -
xhtml2pdf - loading static CSS files and images in Django
How do I use xhtml2pdf in Django to create a PDF document from an HTML file, using my css stylesheet and bootstrap styles? The xhtml2pdf docs describe adding stylesheets / images via a link_callback function. I tried the below: 1: I copied the "Using xhtml2pdf in Django" code from the docs into my project: https://xhtml2pdf.readthedocs.io/en/latest/usage.html#using-xhtml2pdf-in-django 2: Created an html template. In the html template, I use {% load static %} tag along with <link rel="stylesheet" href="{% static 'subs_app/css/main.min.css' %}"> I get the following error: SuspiciousFileOperation at /invoice/pdf/1 The joined path (C:\static\subs_app\css\main.min.css) is located outside of the base path component (C:\Users\office\dev\subs\subs_project\static) 3: I also tried ditching the {% load static %} method and linking to the stylesheet directly via the relative path, but this doesn't work either. -
How to add filter properties to django rest model and serializer
I have a client and broadcast model. the client model contains a tag field and operator_code field. I would like to be able to a filter property to be able to filter by tags and or operator_code when creating a new broadcast object. models.py class Broadcast(models.Model): date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) text = models.TextField(max_length=500) end_date = models.DateTimeField() def __str__(self): return self.text class Client(models.Model): phoneRegex = RegexValidator(regex='^7[0-9]{10}$') phone = models.CharField(validators=[phoneRegex], max_length=11, unique=True) tag = TaggableManager() def __str__(self): return self.phone @property def operator_code(self): return self.phone[1:4] @property def time_zone(self): ru_number = phonenumbers.parse(self.phone, 'RU') time_zone = timezone.time_zones_for_number(ru_number) return time_zone Serializers.py class ClientSerializer(TaggitSerializer, serializers.ModelSerializer): tag = TagListSerializerField() time_zone = serializers.SerializerMethodField() operator_code = serializers.SerializerMethodField() class Meta: model = Client fields = '__all__' read_only_fields = ('date_created', 'date_modified', 'operator_code', 'time_zone',) def validate(self, attrs): phone_number_exists = Client.objects.filter(phone=attrs['phone']).exists() if phone_number_exists: raise serializers.ValidationError(detail="phone number exists") if attrs['phone'][0] != '7': raise serializers.ValidationError(detail="phone number must start with 7") if len(attrs['phone']) != 11: raise serializers.ValidationError(detail="phone number must be 11 digits") return super().validate(attrs) def get_operator_code(self, obj): return obj.operator_code def get_time_zone(self, obj): return obj.time_zone class BroadcastSerializer(serializers.ModelSerializer): end_date = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S') class Meta: model = Broadcast fields = ['text', 'end_date',] read_only_fields = ('date_created', 'date_modified', 'filter_client',) -
Duplicate HTML header when using JQuery/AJAX to add new data to a table without page refresh?
I referenced this stack overflow to do away with page refreshing and use ajax/JQuery to update only the table when new data came in. However, I am getting a weird bug. My HTML header for the website is being duplicated, present once at the top of my page and again right above my table with the border extending above it, almost as if it's in the table- see the attached image of my site: A screenshot of a table-based website that has duplicate titles. I've tried moving the header up to the head part of the HTML and that changed nothing, as well as removing it entirely to no success. It's only in my HTML code once so I figure it might be something wrong with the JQuery/ajax side of things but I'm new to these so I don't know how to trouble shoot. Any help would be appreciated! Here's some of my code: ftp.html <html> <head> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'ssheet.css'%}" > <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <title>FTP Stats Table</title> </head> <body> <h2>Ftp Stats Table</h2> <form action='deletef' method='GET'> <button type='submit'>Clear table</button> </form> <table id="_appendHere2" class="tb" border="1"> <tr> <th>Src_Fname</th> <th>Dest_Fname</th> <th>Bytes_Xfer</th> <th>Xfer_Sec</th> <th>Xfer_MBPS</th> </tr> {% for ftp in … -
Change add button django admin if data filtrin
I new her and need help I create a few models: Customer Orders On Customers page I create custom buuton. After click I usef the filter to display all Orders by Customer On mane page Orders exist the standart button "add" a new Order So I try create some logic If on the page Orders used the Filter by Customer, button "Add" open form with filled field the Customer If on page Oreder not used the filter, button "Add" open form free Django 3.2.6 addons smart_selects models.py class Customer(models.Model): """docstring for Customer.""" customer_name = models.CharField(max_length=200, verbose_name='Назва юридичної особи/ФОП', help_text='Введіть поністю назву юридичної особи чи фізичної особи підприємця') customer_inn = models.CharField(max_length=15, verbose_name='ЄДРПОУ', help_text='Введеіть ЄДРПОУ для юридичної особи чи ідентифікаційний код для ФОП') customer_adress = models.TextField(max_length=200, verbose_name='Юридична адреса клієнта' , help_text='Притриймуйтесь формату аналогічно витягу ЄДР. Наприклад: 79000, Область, Район, Місто/Селище, вулиця/проспект Назва вулиці, Номебр будинку, квартира') customer_ceo = models.CharField(max_length=50, verbose_name='Керівник/підписант') class Meta: verbose_name = 'Клієнт' verbose_name_plural = 'Клієнти' def __str__(self): """ String for representing the Model object. """ return self.customer_name class Order(models.Model): order_customer = models.ForeignKey('Customer', on_delete=models.CASCADE, verbose_name="Клієнт") order_date = models.DateField(verbose_name='Дата заявки') order_adress = ChainedForeignKey( 'MarketAdress', chained_field = "order_customer", chained_model_field= "customermarkeradress", show_all = False, auto_choose = True, sort = True, verbose_name= 'Адреса точки') … -
Is there a if __name__ == "main" equivalent for django framework?
I would like django to run a specific script from custom package right after manage.py runserver command finishes. Is this possible with some simple configuration? -
Is there a way to share a common table of database between two django projects without faking it?
I am trying to use a same table across two different projects and want to reflect the changes between them. Let's assume that there is a student table in the data created by PROJECT1-APP1 of django. I want that same student table to use in PROJECT2-APP1. I have searched the interned and get recommendation to import the model from 1 project to other but according to my understanding it is just "faking" it and some functionality like BigAutoFeild and Foreign Keys would not work in this solution. Is there a way that I can use the same database in two different projects which will not mess up with the core operation? -
AttributeError: 'str' object has no attribute 'strftime' in django
I am trying to convert the date string into a specific date format but have an issue with it. date = "2022-06-20T10:17:28-05:00" # getting date from DB original_date = date.strptime('%m/%d/%Y %H:%M:%S') Having error AttributeError: 'str' object has no attribute 'strptime' -
Migrate / MakeMigrations conundrum
I have a wagtail app that deployed to docker, but then I get a very strange error, below are the steps: Step 1: docker-compose run app /venv/bin/python manage.py makemigrations` Migrations for 'locations': bakerydemo/locations/migrations/0008_alter_locationoperatinghours_day.py - Alter field day on locationoperatinghours` Step 2: docker-compose run app /venv/bin/python manage.py migrate locations Operations to perform: Apply all migrations: locations Running migrations: ===> No migrations to apply. <=== HUH? Your models in app(s): 'locations' have changes that are not yet reflected in a migration, and so won't be applied. ===> Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. <=== DOUBLE HUH? Any wagtail or django or docker afficianados that can tell me what might be going on here? A similar question regarding Heroku mentioned running running the migrations before Heroku-izing, that is something I tried here, but it created an error in my locations app after dockerizing the container. The solution is from https://github.com/wagtail/bakerydemo and I added a few customizations to the locations app. -
How to set-up Memcached for Django?
I am trying to set-up Memcached solution, but it does not seem to work. I tested caching a view only and whole solution with the same result. Here are my settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # CORS 'corsheaders.middleware.CorsMiddleware', # adding caches around CommonMiddleware 'django.middleware.cache.UpdateCacheMiddleware', # NEW 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', # NEW 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', } } # cache settings CACHE_MIDDLEWARE_ALIAS = 'default' CACHE_MIDDLEWARE_SECONDS = '6000' CACHE_MIDDLEWARE_KEY_PREFIX = '' I have installed memcached with Homebrew and is properly running. I have tested it using telnet. I am trying a call that returns a few thousand results, and I see no time gains for the 2nd call and on. Any help on how to figure this out would be greatly appreciated! -
Django production (using gunicorn) - internal server error (no request) until 10-20 requests have been made
I have a production system that has been running for 2+ years now, regularly (daily/weekly) updates. Around 2 months ago, a strange behaviour occurs every time I restart Gunicorn, for the first 10-20 requests made to the web server, I get an internal server error. The errors (when the system is switched to debug=True) all relate the the request being None. The login (allauth) page works a treat, but once I have entered my account details (or any other) - I get internal server error on the following URL. If I reload, it loads AOK. If I browse the site, I get a mixture (semi random) of pages that either load or internal server error. After around 10-20 page load attempts - every thing starts working 100% AOK. No issues. I can then log in as any account, every page works. The above issues on restarting the web server also occurs with any other account login. Its as if there is something that is failing in the middleware or some sort of internal time out before the request details can be stored. But, the database server is fully up and running, no load issues at all. Any thoughts on the … -
Django-Next.js Image Upload Error with Empty Body
Users in my application may alter their profile image, however when I send a request to the backend server, it returns an empty body. Frontend const handleImageChange = useCallback(async (e) => { const confirmation = confirm('Press ok to update profile') if (confirmation) { const form = new FormData() form.append('userProfileImage', e.target.files[0]) const location = process.env.NEXT_PUBLIC_API_URL + `/user/update/profile` const api = await fetch(location, { method: 'Patch', headers: { 'Accept': 'application/json', 'Content-type': 'multipart/form-data; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW', }, body: form } ) } }, []) Backend Code class profileImageUpdateView(UpdateAPIView): serializer_class = userProfileImageSerializer http_method_names = ['patch'] def get_object(self): user = self.request.user instance = userProfile.objects.get(user = user) return instance def patch(self, request, *args, **kwargs): print(request.data) return super().patch(request, *args, **kwargs) -
Display filefield object in django templates
models.py enter image description here views.py enter image description here summary_pdf.html enter image description here The problem: enter image description here Can someone help me? I've been stuck in this since morning and haven't found a solution. -
How to avoid recalculation when sorting by a model's property in Django Rest Framework?
I have a simple social media app, with User, Post, and PostVote models. class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) ... @property def score(self): total = 0 for vote in PostVote.objects.all(): if vote.post == self: total += vote.vote return total def get_num_upvotes(self): return PostVote.objects.filter(post=self, vote=1).count() def get_num_downvotes(self): return PostVote.objects.filter(post=self, vote=-1).count() class PostVote(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) post = models.ForeignKey(Post, on_delete=models.SET_NULL, null=True) vote = models.IntegerField() In my views.py, I attempt to calculate the 'top' posts, sorted by score. Here's the view code. class ListCreatePostAPIView(ListCreateAPIView): serializer_class = PostSerializer permission_classes = (IsGoodUser | IsAdminUser,) def get_queryset(self): try: queryset = Post.objects.all().exclude(user=None) queryset = list(queryset) queryset.sort(key=operator.attrgetter("score"), reverse=True) return queryset except: return Post.objects.none() In serializers, I also once again recalculate and return the score, as I'd like to pass it to my front-end. class PostSerializer(serializers.ModelSerializer): score = serializers.SerializerMethodField() num_upvotes = serializers.SerializerMethodField() num_downvotes = serializers.SerializerMethodField() def get_score(self, obj): return obj.get_score() def get_num_upvotes(self, obj): return obj.get_num_upvotes() def get_num_downvotes(self, obj): return obj.get_num_downvotes() class Meta: model = Post fields = ( "score", "num_upvotes", "num_downvotes", ) I know I'm re-calculating the score way too many times, as it's taking 3-4 seconds to return just 50 fake posts / 1250 fake … -
Django migrate primary key from UUID to Slug
I have model AAA with UUID as primary key. Many models have relation to this model. Now I want to migrate them to use Slug as this primary key, to keep slug value in database as a reference. What will be the correct way to do that? from django.db import models from django_extensions.db.fields import AutoSlugField from model_utils.models import UUIDModel # Django models example class AAA(models.Model): id = UUIDField(primary_key=False, version=4, editable=False) title = models.CharField(max_length=255, unique=True) slug = AutoSlugField(populate_from='title', primary_key=False) class BBB(models.Model): aaa = models.ForeignKey(AAA, on_delete=models.CASCADE) # ... other fields here ...