Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to select the suitable deployment plan
I'm planning to deploy a web api build with django rest api and it will be hosted in a digitalOcean droplet. It's frontend will be in a heroku dyno and frontend is developed in react js. Monthly 6000+ users will use this web application so my question is which plans should I use in heroku as well as digitalOcean to satisfy 6000 users without a downtime . Thank you! -
who can i edit image in the django database?
I have a model of image with them name in Django. my model: class images(models.Model): name = models.CharField(max_length=150) image = models.ImageField() in my template I show the users a list of image name. I want when user click on the name of image, in the image detail template show hem the edited image. my model manager is: def get_by_id(self, product_id): qs = self.get_queryset().filter(id=product_id) if qs.count() == 1: return qs.first() else: return None and my views is: def image_detail(request, *args, **kwargs): img_id= kwargs['image_id'] im = images.objects.get_chart(ch_id) if MineralSpectrum is None: raise Http404 reach_image = im.image.path 'my code for edit image' context = {} return render(request, 'image_detail.html', context) but line 6 is wrong. how can I access the image to edit then render it to image_detail template? I have a model that has two fields, a photo, and a photo name. I created a template(image.html) that showed a list of photo names. When the user clicks on the image name, I want to take the corresponding image in the model from the database, edit it and render the edited image to the image_detail.html template -
Filtering accounts from two different OUs in django-python3-ldap
We have a django project, where users get to login using their local AD access using django-python3-ldap. This has worked fine, since we have been using only one OU until now. However, we now need to get users from other OU, which is at the same level as the current OU. How can we do this? We have setup following: settings.py # The LDAP search base for looking up users. LDAP_AUTH_SEARCH_BASE = 'DC=ypn,DC=local' # Custom setting LDAP_AUTH_FORMAT_SEARCH_FILTERS = 'project.ldap.custom_format_search_filters' ldap.py: from django_python3_ldap.utils import format_search_filters def custom_format_search_filters(ldap_fields): # Call the base format callable. search_filters = format_search_filters(ldap_fields) # Advanced: apply custom LDAP filter logic. search_filters.append('(|(OU=office1)(OU=office2))') # All done! return search_filters And when we run python .\manage.py ldap_sync_users, it just gives us nothing. I know the filtering works, because I can search by names, for example (sn=name), and it will give me correct results. Running search without any filters just results on lots of "junk" accounts, people that have left, computers, etc. and we don't want to bring all that junk onboard. -
How do you get queryset objects related to queryset passed to templates in Django
I have these two models and as you can see they have a relationship. class Post(models.Model): text = models.TextField() class PostImage(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) image = models.FileField(upload_to = 'media/',blank=True, null=True) As far as I understand if I query posts and push them to a template and post, I would expect to use something like this in my templates to retrieve the images URL attached to the posts but it doesn't seem to work. {% for post in posts %} {% for post_image in post.post_image_set.all %} {{post_image.image.url}} {% endfor %} {% endfor %} What am I doing wrong? -
How to save and use timezones in Django
I have an important question. I understand Django saves data in "localtime", that is, UTC for my international app. So, if a user creates an "Event" with startdate (datetime object) 18:00, it will be 18:00 UTC. However, the user lives in Spain (UTC+1), so I store the timezone ("Europe/Madrid") in a different field. When I render it in the html, it will show the UTC time (but the user lives in UTC+1). Then, if I want to convert the time to a visiting user from Spain, I use the timezone tag to convert the datetime to Spain ... and now it will show 17:00. {% if logged_user_profile.timezone %} {% timezone logged_user_profile.timezone %} <p class="text-muted font-weight-bold"> {{ event.date_start|date:"h:i A" }} ({{ logged_user_profile.timezone }} </p> {% endtimezone %} {% else %} <p class="text-muted font-weight-bold"> {{ event.date_start|date:"h:i A" }} ({{ owner_profile.timezone }}) </p> {% endif %} The Spain case is only an example. I guess my question is broad, which is the best way to deal with timezones in django. I need to store the datetime of an event and show it to visiting users in their localtime, if the stored datetime is in UTC, it will not reflect the datetime the user … -
Django stripe subscription Forbidden: issue
Hi I'm trying to implement stripe subscription in django. I have been following a guide from guide link I am facing an issue which gives me the error: Forbidden: /create-sub [13/Nov/2020 23:33:40] "POST /create-sub HTTP/1.1" 403 150 here's my code for the sub part: @login_required def create_sub(request): if request.method == 'POST': # Reads application/json and returns a response data = json.loads(request.body) payment_method = data['payment_method'] stripe.api_key = djstripe.settings.STRIPE_SECRET_KEY payment_method_obj = stripe.PaymentMethod.retrieve(payment_method) djstripe.models.PaymentMethod.sync_from_stripe_data(payment_method_obj) try: print("h-1") # This creates a new Customer and attaches the PaymentMethod in one API call. customer = stripe.Customer.create( payment_method=payment_method, email=request.user.email, invoice_settings={ 'default_payment_method': payment_method } ) print("h1") djstripe_customer = djstripe.models.Customer.sync_from_stripe_data( customer) request.user.customer = djstripe_customer print("h2", customer.id) # At this point, associate the ID of the Customer object with your # own internal representation of a customer, if you have one. # print(customer) # Subscribe the user to the subscription created subscription = stripe.Subscription.create( customer=customer.id, items=[ { "price": data["price_id"], }, ], expand=["latest_invoice.payment_intent"] ) print("h3") djstripe_subscription = djstripe.models.Subscription.sync_from_stripe_data( subscription) request.user.subscription = djstripe_subscription request.user.save() print("h4") return JsonResponse(subscription) except Exception as e: print("sorry") return JsonResponse({'error': (e.args[0])}, status=403) else: return HttpResponse('requet method not allowed') I tried various sources but could solve it. I believe the issue lies somewhere in stripe.Customer.create. Any help would be … -
Displaying Data from 2nd Table into 1st Table automatically as Pre-Filled for SuperAdmin (Foreignkey)
Using Django, i have 2 Tables. 1 Table is for the list of questions that User answers, the user would enter numbers. The 2nd Table is for the total Calculation, it simply just shows the total calculated number. I want to show the Total Calculated Number also in the 1st Table. So i have created a Foreign Key to do this. I have placed the Foreign Key inside the 1st Table. But when the User answers and submit the form, when i got to the 1st Table, the foreign key column/row is blank. It is forcing me as the SuperAdmin to open up the entry in the table, and manually select the value for the foreignkey. Also it is not showing in the interface of the table value of Total Calculated Number, it is just showing the 2nd table which is a class and entry number. first picture below displays the two tables in the super admin side, 1st table-"ansquestionss" 2nd table -"resultss" 2nd picture below shows after opening the 1st table "ansquetionss", you can see the foreign key column, which as the column "Results" is blank. (if working correctly This should be automatically pre-filled) 3rd picture below, displays that … -
Django redirect with parameter - NoReverseMatch at
After executing create_goal(), I want to redirect to customer_info(): def create_goal(request, savingsGoalUid): # do stuff customer_id = "43debcf7-8477-4d96-91e6-c3fb0291ea87" return redirect('customer_info_id', customer_id=customer_id) def customer_info(request, customer_id=None): if customer_id is None: # do stuff else: # do more stuff context = {"foo": customer_id} return render(request, "starling/show_details.html", context) I get: NoReverseMatch at /create_goal Reverse for 'customer_info' with keyword arguments '{'customer_id': '43debcf7-8477-4d96-91e6-c3fb0291ea87'}' not found. My urls.py looks like this: urlpatterns = [ path("", views.index, name="index"), path("customer_info", views.customer_info, name="customer_info"), path("create_goal", views.create_goal, name="create_goal"), path("customer_info/<customer_id>", views.create_goal, name="customer_info_id"), path("delete/<savingsGoalUid>", views.delete, name="delete") ] I tried all sorts of variations including customer_info_id, customer_info, formatting a whole new url+query string, but nothing works. All I want is to just pass customer_id as parameter to customer_info() when I redirect to customer_info() after create_goal(). Thanks for any help! -
access picture in django rest framework in views for picture operations
I am using Django Rest framework to create an OpenCV API for face detection. I want to do operation on post image using OpenCV but I am not able to access the image. How can I access the image in views.py here is my code and thanks for your help. #models.py from django.db import models # Create your models here. class MyFile(models.Model): file = models.FileField(blank=False, null=False) description = models.CharField(max_length=255) uploaded_at = models.DateTimeField(auto_now_add=True) from PIL import Image from django.core.files.storage import FileSystemStorage from django.core.files.base import ContentFile from django.conf import settings from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from rest_framework import status from api.face_detection import face_detect from .serializers import MyFileSerializer class MyFileView(APIView): parser_classes = (MultiPartParser, FormParser) def get(self, request, *args, **kwargs): return Response( {'title': 'Opencv RestAPI for face detection'}) def post(self, request, *args, **kwargs): file_serializer = MyFileSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How i can display a list instead of choicelist in django
Each time i want to add an invoice, i want to have a unique invoice_id which is an increment number (+1), but the problem is that i have a multiple users app, so i get the error that this invoice_id already exist. how can i customize the ids so each user can have its ids following the latest of same user. class Company(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=64) class Invoice(models.Model): company = models.ForeignKey('Company', on_delete=models.CASCADE) invoice_id = models.CharField(max_length=20, unique=True) name = models.CharField(max_length=256) -
how can i edit multiple objects/row atonce in django html template
i facing an problem on my django project . i try to edit and update an objects . but it's showing an error which is name is MultipleObjectsReturned . hear is my issue screenshots . when i was clicked this update button ( user can update which he went ) . than showing next 2nd image 1st img showing this error 2nd image Views.py def purchase_order_item_update(request,order_id): purchase_item_list = Purchase_order_item.objects.filter(order_id=order_id) # porder = Purchase_order_item.objects.get(order_id=order_id) # this is the form for getting data from html if request.method == 'POST': for bt in Purchase_order_item.objects.filter(order_id=order_id): pu_id = bt.puid # product Id quantity = request.POST.get('asqty') unit_price = request.POST.get('uprice') # itemid = pk type total = int(quantity) * float(unit_price) cv = Purchase_order_item.objects.get(puid=pu_id) cv.quantity = quantity cv.unit_price = unit_price cv.total_price = total cv.save() return redirect('purchase_order_item',order_id= order_id) return render(request,'back/purchase/assign_purchas_item.html', {'purchase_item_list':purchase_item_list, }) Actually i went to edit and update this list of entries and update also if user making any typing mistake then he can update . thank you -
Django Celery Beat and Tasks Results
Is it possible for django-celery-beat not to save tasks that are performed in a short time interval? By default, all results are saved to the Task Results table. I cannot find this information on celeryproject webpage. Alternatively, what should be the settings for postgres auto vacuum so that indexes don't take up that much disk space? I want a simple solution. Overwriting django celery logic is not an option. -
Failure to install psycopg2 in Pycharm
I'm trying to install psycopg2 to use a postgresql db in the backend of my django project, but every time I run the pip install psycopg2 command I get an error saying: Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. I have added the \bin\ folder containing the file to my path, I've ran the pip install psycopg2-binary command as well, and I've uninstalled and reinstalled posgresql on my computer, I've also ran the python setup.py build_ext command mentioned in the error message, and this error still pops up. I'm operating on a windows 10 os and using posgresql 13.1. Any suggestions? -
UserCreationForm override password hint_id_password1
Hello I want to override the password hints that Django generates for you in the UserCreationForm(). These: Your password cannot be too similar to your other personal information. Your password must be 8 characters long. Your password cannot be a frequently used password. Your password cannot be entirely digital. I tried by overriding help_text in Meta but without any success. -
Invalid parameter error while trying to create stripe payment
i am creating an ecommerce website where i have included stripe payment method but when i try to create the payment there occur invalid parameters error. i have no idea what is going wrong, i have followed as same as the video and tried many thing to solved this but still that error was occuring here is my View.py from django.conf import settings import stripe stripe.api_key = settings.STRIPE_SECRET_KEY class PaymentView(View): def get(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) if order.billing_address: context = {'order': order, 'DISPLAY_COUPON_FORM': False, } return render(self.request, "payment.html", context) else: messages.warning(self.request, "you have not added a billing address") return redirect("First:checkout") def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.get_total() * 100) try: charge = stripe.Charge.create( amount=amount, currency="usd", source=token, ) # create the payment payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.get_total() payment.save() # assign the payment to the order order_items = order.items.all() order_items.update(ordered = True) for item in order_items: item.save() order.ordered = True order.payment = payment order.ref_code = create_ref_code() order.save() messages.success(self.request, " your order was sucessful") return redirect("/") except stripe.error.CardError as e: body = e.json_body err = body.get('error', {}) messages.error(self.request, f"{err.get('messages')}") return redirect("/") except stripe.error.RateLimitError as e: # Too … -
Saving data on OneDrive or Google Drive (Heroku)
Hello I am new to using django and heroku and through out me designing my first project I Found out that I need a AWS 3 account/S3 storage to store images/files but I was wondering if I could use either a OneDrive or a Google Drive to save the files/images that the user uploads and if so, is it Like when using a AWS 3 storage. -
try to sand Email by Django but 504 Gateway Time-out and haven't received an email
I try to write code (on cs50) to send a verification email via Django but occur error and not received a verification email. On page 504 Gateway Time-out and on terminal OSError: [Errno 99] Cannot assign requested address my setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'example@gmail.com' EMAIL_HOST_PASSWORD = 'password of gmail account' MAILER_EMAIL_BACKEND = EMAIL_BACKEND DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_PORT = 587 EMAIL_USE_TLS = True my view.py after saving the account current_site = get_current_site(request) mail_subject = 'subject' message = render_to_string('register/acc_active_email.html', { 'user': account, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(account.pk)), 'token': default_token_generator.make_token(account), }) to_email = form.cleaned_data.get('email') email = EmailMessage(mail_subject, message to=[to_email]) email.send() -
vscode is showing problem in code though it runs properly
i was doing template inheritance while doing a project in django Though my website is working but in the code vscode is showing problem <title>{% block title%} {% endblock %}</title> <style> {% block css %} {% endblock %} </style> after writing another page and inheriting.....my css also works but vscode shows problem in {% block css %} {% endblock %} line -
DJango - Update text depending on dropdown selection?
My Google search skills evidently aren't up to scratch, so I'm wondering if Django has the capability to dynamically update text displayed on the HTML page depending on what option is selected from a dropdown? Or would I need to look into utilising another tool to help with this? Apologies for the noob question as I'm still learning Python/Django. -
Django smart selects is not working properly
I try to chain four categories with django smart select but it does not work properly. Django does not take or input values from in the last one. clothing_size. It is working properly till clothing sizes. That selectbox is always empty. My model: What could be the problem here? That does not seem like js problem, because other fields are working properly. from django.db import models from smart_selects.db_fields import ChainedForeignKey # Create your models here. class MainCategory(models.Model): name = models.CharField(max_length=20, null=True) def __str__(self): return self.name class ClothingType(models.Model): main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE, null=True) clothing_type = models.CharField(max_length=64, null=True) def __str__(self): template = '{0.main_category} {0.clothing_type}' return template.format(self) class ClothingSubType(models.Model): main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE, null=True) # clothing_type = models.ForeignKey(ClothingType, on_delete=models.CASCADE, null=True) clothing_type = ChainedForeignKey(ClothingType, chained_field="main_category", chained_model_field="main_category", show_all=False, auto_choose=True, sort=True, null=True) clothing_sub_type = models.CharField(max_length=254, null=True) def __str__(self): template = '{0.main_category} {0.clothing_type} {0.clothing_sub_type}' return template.format(self) class ClothingSize(models.Model): main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE, null=True) clothing_type = ChainedForeignKey(ClothingType, chained_field="main_category", chained_model_field="main_category", show_all=False, auto_choose=True, sort=True, null=True) clothing_sub_type = ChainedForeignKey(ClothingSubType, chained_field="clothing_type", chained_model_field="clothing_type", show_all=False, auto_choose=True, sort=True, null=True) # clothing_sub_type = models.ForeignKey(ClothingSubType, on_delete=models.CASCADE, null=True) clothing_size = models.CharField(max_length=30, null=True) def __str__(self): template = '{0.main_category} {0.clothing_type} {0.clothing_sub_type} {0.clothing_size}' return template.format(self) class Product(models.Model): name = models.CharField(max_length=30, null=True) sku = models.CharField(max_length=20, null=True) main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE, null=True) clothing_type … -
Django's runserver on Oracle Cloud?
I am trying to use a free instance of Oracle Cloud for my Django project. But I have no idea how I can check the Django's "runserver" page like this python ./manage.py runserver since the public IP address given to my instance didn't load the Django's page. I tried to look into "network" session of Oracle Cloud but I wasn't able to find any meaningful stuff related to this. When I googled this, it seemed that it has to do with firewall setting in terms of Google Cloud so maybe Oracle has the same but in vain. -
django push notifications throws gcm error
I am using django push notifications but I am sometimes getting the following error raised unexpected: GCMError({'multicast_id': 1826728239203974173, 'success': 4, 'failure': 1, 'canonical_ids': 0, 'results': [{'message_id': '0:1605278994023650%0f493ae6f9fd7ecd'}, {'message_id': '0:1605278994028849%2fd9afcdf9fd7ecd'}, {'error': 'InternalServerError'}, {'message_id': '0:1605278994038573%0f493ae6f9fd7ecd'}, {'message_id': '0:1605278994030881%cc9b4facf9fd7ecd'}]},) Traceback (most recent call last): File "/home/project/server-side/.venv/lib/python3.6/site-packages/celery/app/trace.py", line 374, in trace_task R = retval = fun(*args, **kwargs) File "/home/project/server-side/.venv/lib/python3.6/site-packages/celery/app/trace.py", line 629, in __protected_call__ return self.run(*args, **kwargs) File "/home/project/server-side/app/tasks.py", line 299, in alarm_users is_business_app=True, File "/home/project/server-side/tools/utils.py", line 246, in send_push web_devices.send_message(None, extra=kwargs, use_fcm_notifications=True) File "/home/project/server-side/.venv/lib/python3.6/site-packages/push_notifications/models.py", line 73, in send_message r = gcm_send_message(reg_ids, data, cloud_type, application_id=app_id, **kwargs) File "/home/project/server-side/.venv/lib/python3.6/site-packages/push_notifications/gcm.py", line 209, in send_message chunk, data, cloud_type=cloud_type, application_id=application_id, **kwargs File "/home/project/server-side/.venv/lib/python3.6/site-packages/push_notifications/gcm.py", line 166, in _cm_send_request return _cm_handle_response(registration_ids, response, cloud_type, application_id) File "/home/project/server-side/.venv/lib/python3.6/site-packages/push_notifications/gcm.py", line 111, in _cm_handle_response raise GCMError(response) push_notifications.gcm.GCMError: {'multicast_id': 1826728239203974173, 'success': 4, 'failure': 1, 'canonical_ids': 0, 'results': [{'message_id': '0:1605278994023650%0f493ae6f9fd7ecd'}, {'message_id': '0:1605278994028849%2fd9afcdf9fd7ecd'}, {'error': 'InternalServerError'}, {'message_id': '0:1605278994038573%0f493ae6f9fd7ecd'}, {'message_id': '0:1605278994030881%cc9b4facf9fd7ecd'}]} The most interesting thing is that it sometimes works but sometimes not I have not able to find the bug yet. If anyone has encountered this before or anyone knows how to fix this. please can you help? Thanks in advance! -
How to delete the Token from backend in Django
I'm using django rest-auth along with the django rest api. I can logout the user by calling rest-auth/logout in the browsable api and it will delete the token from the Database. In the browsable api, I don't have to send the Token along with the logout url. I called the same url rest-auth/logout from a React js front end and it gives the response as 'successfully logged out' but Token remains in the database. How can I remove the Token by calling the url from the front end. -
plz help mw sir I am getting error when i run migrate commad
mayur@mayur-Latitude-E5440:~/Desktop/practice/myproject$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/lib/python3/dist-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/usr/lib/python3/dist-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python3/dist-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python3/dist-packages/django/core/management/base.py", line 361, in execute self.check() File "/usr/lib/python3/dist-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/usr/lib/python3/dist-packages/django/core/management/commands/migrate.py", line 64, in _run_checks issues = run_checks(tags=[Tags.database]) File "/usr/lib/python3/dist-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/usr/lib/python3/dist-packages/django/core/checks/database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "/usr/lib/python3/dist-packages/django/db/backends/mysql/validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "/usr/lib/python3/dist-packages/django/db/backends/mysql/validation.py", line 13, in _check_sql_mode with self.connection.cursor() as cursor: File "/usr/lib/python3/dist-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/usr/lib/python3/dist-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/usr/lib/python3/dist-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/usr/lib/python3/dist-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/usr/lib/python3/dist-packages/django/db/backends/mysql/base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "/usr/lib/python3/dist-packages/pymysql/init.py", line 94, in Connect return Connection(*args, **kwargs) File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 325, in init self.connect() File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 599, in connect self._request_authentication() File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 871, in _request_authentication auth_packet = self._process_auth(plugin_name, auth_packet) File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 902, in _process_auth return _auth.sha256_password_auth(self, auth_packet) File "/usr/lib/python3/dist-packages/pymysql/_auth.py", line 179, in sha256_password_auth data = sha2_rsa_encrypt(conn.password, conn.salt, conn.server_public_key) File "/usr/lib/python3/dist-packages/pymysql/_auth.py", line 144, in sha2_rsa_encrypt rsa_key = … -
Primary key with multiple fields in MYSQL DB wrongly recognized by Django, when connecting MYSQL table to Django
Below is the MYSQL table of Votes_list. As you can see here the primary key is {g_aadhaar_number, a_grievance_id} fields. Now while importing this table into Django as Model, below is the autogenrated code. g_aadhaar_number = models.ForeignKey(People, models.DO_NOTHING, db_column='G_Aadhaar_number') # Field name made lowercase. a_grievance = models.OneToOneField(Grievance, models.DO_NOTHING, db_column='A_Grievance_ID', primary_key=True) # Field name made lowercase. type = models.CharField(db_column='Type', max_length=10) # Field name made lowercase. class Meta: managed = False db_table = 'votes_list' unique_together = (('a_grievance', 'g_aadhaar_number'),) My doubt is even after Django correctly recoginising that the two fields together act as primary key in the line unique_together = (('a_grievance', 'g_aadhaar_number'),) , why is a_grievance expicitly mentioned as a primary key. This is causing a lot of errors. Can I know a solution? Thank you in advance :)