Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to write a file directly to Django FileField?
Is there a way in Python / DJango to write directly to a model's file field? Suppose I have this model # models.py class Registry(models.Model): name = models.CharField(max_length=50, blank=True) form = models.FileField( upload_to='registryform', null=True, blank=True, max_length=500) A normal workflow for generating a file and writing into it is: with open('readme.txt', 'w') as f: f.write('random text') How can I write and save this file to the file field? with open('readme.txt', 'w') as f: # Write to registry.form using f.write -
problem with high usage of CPU in Django and Celery Docker images
I have multi-container application that I am running using Docker. Below is the list of containers I am using: Django-app (postgresql as db and redis as broker) Celery-worker-1 Celery-worker-2 Celery-worker-3 Celery-beats React currently it is stored on S3 bucket. The problem I am facing is that my each celery task is triggering playwright chrominium engine to gather some data frp, websites and the CPU usage of each worker exceeds 200%. Moreover it affects Django app container where CPU usage exceeds 50% if I run more than 8 tasks in celery on localhost. I am aware of the fact that celery has to comunicate with Django somehow therefore the CPU usage might increase but I want to scale up my application and I am trying to figure out how to decrease the CPU usage of each container. I wouldn't bother with CPU usage but when I trigger multiple tasks simutaneously my backend slows down dramatically (I need to wait up to 20 seconds to get any response on localhost). I am planning to use AWS Fargate for my django app and EC2 with auto-scalling enabled for my celery workers and I am worried how this will work if I set up … -
django-filters and django-import-export together
I am facing a problem:I am using django-filters to filter data from my database, and display the result through template. This works fine. At the same time, as an option, I would like export these data to xls format, using django-import-export. What is the best approach? How to pass the queryset(filterset) from django-filters to django-import-export? The FilterView is ok, the rendering to the template is ok. I created the Resources from django-import-export, but i can't populate the queryset Thank you for your advice -
Controlling order of evaluation in Django templates
I'm wanting to dynamically make bootstrap columns. I have the following snippet of code: {% with footer_items=settings.site_settings.SiteSettings.footer_menu_items.all %} {% with item_len=footer_items|length %} {% with item_columns=12|divide:item_len %} {% for block in footer_items %} <div class="col-md-{{ item_columns|maximums:3 }}"></div> {% endfor %} {% endwith %} {% endwith %} {% endwith %} Now, with these 3 with statements, it looks pretty ugly, and you can barely understand what it does. Now I am wondering, can this be trimmed down into the following statement somehow? (Is it possible to control the control-flow of evaluation in django templates?) {% with footer_items=settings.site_settings.SiteSettings.footer_menu_items.all %} {% for block in footer_items %} <div class="col-md-{{ (12|divide:(footer_items|length))|maximums:3 }}"></div> {% endfor %} {% endwith %} -
Delete the zip file from the server after the user downloads the file in Django
I want to delete the generated zipfile from the server, after the end user downloads it into the local system in Django Python web application. My question is similar to this question asked already by another user But, the solution suggested on that link shared above requires me to import a this line: from webapp.celery import app I am not sure how to install this library? Any idea on this how to make use of the suggested solution on the link Thank you. -
Why are SQL fields not visible?
I created a CRM Application and while running the code in localhost using local database. All the fields are visible but when I deployed the django app and used the Postgre or MySQL. The leads are not visible. `views.py:- from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages from .forms import * from .models import * from django.contrib.auth.models import Group from django.contrib.auth.decorators import login_required,user_passes_test from django.views.decorators.csrf import csrf_exempt # users_in_group1 = Group.objects.get(name="MARKETING").user_set.all() # users_in_group2 = Group.objects.get(name="TECHNICAL").user_set.all() @csrf_exempt def technicalregister_user(request): if request.method == 'POST': form = TechnicalSignUpForm(request.POST) if form.is_valid(): form.save() # Authenticate and login username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) technical_group = Group.objects.get_or_create(name='TECHNICAL') technical_group[0].user_set.add(user) login(request, user) messages.success(request, "You Have Successfully Registered! Welcome!") return render(request, 'adminhome.html') else: form = TechnicalSignUpForm() return render(request, 'technicalregister.html', {'form':form}) return render(request, 'technicalregister.html', {'form':form}) @csrf_exempt def register_user(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() # Authenticate and login username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) marketing_group = Group.objects.get_or_create(name='MARKETING') marketing_group[0].user_set.add(user) login(request, user) messages.success(request, "You Have Successfully Registered! Welcome!") return render(request, 'adminhome.html') else: form = SignUpForm() return render(request, 'register.html', {'form':form}) return render(request, 'register.html', {'form':form}) def is_marketing(user): return user.groups.filter(name='MARKETING').exists() def is_technical(user): return user.groups.filter(name='TECHNICAL').exists() @csrf_exempt def … -
How to write output of PyPDF to Django File field?
I am generating a PDF file after a Model instance is created. I am using pypdf to read, modify, and write the file. I want to save this file to a file field in my Model instance. # models.py class Registry(models.Model): name = models.CharField(max_length=50, blank=True) form = models.FileField( upload_to='registryform', null=True, blank=True, max_length=500) I start the operation in signals when I post_save the model instance. Later on, I will make this task asynchronous. But for now, here is the task snippet. # signals.py @receiver(post_save, sender=Registry) def create_registry(sender, instance=None, **kwargs): form = generate_new_space_object_registration_form( instance=instance.__dict__, id=instance.pk ) # tasks.py def generate_new_registration_form(instance, registry_id): """ some operation """ with open("registry/data/test.pdf", "wb") as output_stream: #writer.write(output_stream) registry.form.save('test.pdf', File(output_stream)) I have this exception raised. Exception Type: UnsupportedOperation Here is the complete log: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.9/site-packages/django/contrib/admin/options.py", line 686, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/utils/decorators.py", line 133, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/views/decorators/cache.py", line 62, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 242, in inner return view(request, *args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1893, in change_view return self.changeform_view(request, object_id, form_url, … -
Why does I can't log out even if it works on server-side in Django React
I'm new to Django and React and I tried to create auth system. Register and Log In work fine both in server-side and client-side but the Log out one didn't. When I send POST method from React it said "POST http://127.0.0.1:8000/user/logout 403 (Forbidden)" even if it works in Django So this is my UserLogOutView of user app in Django class UserLogOutView(APIView): def post(self, request): logout(request) return Response(status=status.HTTP_200_OK) and then urls.py urlpatterns = [ ... path('logout', views.UserLogOutView.as_view(), name='logout'), ] next I send POST method through axios like this in my react component. const submitLogout = () => { axios .post( "http://127.0.0.1:8000/user/logout", ) .then(response => { console.log(response); }) .catch(error => { console.log(error); }); } const handleClickLogOut = (e) => { e.preventDefault(); submitLogout(); props.onClose(false); }; and use it like this. <form onSubmit={e => handleClickLogOut(e)}> <button className='font-bold text-[20px]'>Log Out</button> </form> I also set the CSRF token in Axios headers in that file. axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; axios.defaults.withCredentials = true; any suggestion? -
How to retrieve data from a file (specifically a model in Django) located on another branch on github on the current branch?
I need help working with github - I'm working on a project in Django REST and I've created a new branch that contains a segment of the project. Since I need a Django model that is part of another branch (but also on the master branch because that branch is merged with master), I'm wondering how I can get it to use it on this current branch that I need it on as well? Since it is also a SQL table, I need that model to be the same wherever I use it, I will only possibly take new data. Thank you in advance! -
django trying to install jazzmin and after installing i am getting error "'User' object has no attribute 'get_all_permissions'"
in setting.py INSTALLED_APPS = [ 'jazzmin', 'django.contrib.admin', 'django.contrib.auth',tag-name 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'customer' ] AUTH_USER_MODEL = 'app.User' -
Django session timeout issue
I have implemented django-session-timeout using the following library. Timeout has been configured for 900 seconds. A session timeout page is displayed when after 900 seconds of inactivity. The problem I am facing is, whenever user opens the link for second time, a session timeout page is displayed. Assumption: Cookies from earlier session has not been cleared. I have tried request.session.flush() before the page loads but it doesn't work. The user is being forced to open the link twice as a temporary solution. Need a permanent solution. -
FileNotFoundError in subprocess.py(which is called internally not explicitly)
My cmd keeps on throwing error saying "FileNotFoundError: [WinError 2] The system cannot find the file specified" whenever I try to run "python manage.py runserver" command for my django app. I have uninstalled and reinstalled python due to this issue for several times, I'm afraid if that's what is causing this issue. Not only my django code, but my pip isn't working properly and IDLE isn't opening. I've searched the whole internet for an answer yet I don't have one. Kindly help me out. Iam using a Windows 7, 32-bit, 2gb ram, low level system for my development (MGcloud) D:\Django\MGcloud\MGcloud>python manage.py runserver 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 "D:\Django\MGcloud\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_comma utility.execute() File "D:\Django\MGcloud\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Django\MGcloud\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "D:\Django\MGcloud\lib\site-packages\django\core\management\commands\runserver.py", line 74, in execute super().execute(*args, **options) File "D:\Django\MGcloud\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "D:\Django\MGcloud\lib\site-packages\django\core\management\commands\runserver.py", line 111, in handle self.run(**options) File "D:\Django\MGcloud\lib\site-packages\django\core\management\commands\runserver.py", line 118, in run autoreload.run_with_reloader(self.inner_run, **options) File "D:\Django\MGcloud\lib\site-packages\django\utils\autoreload.py", line 682, in run_with_reloader exit_code = restart_with_reloader() File "D:\Django\MGcloud\lib\site-packages\django\utils\autoreload.py", line 274, in restart_with_reloader p = subprocess.run(args, env=new_environ, close_fds=False) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\Lib\subprocess.py", line 488, … -
How to handle object does not exist of get_object in Django REST?
In my Django views, I call the get_object method to query a record that exist to user types. There can be instances where a user would get none or empty. I call this method to several other methods such as get, patch, etc. from rest_framework.generics import GenericAPIView from django.core.exceptions import ValidationError class FooViewSet(GenericAPIView): def get_object(self, pk): try: foo = Foo.objects.get(pk=pk) return foo except Foo.objects.DoesNotExist: raise ValidationError('Foo Does Not Exist') def get(self, request, pk, format=None): obj = self.get_object(pk) return Response({}) def patch(self, request, pk, format=None): obj = self.get_object(pk) return Response({}) def delete(self, request, pk, format=None): obj = self.get_object(pk) return Response({}) I am trying to catch if the object does not exist and throw a ValidationError but I get this error instead: catching classes that do not inherit from BaseException is not allowed How to correctly throw an error if an object does not exist with a URL query parameter such as this implementation? -
Is it really impossible to expectedly run the code with "{% if %}", "{% with %}" and "{% translate %}" outside of "{% block %}" in Django Templates?
I have base.html below: # "templates/base.html" {% block content %}{% endblock %} And, I have index.html which extends base.html as shown below: # "templates/index.html" {% extends "base.html" %} Then, I use {% if %} which is False outside of {% block %} in index.html as shown below but Hello World is displayed unexpectedly: # "templates/index.html" {% extends "base.html" %} {% if False %} {% block content %} Hello World {% endblock %} {% endif %} So, I use {% if %} inside of {% block %}, then Hello World is not displayed expectedly: # "templates/index.html" {% extends "base.html" %} {% block content %} {% if False %} Hello World {% endif %} {% endblock %} Also, I use {% with %} which defines name variable outside of {% block %} in index.html as shown below but John is not displayed unexpectedly: # "templates/index.html" {% extends "base.html" %} {% with name="John" %} {% block content %} {{ name }} {% endblock %} {% endwith %} So, I set {% with %} inside of {% block %}, then John is displayed expectedly: # "templates/index.html" {% extends "base.html" %} {% block content %} {% with name="John" %} {{ name }} {% endwith %} … -
Can't Migrate Postgresql DB for Azure Django App
I was following the tutorial located here: https://testdriven.io/blog/django-azure-app-service/ and i made it all the way to opening up the SSH cli and typing the command "python manage.py migrate", but when i enter this i get the exception: django.db.utils.OperationalError: could not translate host name "mydbname port=5432" to address: Name or service not known When i scroll up a little i read that this error was the direct result of the following exception: psycopg2.OperationalError: could not translate host name "mydbname port=5432" to address: Name or service not known I've checked my settings.py and my azure configs to make sure the info is correct. I'm at a complete loss, does anyone know what may be causing these exceptions to be thrown? My application is deployed, I'm guessing I just can't connect to my postgresql database for some reason. -
AbstractUser Blocks Admin Page
does anyone know why the AbstractUser I created in Django stops me from accessing the Django Admin page? I think it has something to do with the AUTH_USER in my settings.py but am not sure how to remedy this. The goal here, which I did successfully was add a boolean field to the regular Django log on. models.py from django.db import models from django.contrib.auth.models import AbstractUser class NewUser(AbstractUser): terms_cond_box = models.BooleanField() # I don't see a difference with TvsF. forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import NewUser class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) terms_cond_box = forms.BooleanField() class Meta: model = NewUser fields = ("username", "email", "password1", "password2", "terms_cond_box", ) def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user urls.py from django.urls import path from . import views #from django.contrib.auth import views as auth_views urlpatterns = [ path('', views.welcome, name='welcome'), path('base', views.base, name='base'), path('loginpage', views.loginPage, name='login_user'), path('logout', views.logoutUser, name='logout'), # path('register_user', views.register_user, name='register_user'), path('userhomepage', views.userHomepage, name='user-homepage'), path('register', views.register, name='register'), ] views.py from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth import login from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.core.mail import send_mail, BadHeaderError from … -
Python Django Docker - You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path
I'm running a Django application via Docker. How do I get past the following error message: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. I do have STATIC_ROOT declared in my settings.py file import environ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent env = environ.Env() env_path = BASE_DIR / ".env" if env_path.is_file(): environ.Env.read_env(env_file=str(env_path)) ... STATICFILES_DIRS = [BASE_DIR / "static"] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') ... Some web searching led me to believe the settings.py file isn't even being referenced, but I could be wrong. I think that's shown in the manage.py file below. #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_aws.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() The files are created in Windows, but the Docker container is not running Windows. I was getting some errors related … -
Sending data from Django to Unity using Websocket-Sharp
I want to send data via Websocket from my django server to my unity game. The websocket connect and disconnects corectly, but i can't send any data to unity. In django consumers.py I have this: class SensorDataConsumer(AsyncWebsocketConsumer): async def connect(self): print("connected") await self.accept() async def disconnect(self, close_code): print("disconnected") pass async def receive(self, text_data): # Process the received message from Unity if needed print("received") pass async def send_data(self, event): message = event['message'] print("Sending data:", message) await self.send(text_data=message) In routing.py I have this: websocket_urlpatterns = [ re_path(r'ws/sensordata/$', SensorDataConsumer.as_asgi()), ] I set the asgi like this: application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter(websocket_urlpatterns) }) When the game starts, i connect the websocket. When the method send_sensor_data from views.py is called, i want to send the data to unity. I have this code for the method: @api_view(['POST']) def send_sensor_data(request): sensor_data_consumer = SensorDataConsumer() async_to_sync(sensor_data_consumer.send_data({'message': 'Hello, world!'})) return Response({'success': True}) In Unity, I have a script for websocket: public class SensorDataReceiver : MonoBehaviour { private WebSocket ws; void Start() { ws = new WebSocket("ws://192.168.1.5:8000/ws/sensordata/"); ws.OnMessage += OnMessageReceived; ws.Connect(); } void OnMessageReceived(object sender, MessageEventArgs e) { // Handle the received message here Debug.Log("Received message: " + e.Data); } void OnDestroy() { if (ws != null) { ws.OnMessage … -
How to log out all users after server stops running in django
I am building a website with Django. I have created users using the built-in django user model. I have a login page where each user can login as well as a button to logout. I want to automatically log out the user that is logged in when I stop the runserver command. This is what I've tried so far but it is not working: myapp/signals.py from django.contrib.auth import logout from django.core.signals import request_finished from django.dispatch import receiver @receiver(request_finished) def handle_server_shutdown(sender, **kwargs): logout() myproject/init.py import myapp.signals -
Problem running PHP in a Django app with Apache
I have a web app running in Django which mainly consists of HTML and JavaScript (which is running with no issues) but recently a colleague created some additional content that is implemented PHP. The web page is served by Apache which is configured to accept .-h- files which it executes correctly. The problem I’m seeing is that there is an HTML file that generates a form with a few fields and a submit button which has the PHP file as it’s action like this: <form id=“form1” action=“generator.php” method=“post”> . . . <input type=“submit” name=“submit” value=“Generate”> </form> The .php file can be simplified as: <!DOCTYPE html> <html lang=“en”> <head> <meta http-equiv=“Content-Type” content=“text/html”; charset=utf-8” /> </head> <body> <?php echo “Generating” ?> </body> </html> When the submit (Generate) button is pressed, the network debugging window in the browser shows that generator.php is indeed loaded but the echo statement isn’t executed. The PHP part of the application is non-negotiable much to my chagrin. If there needs to be more information please let me know. -
I am having a hard time designing the relationships for my nursery management system using django
This is part of a university project I assigned the data fields I need for the database tables but the relationships are giving me errors that I'm having a hard time designing them properly as I am a beginner This contains all the models needed in my project from django.db import models from django.core.validators import EmailValidator, MaxValueValidator, MinValueValidator email_validator = EmailValidator(message='Please enter a valid email address') max_score = MaxValueValidator( 100, message='Please enter a number less than 100') min_score = MinValueValidator(0, message='Please enter a number above 0') class Quiz(models.Model): number = models.IntegerField(default=0) score = models.IntegerField(validators=[max_score, min_score]) students = models.ForeignKey( 'Student', on_delete=models.PROTECT, default=None) def __str__(self): return f"Quiz {self.number}" class Subject(models.Model): name = models.CharField(max_length=50) teachers = models.ForeignKey( 'Teacher', on_delete=models.PROTECT, default=None) students = models.ForeignKey( 'Student', on_delete=models.PROTECT, default=None) quizzes = models.ForeignKey('Quiz', on_delete=models.CASCADE, default=None) def __str__(self): return f"{self.name}" class Branch(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=255) teachers = models.ForeignKey( 'Teacher', on_delete=models.PROTECT, default=None) students = models.ForeignKey( 'Student', on_delete=models.PROTECT, default=None) def __str__(self): return f"{self.name}" class Teacher(models.Model): GENDER_MALE = 'M' GENDER_FEMALE = 'F' GENDER_OPTIONS = [ (GENDER_MALE, 'Male'), (GENDER_FEMALE, 'Female') ] first_name = models.CharField(max_length=50) second_name = models.CharField(max_length=50) date_of_birth = models.DateField() gender = models.CharField( max_length=1, choices=GENDER_OPTIONS, default=GENDER_MALE) phone = models.CharField(max_length=11) address = models.CharField(max_length=255) email = models.EmailField(validators=[email_validator]) def __str__(self): return f"{self.first_name} … -
Wrong Authentication
I'm doing a college project, and the bakery has to make the subscription plans, but only they can create, edit and delete the plans. Here below is the class: class PlanoAssinaturaView(APIView): @permission_classes([IsAuthenticated]) def post(self, request): padaria = request.user if not isinstance(padaria, Padaria): return Response( {'error': 'Acesso não autorizado.'}, status=status.HTTP_401_UNAUTHORIZED ) serializer = PlanoAssinaturaSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request): planos = PlanoAssinatura.objects.all() serializer = PlanoAssinaturaSerializer(planos, many=True) return Response(serializer.data) I'm using INSOMNIA and every time I pass the valid JWT TOKEN it enters the IF, so I wanted help identifying the error. insertion of data HEADERS -
Can I use a jsonpath predicate in a filter?
I have a model with a JSONField and need to select just the objects that have a certain value somewhere nested in the jsonb. From the Django documentation I understand you can use contains but the Postgres @> operator for containment does not recurse into the structure. I'd like to use @? '$.** ? (@.mykey == "myValue")' to filter. myKey and myValue are literals in my code, they are not user input. -
Connecting to Heroku ClearDB MySQL database gives me "positional arguments" error
I just created a Python/Django project with a MySQL database that I am trying to host on Heroku. I added a ClearDB database to my Heroku project, but when I try to migrate my database, it gives me this error: DatabaseWrapper.display_name() takes 0 positional arguments but 1 was given I get the gist of this error, but unfortunately I can't seem to be able to trace the problem back to its source to fix it. Here is my database configuration in my settings.py file: DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS'), 'HOST': os.environ.get('DB_HOST'), 'PORT': '3306', 'OPTIONS': { "use_pure": True } } } And, here is my requirements file: amqp==5.1.1 asgiref==3.5.2 async-timeout==4.0.2 billiard==3.6.4.0 celery==5.2.7 charset-normalizer==3.0.1 click==8.1.3 click-didyoumean==0.3.0 click-plugins==1.1.1 click-repl==0.2.0 colorama==0.4.6 dj-database-url==2.0.0 Django==4.1.3 django-celery-results==2.4.0 django-jsonfield==1.4.1 django-mathfilters==1.0.0 djangorestframework==3.14.0 jsonfield==3.1.0 kombu==5.2.4 mysql==0.0.3 mysql-connector-python==8.0.33 mysqlclient==2.1.1 numpy==1.23.4 pathlib==1.0.1 pdf2image==1.16.2 Pillow==9.3.0 prompt-toolkit==3.0.36 protobuf==3.20.3 PyMySQL==1.0.3 pypdf==3.3.0 PyPDF2==3.0.1 python-dotenv==1.0.0 pytz==2022.7.1 redis==4.5.0 reportlab==3.6.12 simplejson==3.18.1 six==1.16.0 sqlparse==0.4.3 typing_extensions==4.5.0 tzdata==2022.6 urllib3==1.26.14 vine==5.0.0 wcwidth==0.2.6 I found another post regarding this on reddit, and it told me: are you using mysql-connector-python? if so, downgrade to 8.0.29, there's a bug in 8.0.30 and later that breaks compatibility with the django app. but unfortunately this will not help as I … -
How to make correct many-to-many link between ingredients and dishes?
I have ingredients (for example, chicken and potatoes) with their amounts in storage. And i have have a dish, which consists of 100g of chicken and 200g of potatoes. I guess classes should look like: class Ingredients(models.Model): name = models.CharField(max_length=30) amount = models.IntegerField() class Dish(models.Model): name = models.CharField(max_length=30) ingredients = models.ManyToManyField(Ingredients) amount = ???? So the question is how to give certain amount to certain ingredient? I don't really know how to solve it