Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Email adress on Django API returns 404
I have an endpoint created like this: class OTPSViewSet(viewsets.ViewSet, mixins.RetrieveModelMixin, mixins.CreateModelMixin): """ A simple ViewSet for listing or retrieving users. """ throttle_classes = [OncePerDayUserThrottle] authentication_classes = [] permission_classes = [] def retrieve(self, request, pk=None): response = self.get_otp(pk) return response def create(self, request): serializer = OtpsForms(data=request.data) if serializer.is_valid(): response = self.verify_otp(request) return response else: return response_error(serializer.errors) def get_otp(self, username): """Send OTP by email Args: username (string): username """ username = username.strip().lower() user = _get_all_by_username(username) ... What happens is that when I make a call to the endpoint with a "username" such as "javi", the call "GET /api/otps/javi/ HTTP/1.1" 200" returns a 200, and when the username is an email like "javi@gmail.com" the call is "GET /api/otps/javi@gmail.com/ HTTP/1.1" 404" returning a 404 not found status. I think it has to do with having an at (@) or a dot (.) inside the url but I don't know how to fix it. Thanks in advance! -
Argument of type "dict[str, str]" cannot be assigned to parameter "data" of type "Type[empty]"
I have a very small serializer for the initial user registration: class UserRegistrationSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ "email", "password", ] def validate_password(self, value): try: validate_password(password=value) except ValidationError as e: raise serializers.ValidationError(list(e.messages)) return value Now I am writing tests for this serializer. These are working fine, but my IDE (vscode) shows me an typing error: class UserRegistrationSerializerTestCase(TestCase): def test_invalid_email(self): request_data = {"email": "test@test", "password": "testpwsecure"} serializer = UserRegistrationSerializer(data=request_data) self.assertFalse(serializer.is_valid()) The error refers to my input to the UserRegistrationSerializer, saying that Argument of type "dict[str, str]" cannot be assigned to parameter "data" of type "Type[empty]" I am not sure what Type[empty] actually means and how I can satisfy the static code analysis here ... the test is working fine and as expected, I would just like to understand and learn what the IDE is complaining about. -
How to update field after creation wih Signals
I'm using signals and i want to update one of fields after creation but every time i've got an error maximum recursion depth exceeded How can i solve that? signals.py @receiver(post_save, sender=CompanyUserPhysicalCard) def create_company_card(sender, instance, created, **kwargs): try: company_card_model = CompanyUserPhysicalCard.objects.get( card__user__individual_user=instance.card.user.individual_user) letters = '01234567890' result_str = ''.join(random.choice(letters) for i in range(9)) card_company_name = company_card_model.company.company_name card_company_abbreviation = company_card_model.company.company_abbreviation if len(card_company_name) < 15: result_str += '-' + str(card_company_name) else: result_str += '-' + str(card_company_abbreviation) company_card_model.custom_id = result_str instance.custom_id = company_card_model.custom_id except CompanyUserPhysicalCard.DoesNotExist as e: print(e) @receiver(post_save, sender=CompanyUserPhysicalCard) def save_user_profile(sender, instance, **kwargs): instance.save() -
django refreshed token after patch doesn't contain latest data
I'm executing a patch method, after which I want to refresh the token to update my userdata through the app (I don't know if this is the right way but refresh tokens are linked to my user in the app so it's convenient). The problem is, after having executed a patch method (successfully, because I see that data changed in my db), when I try to refresh the token it simply returns the old data. I added a custom TokenObtainPairSerializer class to have my data in the token but is there something else I need to do? Please tell me if there is a specific piece of code I should add to this post. -
Best solution to integrate independent applications into a Django (& React) platform?
I have a general platform that I want to evolve. The platform is hosted on a domain like "https://www.example.com". For certain specific users, I would like to give them access to a completely independent application (several applications, independent platform) from their profile on a subdomain like "https://subdomain.example.com". I would like these applications to have: Their own database Be accessible only for authenticated and authorized users Their own server The Django project of the general platform is written in Django/React. Before launching this project, I am wondering about the best way to integrate these independent applications into the main platform. I have done some research and manipulation, but I don't know how to decide on the project architecture: django-host, django-tenant, django-site ... Below is my current architecture What is the best possible option to connect other independent applications to the general platform with the current users? -
Django ignores timezone settings
I am trying to create a record in my Django project with the timezone set to Europe/Rome. When I create the model object, I use this function to set the timezone: MyModel.objects.create( name="trial", date=datetime_aware("2023-08-15") ) However, I am encountering an issue where the record is being stored with the date "2023-08-14" and the UTC timezone (GMT), despite my efforts to set it to Europe/Rome. In order to do this, I first set the following values in my settings.py file: USE_TZ = True TIME_ZONE = "Europe/Rome" Next, I wrote a function to create a datetime object with the appropriate timezone: def datetime_aware(dt_string, timezone=settings.TIME_ZONE): if dt_string: dt = datetime.datetime.strptime(dt_string, "%Y-%m-%d") dt_aware = make_aware(dt, pytz.timezone(timezone)) return dt_aware return None Can you help me figure out what's going wrong? -
How to make the updated_by field display the user's full name in Django?
I just recently started using Django. Please help me figure it out. I have a database that stores various information about network devices. On the site, this information is displayed in a table. I want the updated_by field to display the full name of the user who created this table or who last modified it. All users are registered in Django, there are fields: first name, last name. I want these two fields to be displayed together in the table in the updated_by field. For example, at the end of the table on the site it was written: Updated by an employee: Ivanov Ivan. I tried to do this: from django.contrib.auth.models import User updated_by = models.ForeignKey(User, verbose_name='Updated by an employee', on_delete=models.SET_DEFAULT, default='Employee deleted') But I am getting an error OperationalError at /admin/mainapp/device/1/change/ no such column: device.updated_by_id -
simple_settings.LazySettings raises "cannot import name 'get_cache' from 'django.core.cache'"
The following import fails only on my github actions workflow, but works on my local env: from simple_settings import LazySettings /opt/hostedtoolcache/Python/3.10.11/x64/lib/python3.10/site-packages/simple_settings/__init__.py:1: in <module> from .models import Settings /opt/hostedtoolcache/Python/3.10.11/x64/lib/python3.10/site-packages/simple_settings/models.py:2: in <module> from django.core.cache import get_cache E ImportError: cannot import name 'get_cache' from 'django.core.cache' (/opt/hostedtoolcache/Python/3.10.11/x64/lib/python3.10/site-packages/django/core/cache/__init__.py) Has anyone else encoutered this? Here's the requirements also: certifi==2022.12.7 chromedriver_autoinstaller==0.4.0 django_simple_settings==0.3.1 jira==3.4.1 openapi_core==0.16.5 pytest==7.2.0 pytest_schema==0.1.1 python_dateutil==2.8.2 PyYAML==6.0 requests==2.28.1 selenium==4.8.2 simple_settings==1.2.0 six==1.16.0 urllib3==1.26.13 Python 3.10, OS: Ubuntu-latest -
Each child in a list should have a unique "key" prop error in django + react app
I've tried everything, React keeps giving me the same error: "Each child in a list should have a unique "key" prop." It's a django project with a react app inside, i'm building a form where i want the users to select a category from a dropdown. models.py: class Category(models.Model): title = models.CharField(max_length=20) slug = models.SlugField() def __str__(self): return self.title api.py @permission_classes((AllowAny,)) class CategoriesView(APIView): def get(self, request, *args, **kwargs): categories = Category.objects.all() serializer = CategorySerializer(categories, many=True) return Response(serializer.data) categories_view = CategoriesView.as_view() serializers.py: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('title',) dropdown v1: <label htmlFor="categories">Categories</label> <select id="categories" value={categoryID} onChange={(event) => setCategoryID(event.target.value)} > <option key="default" value=""> Select category: </option> {categories && categories.filter(category => category).map((category) => ( <option key={category.id} value={category.id}> {category.title} </option> ))} </select> dropdown v2: <select id="categories" value={categoryID} onChange={(event) => setCategoryID(event.target.value)} > <option key="default" value="">Select category:</option> {categories && categories.filter(category => category).map((category) => ( <option key={uuidv4()} value={category.id}> {category.title} </option> ))} </select> data fetching: const [categories, setCategories] = useState([]); const [categoryID, setCategoryID] = useState(''); useEffect(() => { const fetchCategories = async () => { const response = await fetch('/api/categories/'); const data = await response.json(); if (Array.isArray(data)) { setCategories(data); } else { console.error('Data returned from API is not an array:', data); } }; fetchCategories(); … -
How to get region of user in loggs Django
I'm looking for way to get info about which region user from and add that in logg file I already can have their ip with function def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return str(ip) And then i add that into logg info def writing_logs(request, action): logger.info('{} {} {} {}'.format( request.user.email, get_client_ip(request), action)) And i want to know how to do something like that and show country/region/city of request user -
Django Admin page Glitch
Recently, in the last two projects the home page of the admin url in django appears with the following css glitch. enter image description here As I have done everything in the same way as the previous project I don't know why this is happening. Is this a recent bug with the newer versions? enter image description here Here is my settings.py: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:5173", ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # External 'rest_framework', 'corsheaders', # Internal Apps 'todo', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', "corsheaders.middleware.CorsMiddleware", 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = "backend.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "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", ], }, }, ] WSGI_APPLICATION = "backend.wsgi.application" # Database DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } … -
How can I create Bulk message sender site like SendGrid?
I am trying to create bulk mail sender website like SendGrid. But I am confused how can I create without using any API of plugins I create my own API so please help me. If anyone know How it will done. I am trying to create website like SendGrid. -
Django ModuleNotFoundError, project cannot recognize my application
when i use 'python manage.py runserver' ModuleNotFoundError is come.. project cannot recognize my application 'main' i ask it to chatGPT and modify insert 'main' in settings.py but project still cannot recognize 'main' -
Aggrgate JSON key value of JSONField Django PostgreSQL
I have a simple model setup as below, import random import string from django.db import models def random_default(): random_str = "".join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) return {"random": random_str, "total_price": random.randint(1, 100)} class Foo(models.Model): cart = models.JSONField(default=random_default) I want to get the sum of total_price from all Foo instances. In native Python, I can do something like below to get the sum, but I believe it is suboptimal. sum(foo.cart["total_price"] for foo in Foo.objects.all()) I tried the following aggregate queries with Django, but none seems correct/working. 1. Foo.objects.aggregate(total=models.Sum(Cast('cart__total_price', output_field=models.IntegerField()))) # Error # django.db.utils.DataError: cannot cast jsonb object to type integer 2. Foo.objects.aggregate(total=models.Sum('cart__total_price', output_field=models.IntegerField())) # Error # django.db.utils.ProgrammingError: function sum(jsonb) does not exist # LINE 1: SELECT SUM("core_foo"."cart") AS "total" FROM "core_foo" ^ # HINT: No function matches the given name and argument types. You might need to add explicit type casts. Question What is the proper/best way to get the sum of top-level JSON keys of a JSONField? Versions Python 3.8 Django 3.1.X -
Trouble printing context in Django Cookiecutter template
Background: Django Cookiecutter template psql db Have created a new app and installed it per settings.py file What I want = data from db to flow into the template view Problem: No matter what I try I can't get the data visible in the template view on my local host. Views.py file ('<projectslug>/<projectslug>/appname/views.py) from django.shortcuts import render def exercise_table(request): var_dict = { 'var_1': "wario", 'var_2': snakes} return render(request, 'pages/home.html', context=var_dict) Template file (<projectslug>/<projectslug>templates/pages/home.html) {% extends "base.html" %} {% block content %} <table> <thead> <tr> <p>You are on home pg</p> <p>the name is: {{ var_1 }} wa ha ha</p> <p>the second var is: {{ var_2 }} stretch </p> </tr> </thead> </table> {% endblock content %} Settings file (base.py) BASE_DIR = Path(__file__).resolve(strict=True).parent.parent.parent APPS_DIR = BASE_DIR / "projectslug" TEMPLATES = [ { # https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND "BACKEND": "django.template.backends.django.DjangoTemplates", # https://docs.djangoproject.com/en/dev/ref/settings/#dirs "DIRS": [str(APPS_DIR / "templates")], # https://docs.djangoproject.com/en/dev/ref/settings/#app-dirs "APP_DIRS": True, } All of the text in home.html displays as expected. The problem is accessing the variables within {{ }} brackets. No matter what I try the variables just do not appear. I've cut down the system as it used to pull info from a psql db and populate in a complex table, but have been able to … -
How to get rid of daylight saving time (DST) in Django? (Because in my country it's not being used anymore!)
In my country, daylight saving time (DST) is not being applied anymore, but Django is still taking it into account. So when I choose my region in TIME_ZONE inside the settings.py file, the time is stored wrong (1-hour offset) inside the database. Is there any possible way to turn off the DST in Django?! -
Django Mock isn't working as expected in Unit test
I'm having a view in which there is a method called can_upload_file that makes external calls. So, in my unit test I tried to mock that particular method as follows: DatasetViewSet._can_upload_file = MagicMock() DatasetViewSet._can_upload_file = "valid" response = self.client.post(self.url, self.dataset, format="multipart") However I see that the actual can_upload_file method in the view is still executed. How can I fix this? -
DRF Social OAUTH2 merge email and social login. Error UNIQUE constraint failed: users_user.email
implemented Django Rest Framework social OAUTH following this guide https://abhik-b.medium.com/step-by-step-guide-to-email-social-logins-in-django-5e5436e20591 I create user successfully with email/password and also with google oauth. The issue is the following... If I create a user with email/password (example@gmail.com) and then I try to login with google with the same email (example@gmail.com) i got following error. django.db.utils.IntegrityError: UNIQUE constraint failed: users_user.email See complete log here [02/May/2023 21:03:07] "POST /api-auth/google-tokens/ HTTP/1.1" 200 648 Internal Server Error: /api-auth/convert-token Traceback (most recent call last): File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\django\db\backends\sqlite3\base.py", line 357, in execute return Database.Cursor.execute(self, query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sqlite3.IntegrityError: UNIQUE constraint failed: users_user.email The above exception was the direct cause of the following exception: Traceback (most recent call last): File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\django\core\handlers\exception.py", line 56, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\django\views\decorators\csrf.py", line 55, in wrapped_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\django\utils\decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\django\views\decorators\csrf.py", line 55, in wrapped_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\drf_social_oauth2\views.py", line 47, in dispatch return super(CsrfExemptMixin, self).dispatch(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Luix\Estudio\React\Try-Hard-Apps\try-hard-backend\evns\tryhard\Lib\site-packages\rest_framework\views.py", line 509, in dispatch response = … -
Which one do you prefer, django vs fast-api?
I got a question. I'm studying Python and Django. However, I heard that the fast-api is now a trend, so I am wondering whether to study Django(django rest framework) more or to study the fast-api again. Which framework do you prefer in practice? If you develop with Python, I would like to know the answer to whether you use django(django rest framework) more or fast-api more in the actual field. I'm wondering which one to prioritize. -
Django Login dont work, how i can i fix it?
I have a functional login feature on my website, but unfortunately, the private page can still be accessed by typing in its URL, even without logging in. I am concerned about this security flaw and would like to know how I can prevent users from accessing the private page without first logging in. Can you offer any advice or guidance on how to address this issue? I asked ChatGPT for help. It suggested putting "login_required" before "def", but it's not working. def login_view(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect('/Händlerpage/ else: return render(request, 'login.html', {'error_message': 'Ungültiger Login'}) else: return render(request, 'login.html') @login_required def Händlerpage(request): return render(request,'Händlerpage.html') -
Django how to update querysets' jsonfield based on current value
According to django docs, queryset could be updated with F expression as qs.update(stories_filed=F('stories_filed')+1) How can we use the F expression on nested jsonfield? Assuming I have a jsonfield as extra_data = models.JSONField(default=dict), and I use extra_data['logs'] to record actions in this model, which means extra_data['logs'] = ['log1', 'log2'] What is required is something like qs.update(extra_data__logs=F('extra_data__logs').append('some logs')) Is there any way to update jsonfield like above? -
Django Admin only showing one record
I just did a migration and now my Django Admin for a specific model is only showing 1 record on the first page, all other pages are emtpty, even though it says there are 40000+ records across 4000+ pages (which there should be - they are in the database). What is happening here? This is on Django 3.0 . -
Django send mail with ics attachment encoding error
I am trying to send an ics attachment to the clients with django: message = EmailMessage(subject, html_string, from_email, [to_email]) if attach: message.attach_file(attach, 'text/calendar; charset=UTF-8') message.send() Before sending the file it has the correct characters (on the server) like: Hajvágás And after I send it, it looks like this: Hajvágás I checked multiple email clients like gmail and spark and all of them show the same gibberish. Also the ics file is validated. Is there a way to send it correctly? -
Make a List Based on the Aggregation of Ratings from Two Models
From two models: class Review(models.Model): artist = models.CharField(max_length=100) album = models.CharField(max_length=200) rating = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(10)], default=10, ) ... class AddedReview(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) review = models.ForeignKey(Review, on_delete=models.CASCADE) rating = models.IntegerField(default=10) ... I was able to create a model method in the Review model to aggregate the ratings from both models above: def avg_rating(self): added_ratings = 0 orig_rating = self.rating added_ratings_count = self.addedreview_set.count() if added_ratings_count > 0: for added_review in self.addedreview_set.all(): added_ratings += added_review.rating ratings_sum = added_ratings + orig_rating ratings_count = added_ratings_count + 1 ratings_avg = ratings_sum / ratings_count avg_return = round(ratings_avg, 1) if avg_return == 10.0: avg_return = 10 else: avg_return = avg_return return avg_return else: return self.rating I have the Reviews displayed by the date they were created, with their "Avg. Rating" displayed: Now I want to create a "Highest Rated" list, ordering the list by each Reviews "Avg. Rating": I thought I would be able to do this using the {{ review.avg_rating }} I just created: # views.py highest_list = Review.objects.order_by('-avg_rating')[0:5] # sidebar_component.html (included in home.html) {% for review in highest_list %} <div class="d-flex justify-content-between"> <p class="list-item"><a href="{% url 'review' review.id %}">{{ review.artist }} - {{ review.album }}</a></p><span>{{ review.avg_rating }}</span> </div> {% endfor %} But this … -
'ManyRelatedManager' object has no attribute 'reserve_distance'
I have been trying to retrieve data from database using prefetch_related including a Many-to-Many relationship. However, I am getting the error: AttributeError: Got AttributeError when attempting to get a value for field `reserve_distance` on serializer `ProjectIndianReserveSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `ManyRelatedManager` instance. Original exception text was: 'ManyRelatedManager' object has no attribute 'reserve_distance'. When removing reserve_distance from ProjectIndianReserveSerializer (considering this is a Many-to-many relationship there is a possibility to have zero records), the serialization finishes with no errors showing an empty result after serialization: "nearest_first_nations": { "reserve_id": null }, However, when running the created query (shown below), a record for the project_id =1 exists in the db: SELECT ("project_nearest_first_nations"."project_id") AS "_prefetch_related_val_project_id", "indianreservebanddistance"."id", "indianreservebanddistance"."reserve_id", "indianreservebanddistance"."reserve_distance" FROM "indianreservebanddistance" INNER JOIN "project_nearest_first_nations" ON ("indianreservebanddistance"."id" = "project_nearest_first_nations"."indianreservebanddistance_id") WHERE "project_nearest_first_nations"."project_id" IN (1) I am wondering why is not showing the record in response when I have the record in the db: _prefetch_related_val_project_id|id |reserve_id|reserve_distance| ------------------------------------+---+----------+----------------+ 1|110| 627| 31.1900| 1|111| 660| 39.5800| 1|112| 607| 46.1700| Here is the configuration I have in the models: indian_reserve_name.py (model) class IndianReserveName(models.Model): name = models.CharField(max_length=127) project.py (model) class IndianReserveDistance(models.Model): reserve_id = models.ForeignKey(IndianReserveName, on_delete=models.SET_NULL, db_column="reserve_id", null=True) reserve_distance = models.DecimalField(max_digits=16, decimal_places=4, blank=False, …