Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implementing configurable feature-based roles and permissions in django rest framework
I have a scenerio where I am creating custom roles and assigning permissions to them for each fetaure. The process is fully customized and generic and it works for CRUD operations(like create user, read user, update user and delete user) perfectly. Now there is a little change in requirements where I have multiple operations for one feature like create order, accept order, split order, refer order. Now I want to create a roles and permissions so that it covers this part of my problem as well. Inititally I had four models i.e. Role, Permission, Feature, RoleFeatureAssociation(fields: role, feature, list(permissions)). I was checking permissions upon each request and if the particular user had that particular permission available for that feature then request was processed. Keeping this procedure in view as well how should I manage new requirements since I have multiple operations for feature instead of just create, read, update and delete. -
How can I make the user click on a button in a Django .html to modify one of the database values?
I have these two buttons found in my Django .html: <div class="d-flex justify-content-center" style="margin: 1em;"> <button type="button" class="btn btn-success btn-lg mx-2" style="width: 150px;">Accept</button> <button type="button" class="btn btn-danger btn-lg mx-2" style="width: 150px;">Reject</button> </div> What I need, is that when the user clicks on the button, that it changes a value, in this case of an invoice of my database. That is to say, now the invoice is in factura.id_estado=1; so, if the user clicks on Accept, factura.id_estado must change to 2 (factura.id_estado=2). The same happens when the user clicks on Reject, factura.id_estado will change to 3 (factura.id_estado=3). I don't know if it is necessary or not, but my database is the Django database which is hosted in my Docker. -
Can't apply migrations in Django project
I'm creatig a custom user model, inherit it from AbstractUser. When i'm making migrations i got ValueError('Related model %r cannot be resolved' % self.remote_field.model) ValueError: Related model 'reviews.user' cannot be resolved from django.contrib.auth.models import AbstractUser from django.db import models # Пользовательские роли. ROLES = [ ('user', 'Пользователь'), ('moderator', 'Модератор'), ('admin', 'Администратор'), ] class User(AbstractUser): username = models.CharField( max_length=150, unique=True, ) email = models.EmailField( max_length=254, unique=True, blank=False, ) first_name = models.CharField( max_length=150, null=True, blank=True, ) last_name = models.CharField( max_length=150, null=True, blank=True, ) bio = models.TextField( verbose_name='Биография', blank=True, null=True, ) role = models.CharField( max_length=256, verbose_name='Роль', choices=ROLES, default='user', ) class Meta: verbose_name = 'Пользователь', verbose_name_plural = 'Пользователи' def __str__(self): return self.username class Title(models.Model): name = models.CharField( 'Название', max_length=256, ) year = models.IntegerField('Год выпуска') description = models.TextField('Описание') class Meta: verbose_name = 'объект "Произведение"' verbose_name_plural = 'Произведения' def __str__(self): return self.name I can't understand what is wrong. -
Getting a ValueError when trying to alter a Django model field related to a ManyToManyField
I'm encountering an issue while trying to make alterations to a Django model field in my project. Specifically, I'm attempting to modify the 'likes' field in the 'Tweet' model. However, I'm receiving the following error: "ValueError: Cannot alter field tweets.Tweet.likes into tweets.Tweet.likes - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields)" Here are the relevant parts of my code: import random from django.conf import settings from django.db import models User = settings.AUTH_USER_MODEL class TweetLike(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) tweet = models.ForeignKey("Tweet", on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) class Tweet(models.Model): # id = models.AutoField(primary_key=True) parent = models.ForeignKey("self", null=True, on_delete=models.SET_NULL) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="tweets") likes = models.ManyToManyField(User, related_name='tweet_user', blank=True, through=TweetLike) content = models.TextField(blank=True, null=True) image = models.FileField(upload_to='images/', blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-id'] I'm not quite sure how to proceed and would appreciate any guidance on how to resolve this error. Thank you for your help! I attempted to modify the 'likes' field directly in the model, but it resulted in the error mentioned above. -
Strategy for syncing a SQL database with a spreadsheet?
This is more of a general design pattern and UX question than a technical one. I am working on a SQL database which contains product inventory (using Django). Currently, this inventory is managed by another (non-technical) employee via a spreadsheet which contains all inventory information and is updated daily. In order to support this employee's workflow, I would like to have the option of uploading the spreadsheet to the server, have it processed, and reflect the changes in the inventory (SQL database). Here's the catch: The SQL database can also be updated by customers via our API. When a user purchases an item, it is removed from the inventory, meaning that our employee's spreadsheet becomes out of sync. Furthermore, if users are modifying the database and the employee does not have the most up-to-date version, when the employee goes to upload their spreadsheet, the changes made by users would be overridden. Here are options I am considering: Require our employee to adopt a custom interface to manage inventory and ditch the spreadsheet. I am hesitant on this option because I want to support their existing workflow. Use an API like on Google Drive to update the spreadsheet programmatically whenever the … -
Should I use `cache.close()` after I finish using cache in Django Views?
I found cache.close() saying below in the doc. *I'm learning Django Cache: You can close the connection to your cache with close() if implemented by the cache backend. So, I use cache.close() after I finish using cache in Django Views as shown below: # "views.py" from django.core.cache import cache def test(request): cache.set("name", "John") cache.set("age", 36) print(cache.get("first_name")) # John print(cache.get("age")) # 36 cache.close() # Here return HttpResponse("Test") My questions: Should I use cache.close() after I finish using cache in Django Views? If I don't use cache.close() after I finish using cache in Django Views, are there anything bad? -
django - Optimize request with indirect relation without any foreign keys
I have 2 models and a view which must join them on matching common_field and then perform some aggregation. The problem is for a given N=5000 rows a request is processed ~30 seconds. Here are myapp/models.py: from django.db import models class MainModel(models.Model): common_field = models.CharField(max_length=20) category = models.IntegerField() # some other fields not relevant for the example class AuxiliaryModel(models.Model): common_field = models.CharField(max_length=21) the_date = models.DateField() myapp/serializers.py: from rest_framework import serializers class MainCategoryAgingSerializer(serializers.Serializer): category = serializers.IntegerField() age_0_99 = serializers.IntegerField() age_100_199 = serializers.IntegerField() age_200_299 = serializers.IntegerField() age_300_399 = serializers.IntegerField() age_400_plus = serializers.IntegerField() myapp/views.py: import datetime from django.db import models from django.db.models import Case, Count, F, OuterRef, Subquery, Value, When from django.db.models.functions import ExtractDay from rest_framework import generics from django_custom_join.myapp.models import AuxiliaryModel, MainModel from django_custom_join.myapp.serializers import MainCategoryAgingSerializer class MainCategoryAgingListAPIView(generics.ListAPIView): serializer_class = MainCategoryAgingSerializer def get_queryset(self): return ( MainModel.objects .annotate( the_date=Subquery( AuxiliaryModel.objects.filter( common_field=OuterRef("common_field"), ) .values("the_date"), ), curr_age=ExtractDay(Value(datetime.date.today()) - F("the_date")), ) .values("category") .order_by("category") .annotate( age_0_99=Count( Case( When(curr_age__range=[0, 99], then=1), output_field=models.IntegerField(), ), ), age_100_199=Count( Case( When(curr_age__range=[100, 199], then=1), output_field=models.IntegerField(), ), ), age_200_299=Count( Case( When(curr_age__range=[200, 299], then=1), output_field=models.IntegerField(), ), ), age_300_399=Count( Case( When(curr_age__range=[300, 399], then=1), output_field=models.IntegerField(), ), ), age_400_plus=Count( Case( When(curr_age__gte=400, then=1), output_field=models.IntegerField(), ), ), ) ) myapp/urls.py: from django.urls import path from django_custom_join.myapp.views import MainCategoryAgingListAPIView urlpatterns = … -
ImportError: cannot import name 'urlquote' from 'django.utils.http'
How to solve this problem.I've tried to import like that from urllib.parse import quote django.utils.http.urlquote = quote.But it's not effective.Please let me know if you can solve this problem. Please let me know if you can solve this problem. -
Dokku: how to change heroku stack to heroku-20 or heroku-22 (from heroku-18)
I have been working on a Django (Python) project using Dokku (thus Heroku) for deployments. Up until today, all deployments worked just fine, but since this morning, I get this error message: Requested runtime 'python-3.10.12' is not available for this stack (heroku-18). I know that python-3.10.12 is available on heroku-18 so I assume I (finally) have to change stack since heroku-18 is deprecated. I have tried using this command on Dokku: dokku buildpacks:add --index 1 {APP-NAME} https://github.com/heroku/heroku-buildpack-python.git, but it doesn't solve my problem (heroku-18 is still being used). Any help would be greatly appreciated -
Need Clarification on Correctly Saving Uploaded File Data to Default Storage using Django-minio-storage?
I've received a response that has been helpful so far, and everything has been functioning as expected. However, I've encountered some confusion when attempting to save uploaded file data to the default storage. In my current implementation, I have a method named _save_uploaded_file_data, which ideally should handle the task of saving uploaded file data to the default storage. This comes after successfully uploading the file to MinIO using a presigned URL. Here's the relevant excerpt of my code: Although my code appears straightforward, I'm uncertain about the accuracy of my approach, particularly when it comes to saving the uploaded file data to the default storage, which could potentially be local storage. I would greatly appreciate guidance, insights, or suggestions on the proper way to handle this situation. If you could provide any tips, relevant code snippets, or best practices related to this scenario, it would be immensely helpful. Thank you. models.py class FileModel(models.Model): uploaded_file = models.FileField(upload_to='uploads) minio.py class MinioUploader: def __init__(self, file): self.client = default_storage.client self.bucket_name = settings.MINIO_STORAGE_MEDIA_BUCKET_NAME self.file = file self.put_presigned_url = self._get_put_presigned_url() def _get_put_presigned_url(self): return self.client.presigned_put_object( self.bucket_name, self.tus_file.filename, expires=timedelta(minutes=2), ) def upload_file(self, file_path): file_data = self._read_file_data(file_path) response = self._upload_to_presigned_url(file_data) if response.status_code == 200: self._save_uploaded_file_data(file_data) return response def _read_file_data(self, … -
Annotate using primary key in Django
Consider a model with some stuff and a method property: class MyModel(models.model): blah blah @property def func(self): blah blah Suppose now I want to annotate MyModel objects with the value of the function: MyModel.objects.annotate(func_value=MyModel.objects.get(pk=Subquery(OuterRef('pk'))).func) but this throws the following error: OuterRef object has no attribute 'clone'. How do I properly annotate the function values to the query set? -
Conflict when using django-simple-history with django-computedfields libraries together
In my django app I have a model with some computed fields, i have used django-computedfields to achive that. Now i am trying to add django-simple-history to my model, but aparently there is a conflict when using these two django libraries. When making migrations I am getting the following error. computedfields.resolver.ResolverException: <class 'arbolsaf.models.HistoricalSpeciesModel'> is not a subclass of ComputedFieldsModel This is my code (I am not showing all fields in the model): from computedfields.models import ComputedFieldsModel, computed, compute from simple_history.models import HistoricalRecords class SpeciesModel(BasicAuditModel, ComputedFieldsModel): history = HistoricalRecords() VALUES_CHOICES = ( ("ninguno", "Ninguno"), ("bajo", "Bajo"), ("medio", "Medio"), ("alto", "Alto"), ) cod_esp = models.CharField(_("Código especie"), max_length=50, unique=True) taxonid_wfo = models.CharField(_("Taxon ID WFO"), max_length=50) nombre_comun = models.CharField(_("Nombre común"), max_length=255) nombre_cientifico = models.CharField(_("Nombre científico"), max_length=255) nombre_cientifico_completo = models.CharField(_("Nombre científico completo"), max_length=255) familia = models.ForeignKey("arbolsaf.FamilyModel", verbose_name=_("Familia"), on_delete=models.RESTRICT) genero = models.ForeignKey("arbolsaf.GenderModel", verbose_name=_("Género"), on_delete=models.RESTRICT) epiteto = models.CharField(_("Epíteto"), max_length=50) variedad_subespecie = models.CharField(_("Variedad/Subespecie"), max_length=50, blank=True, null=True) autor = models.CharField(_("Autor"), max_length=255, blank=True, null=True) nativa = models.BooleanField(_("Nativa?")) class Meta: db_table = 'arbolsaf_species' managed = True ordering = ["nombre_cientifico"] verbose_name = 'Especie' verbose_name_plural = 'Especies' -
Djago - Access related_name in queryset using as_manager
I am having some difficulty figuring out how to use foreign key (related_name) in a queryset using as_manager() Below is the mode and queryset. Everything works except the `get_powerbars()' method. I cannot seem to find any information about how to access the reverse foreign key lookup. Anything I try gets me the error (or similar) 'PowerbarQuerySet' object has no attribute 'outlet' What am I missing? If 'related_name' is not available in a queryset, how would one go about returning all the powerbars and their outlets in a simple fashion. import logging from django.db import models logger = logging.getLogger(__name__) class PowerbarQuerySet(models.QuerySet): """Additional queryset functions""" def get_powerbar_ips(self): try: all_bars = ( self.all().values_list("ip", flat=True).order_by("ip") ) return list(all_bars) except self.model.DoesNotExist: return None def get_powerbars(self): try: all_outlets = ( self.all().outlet ) return all_outlets except self.model.DoesNotExist: return None class Powerbar(models.Model): objects = PowerbarQuerySet.as_manager() name = models.CharField(max_length=200) building = models.CharField(max_length=200) group = models.CharField(max_length=200) ip = models.GenericIPAddressField() def __unicode__(self): return f'{self.name} @ {self.ip}' def __str__(self): return f'{self.name}' class Meta: base_manager_name = 'objects' class PowerbarOutlet(models.Model): powerbar = models.ForeignKey(Powerbar, on_delete=models.CASCADE, related_name='outlet') number = models.PositiveIntegerField() label = models.TextField(blank=True, default="") class Meta: unique_together = ("powerbar", "number") ordering = ("powerbar", "number") def __unicode__(self): return f'{self.number} @ {self.powerbar}' def __str__(self): return f'{self.powerbar}' I have … -
HTMX / Django List Of Forms - CSRF Token Issue?
I've got an application where I'm listing out a bunch of forms - it loads a csrf_token into each form. Each form is a simple dropdown for choosing a 'color' for each item in the list. I have a ListView that returns a list of placement objects like so: {% for placement in placements %} {% include 'placements/snippets/placement_update_form.html' %} {% endfor %} The placement_update_form.html looks like this: <form id="placementUpdateForm" action="{{ placement.get_update_url }}" method="post" hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'> <input type="hidden" name="id" value="{{ placement.id }}"> <label for="color">Color</label> <select name="color" id="color{{ placement.pk }}" class="form-select" hx-post="{% url 'placements:placement-update' placement.pk %}" hx-target="closest #placementUpdateForm"> <option value="" {% if not placement.color %}selected{% endif %}>Default</option> {% for value, display_name in placement_colors %} <option value="{{ value }}" {% if value == placement.color %}selected{% endif %}>{{ display_name }}</option> {% endfor %} </select> </form> I am using HTMX to POST the data to an UpdateView on my backend; which redirects to a success_url that is a DetailView that simply returns the placement_update_template and replaces that exact item in the DOM. It works - once. The first POST works and saves the color as expected. The template is replaced in the DOM, but if you choose a different color (triggering a second … -
instead of the username django value, I get "<django.db.models.query_utils.DeferredAttribute object at 0x0000017E365030D0>" (i see in SQLiteStudio)
I wanted to create a user without entering username and password, but only first_name, last_name and phone_number and so that username when creating a user was equal to phone_number models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): image = models.ImageField(upload_to='images/', null=True, blank=True) phone_number = models.CharField(max_length=11, help_text="Введите номер телефона пользователя", verbose_name="Номер телефона") class Meta(AbstractUser.Meta): pass def save(self, *args, **kwargs): self.username = User.phone_number super().save(*args, **kwargs) def __str__(self): return self.last_name forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from users.models import User class UploadImageForm(forms.ModelForm): class Meta: model = User fields = ['image'] class UserCreateForm(UserCreationForm): username = forms.CharField(label='username', max_length=100) phone_number = forms.CharField(label='phone_number', max_length=11) class Meta(UserCreationForm.Meta): model = User fields = ('username', 'phone_number') def save(self, *args, **kwargs): self.username = self.phone_number super().save(*args, **kwargs) admin.py from django.contrib import admin from django.contrib.admin import ModelAdmin from django.contrib.auth.admin import UserAdmin from django.utils.translation import gettext_lazy as _ from .forms import UserCreateForm from .models import * @admin.register(User) class CustomUserAdmin(ModelAdmin): add_form = UserCreateForm list_display = ('last_name', 'phone_number', 'is_staff') list_display_links = ('last_name', 'phone_number') search_fields = ('last_name', 'phone_number') ordering = ['last_name'] add_fieldsets = ( ( None, { "classes": ("wide",), "fields": ("username", 'phone_number'), }, ), ) fieldsets = ( (_("Personal info"), {"fields": ("first_name", "last_name", "phone_number", 'image')}), ( _("Permissions"), { "fields": ( "is_active", … -
Django:- Identification and Access Control
I'm working in an intelligence agency. Each and every agent of that agency has to provide their generated number on a certain page before they can access some pages. In our CustomUser model, we have a field that asks the user for their full name. We want the name to appear in the 'name' field of the Access model in real-time. What we want is that when someone types their number in the Access model, their full name in the CustomUser model should appear in the 'name' field of the Access model in real-time. My signals: @receiver(post_save, sender=User) def generate_number(sender, instance, created, **kwargs): if created: random_number = ''.join(random.choices(string.digits, k=10) Account.objects.create(user=instance, secret_number=random_number) My models: class Account(models.Model): user = models.ForeinKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) secret_number = models.IntegerField() Class Access(models.Model): user = models.ForeinKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) account_number = models.IntegerField() name = models.CharField(max_length=50) Note: We don't want to use the current user, which means that we want to allow someone on the platform to use another agent number to log in. I don't know if this is possible in django, that's why I'm asking this question. Thanks. -
Django allauth login isnt working. It was working but I am getting a ratelimit issue
Here is the login view def login(request): if request.method == 'POST': try: form = UserLoginForm(request.POST) if form.is_valid(): print('form is valid') email = form.cleaned_data.get('login') password = form.cleaned_data.get('password') try: user = authenticate(request, username=email, password=password) except Exception as e: print(str(e)) messages.success(request,str(e)) if user: #auth_login(request, user) messages.success(request, 'Sign in successful!') print('Login successful') return redirect('/dashboard') else: print(form.errors) print() except Exception as e: print(str(e)) else: form = UserLoginForm() return render(request, 'account/login.html', {'form': form}) When trying to login, I am getting File "\lib\site-packages\allauth\ratelimit.py", line 58, in consume if request.method == "GET" or not amount or not duration: AttributeError: 'NoneType' object has no attribute 'method Is this a known issue ? Please help -
Change Django to use EmailMultiAlternatives instead of send_mail() by default (all-auth)
So I am using django-all-auth for my authentication and using its in-built functionality for mailing reset passwords, confirmations of registration, etc. I have designed templates that include images. For the regular emails, I am explicitly using functions that use EmailMultiAlternatives instead of send_mail() since that allows inline images and background images. Django-all-auth however automatically uses send_mail() and my emails are arriving with the images missing. How can I override it so it uses EmailMultiAlternatives? -
Collapsed field in Django Admin's change view
The table Content has a field compressed_string that stores a very long string in the compressed form. This is what I have to display the original decompressed string in the Django Admin's change view: class ContentAdmin(admin.ModelAdmin): fields = ( [f.name for f in Content._meta.fields if f.name not in ['compressed_string']] + ['original_string']) readonly_fields = ['original_string'] list_display = [f.name for f in Content._meta.fields] def original_string(self, obj): return pickle.loads(brotli.decompress(obj.compressed_string)) I would like original_string to be displayed collapsed, with the possibility to expand and view the whole string. How can I accomplish this? -
I am getting "NoReverseMatch" error for my 'results' page
I am creating a quiz website. After the user answers all the questions he is redirected to the results page. But if he clicks the back button in Chrome he goes back to the questions in the quiz. But since the quiz is submitted i don't want him to go there. Instead It should redirect him into the home page where a list of all quizzes is available. So in the templates of the results page I included the following JavaScript code. <script> window.onload = function() { // Check if the referring URL matches the results page URL console.log('Referrer:', document.referrer); var expectedReferringURL = '{% url "quizquestions" %}'; // Check if the referring URL contains the expected URL pattern name if (document.referrer.includes(expectedReferringURL)) { // Replace the current history entry with the home page URL window.history.replaceState(null, null, '{% url "quizlist" %}'); } }; </script> The url pattern of the name "quizquestions" is path('quizzes/<int:quiz_id>/question/<int:question_id>',user_views.quizquestions,name='quizquestions') But when I go to the results page it shows this error Reverse for 'quizquestions' with no arguments not found. 1 pattern(s) tried: ['quizzes/(?P<quiz_id>[0-9]+)/question/(?P<question_id>[0-9]+)\\Z'] Any thoughts on why is this happening? -
Update Django via settings to new domain
I'm new to Django and nginx. I have built a default Django app and my setup uses a nginx server as a reverse proxy. My application was previously reached via https://myapplication.intranet and every internal link referred to this link (e.g. href "/" points to "https://myapplication.intranet/" and href points to "/test" "https://myapplication.intranet/test") - so everything worked. Now nginx changed the domain link to "https://myapplication.intranet/new/", and everything broke: redirect (e.g. in view.py) href (in html templates. For example href "/test" incorrectly points to "https://myapplication.intranet/test" instead of "https://myapplication.intranet/new/test") css sheets not found My question is the following: What adjustments have to be made (for Django) in order to make the application work again? Is there an easier (and more general) way than rewriting all links in all files to make the urls specific? Thank you very much. -
Invoke Django reload manually
I would like to force a reload of Django similar to when Django reloads after a file has changed. e.g. Watching for file changes with StatReloader This answer has the desired result but it involves a reload on "file changing": https://stackoverflow.com/a/43593959/12446456 However, I would specifically like to invoke the reload behaviour manually after a get request has been handled by Django. -
Basic Django image runs locally but fail inside Kubernetes?
I created a bare minimal Django project using django-admin startproject I then dockerized it using the following Dockerfile FROM python:3 ENV PYTHONUNBUFFRED=1 COPY . . RUN pip install -r requirements.txt EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] I built and pushed the image to ACR. I am able to run it locally using docker run -p 8000:8000 <image_name> and I am able access the site at localhost:8000. However, when I try to deploy it inside a Kubernetes deployment with the following yml file, it just crashed and restart over and over. apiVersion: apps/v1 kind: Deployment metadata: name: demodjango-deployment labels: app: demodjango spec: replicas: 1 selector: matchLabels: app: demodjango template: metadata: labels: app: demodjango spec: containers: - name: demodjango image: djangonba.azurecr.io/demodjango:latest imagePullPolicy: "Always" ports: - containerPort: 8000 --- apiVersion: v1 kind: Service metadata: name: demodjango-service spec: type: LoadBalancer selector: app: demodjango ports: - protocol: TCP port: 8000 targetPort: 8000 I am unable to access the page through the external IP address of the service demodjango-service either even at time where it somehow didn't crash. I already made the following modification ALLOWED_HOSTS = ['*'] I believe there is something fundamentally wrong with my approach? Can anyone tell me theoretically why it works … -
How can i raise a message error when introducing the same company and username
Hi guys I'm creating a django form I'm introducing companies and users to create a license, I would like that you cannot register the same user with the same company class UserForm(forms.Form): """User form model.""" company = forms.ModelChoiceField( queryset=models.CompanyInfo.objects.all(), empty_label=None, error_messages={"required": "Please enter customer company."}, ) user_name = forms.CharField( error_messages={"required": "Please enter username."}, empty_label=None, ) full_name = forms.CharField( error_messages={"required": "Please enter customer full name."} ) email = forms.EmailField(required=True) I would like to create the validaton here, I've been trying to use "unique" direct to de field in the form but i noticed i cannot use it, how can i create that kind of validation directly in the form? -
How to solve django.db.utils.OperationalError: (1060, "Duplicate column name 'country_id'")
I was trying to delete some of the fields of my model and I tried to migrate them, but I got the error: Operations to perform: Apply all migrations: admin, auth, contenttypes, leads, order, sessions Running migrations: Applying leads.0023_auto_20230823_0043...Traceback (most recent call last): File "/web/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/web/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 74, in execute return self.cursor.execute(query, args) File "/web/.local/lib/python3.6/site-packages/pymysql/cursors.py", line 148, in execute result = self._query(query) File "/web/.local/lib/python3.6/site-packages/pymysql/cursors.py", line 310, in _query conn.query(q) File "/web/.local/lib/python3.6/site-packages/pymysql/connections.py", line 548, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/web/.local/lib/python3.6/site-packages/pymysql/connections.py", line 775, in _read_query_result result.read() File "/web/.local/lib/python3.6/site-packages/pymysql/connections.py", line 1156, in read first_packet = self.connection._read_packet() File "/web/.local/lib/python3.6/site-packages/pymysql/connections.py", line 725, in _read_packet packet.raise_for_error() File "/web/.local/lib/python3.6/site-packages/pymysql/protocol.py", line 221, in raise_for_error err.raise_mysql_exception(self._data) File "/web/.local/lib/python3.6/site-packages/pymysql/err.py", line 143, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.OperationalError: (1060, "Duplicate column name 'country_id'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/web/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/web/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/web/.local/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/web/.local/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/web/.local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res …