Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Processing data from React.js form with django
I create a web application using Django for the back-end and React for the front-end. I have three input forms on my HTML page, which I create with react. I need to send this data to MySQL.db and processing using .py script. Can you explain, how can I send data from react to django -
Django. How to migrate just a particular app in mongo
I want to migrate the models logging app into the thor (mongodb) database. But when I say " python manage.py migrate --database=thor ", it migrates other apps as well. I'm sure I'm doing something wrong. Can anyone help? class AuthRouter(object): """ A router to control all database operations on models in the auth application. """ route_app_labels = {'models_logging'} def db_for_read(self, model, **hints): """ Attempts to read auth models go to auth_db. """ if model._meta.app_label == 'models_logging': return 'thor' return None def db_for_write(self, model, **hints): """ Attempts to write auth models go to auth_db. """ if model._meta.app_label == 'models_logging': return 'thor' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth app is involved. """ if obj1._meta.app_label == 'models_logging' or \ obj2._meta.app_label == 'models_logging': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth app only appears in the 'auth_db' database. """ if app_label == 'models_logging': return db == 'thor' return None -
Django - How to query a related translated model?
I have two models that are many to many related. Article and Tag models. Both are TranslateableModel using django-parler. I would like to get all tags together with articles_count for the current language. For example if a user comes to the page /en/blog I would like them to see tags together with the number of articles written in english for that tag. Something like Django (7 articles), Ruby on rails (4 articles) For django there might be 10 articles but only 7 are translated to english. What I have is something like this: Tag.objects.translated() .annotate(articles_count=(Count("articles__translations"))) But this gives me the count of total translations. If an article exists both in english and in french, it counts double. How can I make it so that it gives me the number of articles only in the current language in a given tag? -
inserting a data in a formset passed by a form
hi I have this error in inserting a data in a formset passed by a form this is the error that appears in my browser: NOT NULL constraint failed: devtest_datigruppi.gruppi_scheda_id it practically fails to see this change: groups.gruppi_scheda = Schede.objects.get (tab_name = tabName) but via print the right thing appears to me schedaName = schede_form.cleaned_data['nome_scheda'] scheda = schede_form.save(commit = False) scheda.utente = request.user scheda.save() #gruppi if gruppi_formset.is_valid(): for gruppi in gruppi_formset: gruppi.save(commit = False) gruppi.gruppi_scheda = Schede.objects.get(nome_scheda = schedaName) //print(gruppi.gruppi_scheda) gruppi.save() -
How to filter books, so you get the authors books and not every book available, when you use ListView and DetailView (Django)
Authors books should only be displayed when tapping the authors name in the ListView. models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils.text import slugify class Author(models.Model):´ author = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(unique=True, blank=False, null=False) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, null=False, blank=False) title = models.CharField(max_length=200) price = models.FloatField() image = models.ImageField(null=True, blank=True) views.py from app.models import Book, Author from django.shortcuts import render, redirect from django.contrib.auth.models import User, Group from django.views.generic.list import ListView from django.views.generic.detail import DetailView class HomeView(ListView): model = Author ordering = ['-id'] template_name = 'app/home.html' class AuthorView(DetailView): model = Author template_name = 'app/author.html' def get_context_data(self, *args, **kwargs): # author_pk = self.kwargs.get('pk', None) # Tried this logic, but it makes no sense after I looked at it more close books = Book.objects.all() if books.author is Author.pk: books_filtered = books.objects.all() context = super(AuthorView, self).get_context_data(*args, **kwargs) context['books'] = books_filtered return context Now when all authors are displayed on the home page with ListView, when someone clicks on an author they should see only the books the author has made with the DetailView This link I tried but it will only display all the books -
reverse proxy nginx docker django
so what I'm trying to do is to have two web apps: appli1 and appli2. They are served at web.appli1.com and web2.appli2.com here is my docker-compose file : version: '3' services: reverse-proxy: image: nginx volumes: - ./nginx.conf:/etc/nginx/nginx.conf ports: - 8000:8000 - 8001:8001 web: build: . command: python manage.py runserver 0.0.0.0:8000 depends_on: - redis environment: - REDIS_HOST=redis #ports: #- "8000:8000" web2: build: . command: python manage.py runserver 0.0.0.0:8001 depends_on: - redis environment: - REDIS_HOST=redis redis: image: redis:3.2-alpine volumes: - redis_data:/data volumes: redis_data: and here is my nginx.conf file : events { } http { server { listen 8000; server_name web.appli1.com; location / { proxy_pass http://web:8000; } } server { listen 8001; server_name web2.appli2.com; location / { proxy_pass http://web2:8001; } } } I've also set the domains in /etc/hosts using ip of host machine -
How to Create Group and Give Permission to users in Django?
I am Working on a e-commerce Project there i have created a custom dashboard for adding products and others things. but my client requirement create a interface on dashboard where i can create group and give permissions to my staff users. but don't idea what proper way to achieve target. Please give me suggestions. Thank you in advance. -
Django: Forgot Password using Phone Number
I have developed an app in React as frontend and Django as backend. In my app, I am taking only phone number as the input for user registration. I am able to register users successfully but problem lies in the forgot password section. As of now, I have been able to implement this part only via Email, also via the combination of Email and phone number (using Djoser). In Serializers.py from djoser.serializers import SendEmailResetSerializer class CustomSendEmailResetSerializer(SendEmailResetSerializer): phone = serializers.CharField(required=True) def get_user(self, is_active=True): # Retrieving user here. try: user = User.objects.get( phone=self.data['phone'] ) if is_active: return user else: return None except User.DoesNotExist: raise serializers.ValidationError("No user found") In settings.py DJOSER = { 'SERIALIZERS': { 'password_reset': 'serializers.CustomSendEmailResetSerializer', }, } But not via the phone number only. Any suggestions how to do this thing. -
How do I redirect from require_http_methods without using middleware?
I used a @require_http_methods decorator in my code for the logout page, but I can't wrap my head around the proper way to redirect a user on the method error. It is suggested to create a middleware there: django require_http_methods. default page But I wonder if there is a simpler way? -
Why cant I use the message feature provided by django?
In my view (Part of it): from django.contrib import messages try: selection=request.POST.get('portrange') except: messages.warning(request, "Please select the ports") In my html (Part of it): <div class="row"> <div class="col-md-10"> <div class="form-group"> <label for="port_range">Port range</label> <textarea class="form-control" id="port_range" rows="5" name ="portrange"></textarea> </div> </div> </div> How come my messages.warning is not appearing if i have no input in my textarea (portrange)? Am i doing something wrong for django message? All I know is i have to import: from django.contrib import messages When i press the submit button, it just redirect to another page without showing the warning -
Saving date and time into the database using django
I have created a date and time for my website where users will choose the date and time but I not sure how to save it into the database that I had. Below is images of how it looks like on my website and the code for it. my reception.html <script> $(function () { $("#datetimepicker1").datetimepicker(); }); </script> <div class="form-group m-3" > <h4> Hello {{ user.username }}, you are at the Reception Unserviceable Page</h4> <p>Select a date and Time</p> <div class="input-group date" style="width:300px" id="datetimepicker1" data-target-input="nearest"> <input required name="datetime" type="text" class="form-control datetimepicker-input" data-target="#datetimepicker1" /> <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> -
In Django admin options for model like ADD/DELETE/UPDATE not showing
I use Django rest framework. After run python manage.py runserver if I open http://127.0.0.1:8000/admin/ then attached below image showing same If I open any model then options like ADD/DELETE/UPDATE options are not showing. Attached above img for same (user model) Errors in console showing below- requirement.txt aiohttp==3.6.3 appdirs==1.4.4 asgiref==3.2.10 async-timeout==3.0.1 atomicwrites==1.4.0 attrs==20.2.0 awacs==0.9.6 aws-xray-sdk==0.95 awscli==1.20.34 boto3==1.18.32 botocore==1.21.34 certifi==2017.7.27.1 cffi==1.14.3 cfn-flip==1.0.3 chardet==3.0.4 click==6.7 colorama==0.4.3 colorclass==2.2.0 cryptography==3.1.1 dateparser==0.7.6 defusedxml==0.6.0 dictdiffer==0.7.0 distlib==0.3.1 Django==3.0.9 django-3-jet==1.0.8 django-admin-rangefilter==0.6.3 django-allauth==0.42.0 django-cors-headers==3.6.0 django-extensions==3.0.6 django-filter==2.4.0 django-flat-json-widget==0.1.1 django-grappelli==2.14.2 django-json-widget==1.0.1 django-money==1.1 django-nested-admin==3.3.2 django-otp==1.0.0 django-phonenumber-field==5.0.0 django-prettyjson==0.4.1 django-sendgrid-v5==0.9.0 django-simple-history==2.11.0 django-slack==5.15.3 django-sort-order-field==1.2 django-split-json-widget==1.16 django-storages==1.9.1 django-twilio==0.13.0.post1 djangorestframework==3.11.1 docker==4.3.1 docutils==0.14 ecdsa==0.16.0 filelock==3.0.12 flatten-json==0.1.7 future==0.16.0 futures==3.1.1 idna==2.6 importlib-metadata==2.0.0 jet-bridge-base==0.8.0 Jinja2==2.11.2 jmespath==0.9.3 jsondiff==1.1.1 jsonpickle==1.4.1 jsonschema==2.6.0 MarkupSafe==1.1.1 mock==4.0.2 more-itertools==8.5.0 moto==1.3.7 multidict==4.7.6 oauthlib==3.1.0 phonenumbers==8.12.8 Pillow==7.2.0 pluggy==0.13.1 prompt-toolkit==2.0.9 psycopg2-binary==2.8.5 py==1.9.0 py-moneyed==0.8.0 pyaml==20.4.0 pyasn1==0.4.8 pycparser==2.20 pycryptodome==3.9.8 PyJWT==1.7.1 pyotp==2.4.0 pytest==4.0.0 python-dateutil==2.6.1 python-dotenv==0.14.0 python-http-client==3.3.1 python-jose==2.0.2 python-monkey-business==1.0.0 python3-openid==3.2.0 pytz==2020.1 PyYAML==5.3.1 regex==2020.7.14 requests==2.24.0 requests-oauthlib==1.3.0 responses==0.12.0 rsa==4.5 s3transfer==0.5.0 sendgrid==6.4.7 six==1.10.0 slackclient==2.9.2 SQLAlchemy==1.3.19 sqlparse==0.3.1 standardjson==0.3.1 starkbank-ecdsa==1.1.0 stringcase==1.0.6 terminaltables==3.1.0 troposphere==2.6.2 twilio==6.45.0 tzlocal==2.1 urllib3==1.25.10 virtualenv==20.0.31 wcwidth==0.2.5 websocket-client==0.57.0 Werkzeug==1.0.1 whitenoise==5.2.0 wrapt==1.12.1 xmltodict==0.12.0 yarl==1.5.1 zipp==3.2.0 I use pyenv for environment. -
how to uplaod image in django rest framework with heroku and aws s3 bucket storage
i am using heroku for my django rest framework project and i am using whitenoise storage but the problem with this is that after image uploading image it is disappear after some time i want permanently image storage with aws s3 bucket help me with that models.py class UploadImage(models.Model): img_id = models.AutoField(primary_key=True) image = models.ImageField(upload_to='media/images/') def __str__(self): return str(self.image) what changes i have to make to use and store the images in aws s3 bucket -
Reverse for '' with arguments '('',)' not found. 1 pattern(s) tried: ['accConnect/setting/(?P<settings_pk>[0-9]+)$']
I am currently running into the above error when trying to render a Model Form. My form looks like this at the moment: Form.py: class SettingUpdateForm(ModelForm): class Meta: model = SettingsClass fields = '__all__' Models.py: Complex = models.CharField(choices=complex_list , max_length = 22 ,default='1' , unique=True) #Trial Balance Year To Date Trial_balance_Year_to_date= models.BooleanField(default = False) tbytd_Include_opening_balances=models.BooleanField(default = False) tbytd_Only_use_main_accounts=models.BooleanField(default = False) tbytd_Print_null_values=models.BooleanField(default = False) tbytd_Print_description=models.BooleanField(default = True) tbytd_Print_account=models.BooleanField(default = True) tbytd_Sort_by_account_name=models.BooleanField(default = True) #Trial Balance Monthly Trial_balance_Monthly=models.BooleanField(default = False) tbm_Only_use_main_accounts=models.BooleanField(default = False) tbm_Print_null_values=models.BooleanField(default = False) tbm_Print_description=models.BooleanField(default = True) tbm_Print_account=models.BooleanField(default = True) tbm_Sort_by_account_name=models.BooleanField(default = True) When the form is trying to render, it gives the following error based on my views.py: Full Error Message: NoReverseMatch at /accConnect/setting/2 Reverse for 'viewSettings' with arguments '('',)' not found. 1 pattern(s) tried: ['accConnect/setting/(?P<settings_pk>[0-9]+)$'] Request Method: GET Request URL: http://localhost:8000/accConnect/setting/2 Django Version: 3.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'viewSettings' with arguments '('',)' not found. 1 pattern(s) tried: ['accConnect/setting/(?P<settings_pk>[0-9]+)$'] Exception Location: C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.4 Python Path: ['C:\\Users\\KylePOG\\Documents\\GMA Programming\\accConnect', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\KylePOG\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Mon, 20 Sep 2021 06:35:19 +0000 Error during template rendering In template C:\Users\KylePOG\Documents\GMA Programming\accConnect\main\templates\main\base.html, error at line 11 Reverse for 'viewSettings' with arguments … -
django: Images(MEDIA) not displaying heroku server
I have developed an ecommerse site using django framework. All the images are uploading through the admin panel.Its works fine locally. But, the images are not loading.Other fuctions are working perfectly. I have installed whitenoise and adds it to setting.py.But,it still not working. settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') Models.py class Product(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False,null=True,blank=True) image = models.ImageField(null=True, blank=True) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',include('store.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) store.html {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> {% for product in products %} <div class="col-lg-4"> <img class="thumbnail" src="{{product.imageURL}}"> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> <button data-product={{ product.id }} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> <a class="btn btn-outline-success" href="#">View</a> <h4 style="display: inline-block; float:right;"><strong>${{product.price|floatformat:2}}</strong></h4> </div> </div> {% endfor %} {% endblock content %} -
Django static files are not loaded on cPanel
I deployed a django app on cPanel. I installed python, django and set the STATIC Variables in settings.py and ran collectstatic. and everything works fine. I get the message in terminal that the static files are copied. but when I launch the application static files are not loaded and gives 404 error. but those static file exists in my public_html folder. I'm really stuck what could be the problem. When i checked the log file I get the following error : /opt/cpanel/ea-ruby24/root/usr/share/passenger/helper-scripts/wsgi-loader.py:26: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses App 2893412 output: import sys, os, re, imp, threading, signal, traceback, socket, select, struct, logging, errno I can see that the error is in wsgi-loader.py file. but I can't find it anywhere on the server. Please help it's taken days for me already. -
Upload multiple photos in Django REST admin panel
I can't find a solution to upload multiple photos to one ImageField in admin panel. I had StackedInline but it's not what I need because there each photo must be upload to new ImageField. I've gone through many questions which might have been close to mine but haven't got a solution yet. Admin panel is pretty much main part of my app. Is is possible to achieve this result in admin panel? This is how I want to see it models.py from django.db import models class User(models.Model): first_name = models.CharField(verbose_name='Имя', max_length=40) last_name = models.CharField(verbose_name='Фамилия', max_length=40) rfid_mark = models.CharField(verbose_name='RFID', max_length=10, editable=True, unique=True) registration_date = models.DateTimeField(verbose_name='Дата регистрации', auto_now=True, editable=False) def __str__(self): return self.first_name + ' ' + self.last_name class UserImage(models.Model): user = models.ForeignKey(User, verbose_name='Пользователь', on_delete=models.CASCADE) photo = models.ImageField(verbose_name='Фото') def __str__(self): return '' -
How to scale mysql table to keep historic data without increasing table size
I have a questionnaire in my app, using which I am creating data corresponding to user who have submitted it and at what time(I have to apply further processing on the last object/questionnaire per user). This data is saved inside my server's MySQL db. As this questionnaire is open for all my users and as it will be submitted multiple times, I do not want new entries to be created every time for same user because this will increase the size the table(users count could be anything around 10M), But I also want to keep the old data as a history for later processing. Now I have this options in mind: Create two tables. One main table to keep new object and one history table to keep history objects. Whenever a questionnaire is submitted it will create a new entry in history table, but update the existing entry in main table. So, is there any better approach to this and how other companies tackle such situations? -
How can I split orders by attributes in my API
I have a method that creates an order from the user's basket. In order for the courier to take an order from different restaurants, the order is divided into several. But at the moment I'm splitting the order just by the dish in the basket. How to make an order split by restaurants, that is, if a user orders 5 dishes from two different restaurants, then 2 orders were formed views.py @action(methods=['PUT'], detail=False, url_path='current_customer_cart/add_to_order') def add_cart_to_order(self, *args, **kwargs): cart = Cart.objects.get(owner=self.request.user.customer) cart_meals = CartMeal.objects.filter(cart=cart) data = self.request.data for cart_meal in cart_meals: order = Order.objects.create(customer=self.request.user.customer, cart_meal=cart_meal, first_name=data['first_name'], last_name=data['last_name'], phone=data['phone'], address=data.get('address', self.request.user.customer.home_address), restaurant_address=cart_meal.meal.restaurant.address, ) order.save() return response.Response({"detail": "Order is created", "added": True}) models.py class Order(models.Model): """User's order""" customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='related_orders') first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) phone = models.CharField(max_length=20) cart_meal = models.ForeignKey(CartMeal, on_delete=models.CASCADE, null=True, blank=True) restaurant_address = models.CharField(max_length=1024, null=True) address = models.CharField(max_length=1024) status = models.CharField(max_length=100, choices=STATUS_CHOICES, default=STATUS_NEW) created_at = models.DateTimeField(auto_now=True) delivered_at = models.DateTimeField(null=True, blank=True) courier = models.OneToOneField('Courier', on_delete=models.SET_NULL, null=True, blank=True) class CartMeal(models.Model): """Cart Meal""" user = models.ForeignKey('Customer', on_delete=models.CASCADE) cart = models.ForeignKey('Cart', verbose_name='Cart', on_delete=models.CASCADE, related_name='related_meals') meal = models.ForeignKey(Meal, verbose_name='Meal', on_delete=models.CASCADE) qty = models.IntegerField(default=1) final_price = models.DecimalField(max_digits=9, decimal_places=2) class Meal(models.Model): """Meal""" title = models.CharField(max_length=255) description = models.TextField(default='The description will be later') price … -
How to create the login and signup urls/views with django rest framework + firebase auth
I was trying to configure django rest framework with firebase auth. I had a look into a few tutorials and firebase doc. So far what I did is, pip install firebase-admin Create Auth class (copied): class FirebaseAuthentication(authentication.BaseAuthentication): def authenticate(self, request): auth_header = request.META.get("HTTP_AUTHORIZATION") if not auth_header: raise APIException("No auth token provided") id_token = auth_header.split(" ").pop() decoded_token = None try: decoded_token = auth.verify_id_token(id_token) except Exception: raise APIException("Invalid auth token") pass if not id_token or not decoded_token: return None try: uid = decoded_token.get("uid") except Exception: raise APIException() user, created = User.objects.get_or_create(username=uid) user.profile.last_activity = timezone.localtime() return user downloaded the config file (Generate new private key) from firebase and add that in settings, cred = credentials.Certificate(os.path.join(BASE_DIR, "firebase_config.json")) firebase_admin.initialize_app(cred) REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'myauth.authentication.FirebaseAuthentication', ] } I am just a bit lost after that. Lets say, I got the uid in an android application. What would be the url or views to login/signup users? Thanks in advance. -
how to screen share using python vidstream onto a django html page?
I am trying to get the python window to show on the django html page but im not sure how to as im new to django. I followed this video "https://www.youtube.com/watch?v=8xy4JKvqsV4" to set up the python script for screen sharing Im running the receiver.py on the linux machine and the sender.py on the windows virtual machine.. receiver.py from vidstream import StreamingServer import threading receiver = StreamingServer('ipaddr', 8080) t = threading.Thread(target=receiver.start_server) t.start() while input("") != 'STOP': continue receiver.stop_server() sender.py from vidstream import ScreenShareClient import threading sender = ScreenShareClient('ipaddr', 8080) t = threading.Thread(target=sender.start_stream) t.start() while input("") != 'STOP': continue sender.stop_stream() -
Tockenizing any model instance in django (DRF)
So i am working with Django and django-rest-knox for token based authentication. It works fine but what i want now is to tokenize any other model instance instead of a user istance. Normal way; from knox.models import AuthToken AuthToken.objects.create(user=myuser) What i tried; AuthToken.objects.create(some_other_model_instace) Which gives an error; AuthToken.user" must be a "User" instance Is there any way to do so? -
Django Makemigrations fails on new autoscaling instances (shows no new changes)
We have a django backend hosted on Autoscaling ec2 instances, and during the deployments it has found that makemigrations and migrate fails (with new models added) when the new ec2 replaces in auto scaling group, as the migrations were done from the old instances, it shows no new migrations on the latest ec2. What could be the efficient solution for this - To have a separate server only for database migrations To push the migrations file directly on git/bitbucket with code so that during deployments new changes are reflected. Is there any other good solutions for this in general? -
How to view contents of one model to another model?
I am doing an Inventory App that let the user add items in the inventory and once added, they can view it in the view page of the app. they can only see it in view only mode. class Inventory(models.Model): last_modified_by = models.ForeignKey(User, on_delete=models.PROTECT) last_modified = models.DateTimeField(auto_now=True) I want to access specific items inside the Inventory Class to another model. for example I want to use last_modified_by inside for instance a Testclass. and last_modifiedin let say anotherTest class. I want to seperate the items in Inventory class in tabs, for example i have a tab inside the Test class and have all the items in it. How can i do this? -
Changing primary key in Django caused constraint does not exist error
I have Django project with DigestIssue model among others and there were Django auto created primary key field id and my field number. I wanted to get rid of duplication and set number as PK because number is unique and with same values as id. But I have foreign keys referencing this model. I doubt that they will migrate automatically after such operation. I tried, hoping for such automigration and got constraint "idx_16528_sqlite_autoindex_gatherer_digestissue_1" of relation "gatherer_digestissue" does not exist error ("sqlite" in constraint name is historical thing, I switched to PostgreSQL a time go). I tried more complicated way, following https://blog.hexack.fr/en/change-the-primary-key-of-a-django-model.html but got same error on PK switching step. So the question is - how to replace in Django old primary key with new one with same values and referenced by other models?