Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: While keeping debug=True APIs are running faster
I have observed that our production environment is slow while keeping debug=False We need to wait 20s or 15 sec for one API response. The same API's are performing in milliseconds, only we changed debug=True -
"error": "invalid_client" while using Django OAuth toolkit
I was following the steps mentioned in the documentation for django rest framework. I'm not able to proceed from step 4. As mentioned in the documentation, curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/ I have changed the above variables with my values. curl -X POST -d "grant_type=password&username=admin&password=admin123" -u "5hKeHNtF3EKy3uCpJqaAe3mU2bGZTgJhsKKxIuAQ:pbkdf2_sha256$390000$VFcCOjIZkBFObellddDgKA$DXovC1UiuxRQ0KN/lARIdQmXcj8dnoJofkznmkkqsZY=" http://localhost:8000/o/token/ I tried to import the curl on postman and Im getting this error Then I tried running the curl on Insomnia testing tool, and I got the request configured as in the screenshot. Then I click send and I got an error SO i changed 'Content-Type' to 'Form URL Encoded' Now I'm geting an error { "error": "invalid_client" } I'm stuck with this and don't know how to proceed with this. Please lend me a hand. Thanks in advance... -
ValueError at / Field 'id' expected a number but got 'srednje'
I have django application. I want user to type url with name of certain article in browser and then they will see all products linked to this article. My models look like this: class Article(models.Model): slug = models.SlugField(unique=True, null=True) title = models.CharField(max_length=20, null=True) def __str__(self): return self.title class Product(models.Model): name = models.CharField(max_length=20) # price = models.IntegerField() description = models.CharField(max_length=400) a_article = models.ForeignKey(Article, on_delete=models.CASCADE, null=True) And I try to get this work in my view: def product(request, pk): product = models.Product.objects.filter(a_article=pk) return render(request, 'product.html') Since I passed pk in my function I put it in urls as well: path('<str:pk>/', views.product, name='product'), When I run this and get on url: http://127.0.0.1:8000/srednje/ I get an error: ValueError at /srednje/ Field 'id' expected a number but got 'srednje'. I think this is probably somehow linked to primary key or foreign key but how and how can I change this to work? -
when deploying Django project to Linux server (Getting static files errors)
Hi Team please find the below settings file. i am trying to deploy the django project to linux server but getting below error: Bad Request (400) from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'admin_interface', 'colorfield', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'employee', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': str(BASE_DIR / 'db.sqlite3'), } } # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' #Please advise if we need to change the below _DIRS STATICFILES_DIRS = (os.path.join('employee/static') Error: Found another file with the destination path 'css/mystyle.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Please advise if any changes are required. -
Django bulk_create using a list of random fields without a hardcoded query
I am trying to create new instances in my Django model using bulk_create(). My models are: Class Emotion(models.Model): emotion_grp_id = models.AutoField(primary_key=True, ... emotion_group = models.CharField(max_length=55, ... Class EmotionSubGroup(models.Model): emotion_sub_grp_id = models.AutoField(primary_key=True, ... emotion_grp = models.ForeignKey(EmotionGroup, on_delete=models.CASCADE, ... emotion_sub_group = models.CharField(max_length=55, ... views.py The relevant portion of the function that I am using looks like this: def DataUpload (request): # ... # ... df_rawdata = pd.read_csv(csv_file, sep=''). # Dataframe from source (.csv) file row_iter = df_rawdata.iterrows() data = [ EmotionSubGroup( emotion_grp_id=row['emotion_grp'], emotion_sub_group=row['emotion_sub_group'], ) for index, row in row_iter ] EmotionSubGroup.objects.bulk_create(data) Is it possible to create a general data structure instead of hardcoding the field names, for example: data = `list_of_target_fields = rows_from_external_source` to be equivalent of what I am using currently and carry out the upload. -
TypeError: cannot pickle '_io.BufferedReader' object when sending e-mail with Django-mailer and Djoser
The problem I'm trying to send a Djoser user's activation email using django-mailer. However, I receive the following error: TL;DR: TypeError: cannot pickle '_io.BufferedReader' object FULL: Traceback (most recent call last): File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/rest_framework/mixins.py", line 19, in create self.perform_create(serializer) File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/djoser/views.py", line 144, in perform_create settings.EMAIL.activation(self.request, context).send(to) File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/templated_mail/mail.py", line 78, in send super(BaseEmailMessage, self).send(*args, **kwargs) File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/core/mail/message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/backend.py", line 15, in send_messages messages = Message.objects.bulk_create([ ^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/backend.py", line 16, in <listcomp> Message(email=email) for email in email_messages ^^^^^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/django/db/models/base.py", line 554, in __init__ _setattr(self, prop, value) File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/models.py", line 150, in _set_email self.message_data = email_to_db(val) ^^^^^^^^^^^^^^^^ File "/Users/joaoalbuquerque/pyenv/versions/3.11.0/envs/garvy/lib/python3.11/site-packages/mailer/models.py", line 94, in email_to_db return base64_encode(pickle.dumps(email)).decode('ascii') ^^^^^^^^^^^^^^^^^^^ TypeError: cannot pickle '_io.BufferedReader' object Internal … -
Django request.POST returning NONE
I have been working on a Django REST API and one of the views is as follows : @api_view(['POST']) def create(request): key = request.POST.get('key') name = request.POST.get("name") email = request.POST.get("email") password = request.POST.get("password") print(key) if(key=='0'): user = Users(name=name,email=email,password=password) user.save() return Response("User Created Successfully") else: return Response("Invalid Key") When I send a POST request with all the proper parameters I get the key printed as NONE, but I tried replacing POST with GET every where as below and then sending a GET request actually works normally, but POST request isn't working : @api_view(['GET']) def create(request): key = request.GET.get('key') name = request.GET.get("name") email = request.GET.get("email") password = request.GET.get("password") print(key) if(key=='0'): user = Users(name=name,email=email,password=password) user.save() return Response("User Created Successfully") else: return Response("Invalid Key") Thanks in advance !! Tried GET instead of POST and that works, but since this is a method to enter value in the DB so this should be POST request. -
ModuleNotFoundError: No module named 'celery'
I'm sure that I have installed celery using pip install celery. I am running my Django application on Docker. When I run the command docker compose up, it shows the error. File "<frozen importlib._bootstrap>", line 1206, in _gcd_import batch_email-web-1 | File "<frozen importlib._bootstrap>", line 1178, in _find_and_load batch_email-web-1 | File "<frozen importlib._bootstrap>", line 1128, in _find_and_load_unlocked batch_email-web-1 | File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed batch_email-web-1 | File "<frozen importlib._bootstrap>", line 1206, in _gcd_import batch_email-web-1 | File "<frozen importlib._bootstrap>", line 1178, in _find_and_load batch_email-web-1 | File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked batch_email-web-1 | File "<frozen importlib._bootstrap>", line 690, in _load_unlocked batch_email-web-1 | File "<frozen importlib._bootstrap_external>", line 940, in exec_module batch_email-web-1 | File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed batch_email-web-1 | File "/Batch_Email/Batch_Email/__init__.py", line 1, in <module> batch_email-web-1 | from .celery import app as celery_app batch_email-web-1 | File "/Batch_Email/Batch_Email/celery.py", line 4, in <module> batch_email-web-1 | from celery import Celery batch_email-web-1 | ModuleNotFoundError: No module named 'celery' Before installing celery the command docker compose up would run the Django server. I have installed Redis for using celery. Why am I getting this error and how can I fix it? -
how to delete token django rest framework simple jwt
Currently users are being issued a new token each time they login in, so there are several outstanding tokens linked to each user. This means the user cannot be deleted. How can I delete tokens? I'm looking for resources rather than help with coding please. -
Are there any benefits of havin CharField defined smaller than little larger?
Let's assume that in some particular case I know that I will need CharField for single words. I wonder does the length of CharField influences the performance of the query, or the size of DB when it's defined as bigger. In this case, I assume that all data fit the size of CharField because - let's assume - that in every row in the column each cell has a word with length 3. For example: What changes when I define the length of CharField to 3, or 250? I'm aware that there are (many) other reasons to define CharFiled in some way (define a particular allowed range), but are there any reasons to try to make the available range smaller for the sake of performance or the size of DB? Is it worth considering and if so, when? Would it be the same for SQLite and PostgreSQL? -
Django Form as a Table
The following code in the django template language is working but i don't know why. The purpose of this code is to display a form as a table with a number of columns. The first thing that throws me of is that the tag for opening a row is never giving but it is still made. {% extends 'base.html' %} {% load render_table from django_tables2 %} {% block content %} <form method="get"> {% csrf_token %} <table> <tbody> {% for field in filter.form %} <td>{{ field.label}}</td> <td>{{ field }}</td> {% if forloop.counter|divisibleby:"4"%} </tr> {% endif %} {% endfor %} </tbody> </table> <input type="submit" value="Search"> </form> {% render_table table%} {% endblock %} This generates a four column table. Is there any way the opening tags can be explicitly declared?And why is this code working? I have tried to explicitly create the tags for row explicitly but this didn't not create the table correctly.It had an empty row space and a extra row. {% extends 'base.html' %} {% load render_table from django_tables2 %} {% block content %} <form method="get"> {% csrf_token %} <table> <tbody> {% for field in filter.form %} {% if forloop.counter|divisibleby:"5"%} <tr> {% endif %} {% if forloop.counter|divisibleby:"5" == False %} … -
Can't deploy two different website on the same ubuntu server using nginx
I have two different django website that I want to deploy on my linux server with two different domain but it not working. Only one of the two website is working (the first website). And when I go the the second domain url it point to the first website application (both domain are pointed correclty to the server) First website: Folder name = mysite domain name = www.firstwebsite.com Second Website: Folder name = mysite2 domain name = www.secondwebsite.com sudo vim /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock Environment="PATH=/usr/bin:/home/tiber/mysite/env/bin" [Install] WantedBy=sockets.target sudo vim /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=tiber Group=www-data WorkingDirectory=/home/tiber/mysite ExecStart=/home/tiber/mysite/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ mysite.wsgi:application [Install] WantedBy=multi-user.target I have a different config file for each project so first project is /etc/nginx/sites-available/mysite and second is /etc/nginx/sites-available/mysite2 Here is the config of the second project cause that the one who is not working properly server { listen 80; server_name www.secondwebsite.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/mysite2; } location /media/ { root /var/www/mysite2; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
intern_profile_view() missing 1 required positional argument: 'request'
Can anyone tell me what I've done wrong? I'm trying to create a simple multi users app in django and I can't quite tell what I'm missing in my view. Here's what I have so far. views.py @method_decorator([login_required, intern_required], name='dispatch') def intern_profile_view(request): if request.method == 'POST': user_form = InternSignUpForm(request.POST, prefix='UF') profile_form = InternProfileForm(request.POST, prefix='PF') if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) user.save() user.intern_profile.bio = profile_form.cleaned_data.get('bio') user.intern_profile.location = profile_form.cleaned_data.get('location') user.intern_profile.save() else: user_form = InternSignUpForm(prefix='UF') profile_form = InternProfileForm(prefix='PF') return render(request, 'interns/intern_profile.html',{ 'user_form': user_form, 'profile_form': profile_form, }) models.py class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_intern = models.BooleanField(default=False) class InternProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='intern_profile') bio = models.CharField(max_length=30, blank=True) location = models.CharField(max_length=30, blank=True) traceback Traceback (most recent call last): File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mikha\issue_env\lib\site-packages\django\utils\decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) TypeError: intern_profile_view() missing 1 required positional argument: 'request' urls.py path('interns/', include(([ path('', interns.intern_profile_view, name='intern_profile'), ], 'classroom'), namespace='interns')), -
Django ORM, how to "rebase" a QuerySet to a related model
With a database model described in the simplified toy example below, we are trying to get a list of EAV attributes used a specific Product. The "Actions" below do the above purpose; however, we feel the statement is overly complicated: The Python expression starts from the template variable but the values arguments still need to maintain a full qualified path starting from the original Product model. Instead of attribute_set = template. Values("id", "template__id", "template__templateattribute__id"), we wonder if there is a way to refer to the columns like templateattribute__id, in a way like "rebased" to the related model. We appreciate any hints or suggestions. ** Actions: ** template = Product.active_objects.filter(id='xxx').select_related('template') attribute_set = template. Values("id", "template__id", "template__templateattribute__id") for i, attr in enumerate(attribute_set): print("{:03}: {}".format(i, attr)) # Output: # Output: # 000: {'id': xxx, 'template__id': xxxx, 'template__templateattribute__id': xxxxx} # 001: {'id': xxx, 'template__id': xxxx, 'template__templateattribute__id': xxxxx} # 002: {'id': xxx, 'template__id': xxxx, 'template__templateattribute__id': xxxxx} # ... ** Sample source code: ** # Simplified toy example class Product(models.Model): product_template = models.ForeignKey(Template) sku = models.CharField(max_length=100) ... class Template(models.Model): base_sku = models.CharField(max_length=100) ... class TemplateAttribute(models.Model): product_template = models.ForeignKey(Template) attribute = models.ForeignKey(eav_models.Attribute) ... # From the open source Django EAV library # imported as `eav_models` # class … -
PythonConsole Pycharm error: django.core.exceptions.ImproperlyConfigured: DJANGO_SETTINGS_MODULE
Using PyCharm Communuty: trying to run my PyCharm console with folowing code to do some tests but unfortunately facing the problem described below. Really appreciate your attention from django.db import models # Create your models here. class ProductCategory(models.Model): name = models.CharField(max_length=128, unique=True) description = models.TextField(null=True, blank=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=256) description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) quantity = models.PositiveIntegerField(default=0) image = models.ImageField(upload_to='products_images') category = models.ForeignKey(to=ProductCategory, on_delete=models.CASCADE) Then trying to run PyCharm console and execute the folowing line: from products.models import ProductCategory Then getting error: Traceback (most recent call last): File "/snap/pycharm-community/310/plugins/python-ce/helpers/pydev/pydevconsole.py", line 364, in runcode coro = func() File "<input>", line 1, in <module> File "/snap/pycharm-community/310/plugins/python-ce/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) File "/home/verts/Documents/Last/course/store-server/store/products/models.py", line 5, in <module> class ProductCategory(models.Model): File "/home/verts/Documents/Last/course/store-server/store/venv/lib/python3.9/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/home/verts/Documents/Last/course/store-server/store/venv/lib/python3.9/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/home/verts/Documents/Last/course/store-server/store/venv/lib/python3.9/site-packages/django/apps/registry.py", line 135, in check_apps_ready settings.INSTALLED_APPS File "/home/verts/Documents/Last/course/store-server/store/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/verts/Documents/Last/course/store-server/store/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 63, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. App 'products' is registered in settings .. :( -
django doesn't recongnise my apps on the INSTALLED APPS in setting.py after saving them there and I can't applied migrations on them
I started a project in Django and I started apps with python manage.py startapp "AppName". Then runserver and got "You have 17 unapplied migrations, run migrate to apply them. I saved my apps on the INSTALLED APPS in settings.py of my project. then if i makemigrations i get this "No changes detected" then if run the manage.py migrate i get this "Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply." NO migrations was applied on my apps. Even when i run python manage.py makemigration "AppName" i get this 'No installed app with label "AppName"'. I stuck here for weeks now and i don't know what to do. I have set up my venv, python paths in E.Variables and even virtualenvwrappers. Is there anything that's missing out what are the possible causes of this problem.... I have tried changing my folder paths, Installing python in the new folder paths i changed for my projects. -
Page loader while retrieving data from a PostgreSQL database in Django
I'm using Django with a PostgreSQL database to create a website for entering and viewing data. On the data viewing page there are several tables that are populated with data from the database. I'm trying to implement a page loader that will display until the data has been retrieved from the database and the webpage is fully loaded. At the moment, the page loader does not appear until after the data is retrieved and then only flashes briefly while the page fully loads. How can I make it appear from when I first click on the link to go to the page? Here is my html: <div id="page-loader"> <div class="loader-spinner"></div> <p class="loader-message">Loading...</p> </div> My CSS: #page-loader { display: flex; align-items: center; justify-content: center; width: 300px; z-index: 999999; background-color: rgba(75, 75, 75, 0.75); border-radius: 10px; } .loader-spinner { width: 50px; height: 50px; border: 2px solid #FC6620; border-radius: 50%; border-top: 2px solid #fff; animation: spin 1s linear infinite; margin: 0; z-index: 999999; } @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .loader-message { margin-left: 10px; font-size: 24px; color: #FC6620; z-index: 999999; } and my Javascript: document.addEventListener('readystatechange', () => { document.getElementById("page-loader").style.display = "visible"; }) window.onload = function() … -
Error when trying to save a form in django
I am new to django and I am working on a project whereby users fill a form from frontend and the data is saved to a gig model where the writer extends from a profile foreignkey. The error says ValueError at /seller_profile/ The Gig could not be created because the data didn't validate. Here is the models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='avatar.jpg', null=True, blank=True) about = models.CharField(max_length=100) def __str__(self): return self.user.username class Gig(models.Model): writer = models.ForeignKey(Profile, on_delete = models.CASCADE, null=False, blank=False) category = models.ForeignKey('Category', on_delete = models.CASCADE, null=False, blank=False) title = models.CharField(max_length=500, null=True, blank=True) description = models.CharField(max_length=500, null=True, blank=True) image = models.ImageField(null=False, blank=False) gig_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title Views.py: def createGig(request): gig = request.user.profile form = CreateGigForm() if request.method == 'POST': form = CreateGigForm(request.POST, request.FILES) if form.is_valid: gig = form.save(commit=False) gig.writer = gig gig.save() messages.info(request, 'Profile Succesfully Created') return redirect('create') else: messages.error(request, 'Gig Not Created! Try Again Later') context = {'form':form} return render(request, 'starter/create_gig.html', context) And here is a screenshot of the error message: Error message screenshot -
Pip error with requirements while deployng Django to Digital Ocean
I am trying to Deploy my Django API to a droplet in Digital Ocean, with ubuntu. I freezed my environment with pip freeze > requirements.txt command, and pulled it into the server. When I ask to install dependencies, into the activated virtual environment, with pip install -r requirements.txt it says that ERROR: Could not find a version that satisfies the requirement apturl (from versions: none) ERROR: No matching distribution found for apturl If id does matter, here is the actual requirements file: apturl beautifulsoup4==4.11.1 blinker==1.4 Brlapi certifi==2020.6.20 chardet==4.0.0 charset-normalizer==2.1.1 cliapp==1.20180812.1 click==8.0.3 colorama==0.4.4 command-not-found==0.3 cryptography==3.4.8 cupshelpers==1.0 dbus-python==1.2.18 defer==1.0.6 distlib==0.3.4 distro==1.7.0 distro-info===1.1build1 filelock==3.6.0 Flask==2.2.2 Flask-Login==0.6.2 Flask-SQLAlchemy==3.0.1 git-filter-repo==2.38.0 greenlet==1.1.3.post0 gunicorn==20.1.0 httplib2==0.20.2 idna==3.3 importlib-metadata==4.6.4 itsdangerous==2.1.2 jeepney==0.7.1 Jinja2==3.1.2 keyring==23.5.0 language-selector==0.1 launchpadlib==1.10.16 lazr.restfulclient==0.14.4 lazr.uri==1.0.6 llfuse==1.3.8 louis==3.20.0 macaroonbakery==1.3.1 Markdown==3.3.6 MarkupSafe==2.1.1 more-itertools==8.10.0 netifaces==0.11.0 oauthlib==3.2.0 olefile==0.46 pexpect==4.8.0 Pillow==9.0.1 pipenv==11.9.0 platformdirs==2.5.1 protobuf==3.12.4 psycopg2-binary==2.9.5 ptyprocess==0.7.0 pycairo==1.20.1 pycups==2.0.1 Pygments==2.11.2 PyGObject==3.42.1 PyJWT==2.3.0 pymacaroons==0.13.0 PyNaCl==1.5.0 pyparsing==2.4.7 pyRFC3339==1.1 python-apt==2.3.0+ubuntu2.1 python-dateutil==2.8.1 python-debian===0.1.43ubuntu1 python-dotenv==0.21.0 pytz==2022.1 pyxdg==0.27 PyYAML==5.4.1 reportlab==3.6.8 requests==2.28.1 SecretStorage==3.3.1 six==1.16.0 soupsieve==2.3.2.post1 SQLAlchemy==1.4.41 systemd-python==234 ttystatus==0.38 typing_extensions==4.4.0 ubuntu-advantage-tools==27.12 ubuntu-drivers-common==0.0.0 ufw==0.36.1 unattended-upgrades==0.1 urllib3==1.26.5 virtualenv==20.13.0+ds virtualenv-clone==0.3.0 wadllib==1.3.6 Werkzeug==2.2.2 xdg==5 xkit==0.0.0 zipp==1.0.0 I tried to install dependencies by hand, update pip and Python ( version 3.10 ), and build-essentials, but nothing worked. I deleted the versions from the file, and it … -
Django passing parameter from one funttion to another
I am trying to pass the value from the drop down menu to the next function other_funtion() missing 1 required positional argument: 'descrip' python def Home(request): # Description = menu_options.description() if env('ENVIRONMENT') == "TEST": current_user = f"{request.META['USERNAME']}" else: current_user = request.META['REMOTE_USER'] Description = Some_model.objects.raw(""" SELECT min(bgd.id) as id, groups, [Description] FROM [dbo].[description] bgd INNER JOIN [dbo].[auth_group] ag ON bgd.groups= ag.[groups] INNER JOIN [dbo].[auth_user_groups] aug ON ag.id = aug.group_id INNER JOIN [dbo].[auth_user] au on au.id = aug.[user_id] WHERE bgd.Status= 'Active' AND au.[username] = %s group by [Description], groups """,[current_user]) if request.method == 'POST': descrip = request.session.get('Description') request.session['Description'] = descrip other_funtion(descrip) # request.session['Description'] = Description print(descrip) return {"Description":Description} return render(request, "index.html",{"Description":Description}) def other_funtion(request): descrip = descrip print(descrip) return render(request, somehtml.html, {}) html ` <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> {% for results in Description %} <a class="dropdown-item" href="{% url 'BidderPref' %}" target="_self name="descript" value="{{results.Description}}">{{results.Description}} </a> {% endfor %} </div> ` Expected the value to pass if I change the section in the opening funtion to still have the issue def other_funtion(request, descrip) also tried descrip = request.session['Description'] #in the section funtion is try similar with the class Any help would be greatly appreciated -
Django fetch data in specific format
I have two table sale which has field like this And other table is product I am fetching tag count and avg product price with this query today = timezone.now().today() start_date = today - relativedelta(months=12) end_date = today sale_filters = ( Q(tags__name__in=['Device','Mobile']) & (Q(date_created__gte=start_date) & Q(date_created__lte=end_date)) ) sale_year = Sale.objects.using('read_rep') \ .prefetch_related('products') \ .annotate(month=TruncMonth('date_created')) \ .filter( sale_filters ).values( 'tags__name','date_created' ).annotate( tags_count=Count('tags__name'), price_avg=Coalesce(Avg('products__price'), Decimal('0')), price_sum=Coalesce(Sum('products__price'), Decimal('0')) ).order_by('date_created') Result: {'tags__name': 'Device', 'date_created': datetime.datetime(2022, 11, 12, 3, 20, 3, tzinfo=<UTC>), 'tags_count': 1, 'price_avg': Decimal('234.000000'), 'price_sum': Decimal('234.00')}, {'tags__name': 'Mobile', 'date_created': datetime.datetime(2022, 11, 12, 3, 20, 3, tzinfo=<UTC>), 'tags_count': 1, 'price_avg': Decimal('234.000000'), 'price_sum': Decimal('234.00'), 'fee_sum': Decimal('7.02')}, {'tags__name': 'Device', 'date_created': datetime.datetime(2022, 12, 6, 16, 25, 6, 178045, tzinfo=<UTC>), 'tags_count': 1, 'price_avg': Decimal('100.000000'), 'price_sum': Decimal('100.00')}, {'tags__name': 'Mobile', 'date_created': datetime.datetime(2022, 12, 6, 16, 25, 6, 178045, tzinfo=<UTC>), 'tags_count': 1, 'price_avg': Decimal('100.000000'), 'price_sum': Decimal('100.00')} I want result like this {'date_created': datetime.datetime(2022, 11, 12, 3, 20, 3, tzinfo=<UTC>), 'Device': 1, 'Mobile': 1, 'price_avg': Decimal('100.000000'), 'price_sum': Decimal('100.00')} {'date_created': datetime.datetime(2022, 12, 6, 16, 25, 6, 178045, tzinfo=<UTC>), 'Device': 1, 'Mobile': 1, 'price_avg': Decimal('100.000000'), 'price_sum': Decimal('100.00')} Is there any way that I can achieve this data format. Any help will be appreciated. -
What is the difference between @action and @api_view to create routes in Django Rest Framework
Both decorators appear to simply create a route for you. But what would be the practical difference (if any)? In the documentation, it is not clear. I even created two routes the same way and there was no difference -
Is there a way to optimise the time taken for uploading multipart data in a django + react app?
I have an app that has a django rest framework backend and a react frontend. As usual the user has an option to edit the details he has initially submitted. The details also contain a profile picture of the user. The update view works fine, but what I have noticed in the network tab is, if the user tries to update his profile it takes upt 5-8s and sometimes 27s for the react frontend to receive a response from backend. Question Is there any way to reduce this time or any performance optimisation method? I am also posting my code incase I am doing something wrong. react part export const editTeacherDetail = async (detailsData, photo) => { console.log("detailsData before in main api = ", detailsData); console.log("photo before in main api = ", photo); let formData = new FormData(); formData.append("name", detailsData.name.toUpperCase()); formData.append("state", detailsData.state); formData.append("adhaar_number", detailsData.adhaar_number); formData.append("current_profession", detailsData.current_profession); formData.append("phone", detailsData.phone); formData.append("location", detailsData.location.toUpperCase()); formData.append("full_address", detailsData.full_address.toUpperCase()); formData.append("date_of_birth", detailsData.date_of_birth); formData.append("gender", detailsData.gender.toUpperCase()); formData.append("name_of_school", detailsData.name_of_school.toUpperCase()); formData.append("experience", detailsData.experience); formData.append("teach_for_no_days", detailsData.teach_for_no_days); formData.append("subject", detailsData.subject.toUpperCase()); formData.append("teach_class", detailsData.teach_class); formData.append("home_tuition", detailsData.home_tuition); formData.append("fees", detailsData.fees); formData.append("home_tuition_fees", detailsData.home_tuition_fees); formData.append("shift", detailsData.shift.toUpperCase()); formData.append("board", detailsData.board.toUpperCase()); if (typeof photo !== "string") { formData.append("profile_photo", photo); } try { console.log("formData = ", formData); let response = await axiosInstance.put(`/teacher/edit-detail/`, formData); console.log(response); return response; … -
I don't have permission to pip install in docker shell
I have a Django app in a docker container, I'd like to install djangorestframework, but when I enter the container's shell, docker exec -t -i <container id> shell, and run pip install djangorestframework, then I get: ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: '/.local' Check the permissions. It might be useful to know that I am using a Linux machine and had an issue with Docker running Django proceses as root, which meant I needed superuser privleges to edit Django files that were created by Django manage.py functions. I overcame this by adding: user: "${user_id}:${group_id}" To the docker-compose.yml file -
Doing select_related() twice - using the output queryset
I am trying to join two models together. Project has an FK to org (orgid) People has an FK to org (orgid) But, I want the result of org + project + people, So I tried to do select_related() and then select_related on the outcome to join the new queryset to the other model. It didn't work :( a = people.objects.filter(personid=user, status='approved').select_related('orgid') b = a.select_related('projectid') In SQL this would be simply SELECT * from( SELECT app_org.orgid as orgid, orgname, username, role from app_org LEFT JOIN app_people on app_people.orgid = app_org.orgid)x LEFT JOIN app_project in x.orgid = app_project.orgid Can anyone please help me? I also tried a = people.objects.filter(personid=user, status='approved').select_related('orgid__projectid')