Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. even though my fields are little
I created a script to programmatically upload data to my backend, but django keeps throwing the The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. error at me, here is the data I am sending {'store': 'dang-1', 'name': 'Nike Air Max Plus', 'description': 'Let your attitude have the edge in your Nike Air Max Plus, a Tuned Air experience that offers premium stability and unbelievable cushioning.', 'brand': 'Nike', 'model': 'Air Max Plus', 'gender': 'U', 'category': 'shoes', 'image_v0_1': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (3).jpg'>, 'image_v0_2': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (3).png'>, 'image_v0_3': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (3).jpg'>, 'image_v1_1': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (1).jpg'>, 'image_v1_2': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (1).png'>, 'image_v1_3': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (1).jpg'>, 'image_v2_1': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (2).jpg'>, 'image_v2_2': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (2).png'>, 'image_v2_3': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (2).jpg'>, 'variants': '[{"is_default": true, "price": 65000, "quantity": 10, "shoe_size": 45, "color": "black"}, {"is_default": false, "price": 65000, "quantity": 10, "shoe_size": 45, "color": "multi-colored"}, {"is_default": true, "price": 65000, "quantity": 10, "shoe_size": 45, "color": "green"}]'} And here is the script I created import json import requests if __name__ == '__main__': json_file = open('data/data.json') products = json.load(json_file).get("products") for index, product in enumerate(products): print(f"Creating {index + 1}/{len(products)} - {product.get('name')}") … -
Specify exact opening hours for buisness
im trying to create custom field for django model. I need to store opening hours for every day of the week. class Restaurant(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) city = models.CharField(max_length=15) street = models.CharField(max_length=15) house_number = models.CharField(max_length=3) flat_number = models.CharField(max_length=3, default='0') phone_number = models.CharField(max_length=12) image = models.ImageField() rating = models.FloatField(validators=[validate_rating_number]) def __str__(self): return f'{self.name}, {self.city}' I have to store opening hours in a field like opening_hours = models.CustomField() -
Django dynamic url with data from DB
Models.py from django.db import models # Create your models here. class reviewData(models.Model): building_name = models.CharField(max_length=50) review_content = models.TextField() star_num = models.FloatField() class buildingData(models.Model): building_name = models.CharField(max_length=50) building_loc = models.CharField(max_length=50) building_call = models.CharField(max_length=20) views.py # Create your views here. from django.shortcuts import render from rest_framework.response import Response from .models import reviewData from .models import buildingData from rest_framework.views import APIView from .serializers import ReviewSerializer class BuildingInfoAPI(APIView): def get(request): queryset = buildingData.objects.all() serializer = ReviewSerializer(queryset, many=True) return Response(serializer.data) class ReviewListAPI(APIView): def get(request): queryset = reviewData.objects.all() serializer = ReviewSerializer(queryset, many=True) return Response(serializer.data) urls.py from django.contrib import admin from django.urls import path from crawling_data.views import ReviewListAPI from crawling_data.views import BuildingInfoAPI urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), #path('api/buildingdata/(I want to put building name here)', ReviewListAPI.as_view()) ] I am making review api. I want to use building name as url path to bring reviews for specific buildings For example, there are a, b, c reviews a, b reviews are for aaabuilding c reviews are for xxxbuilding api/buildingdata/aaabuilding (only shows aaabuilding review) { building_name = aaabuilding review_content = a star_num = 5 building_name = aaabuilding review_content = b star_num = 3 } api/buildingdata/xxxbuilding (only shows xxxbuilding review) { building_name = xxxbuilding review_content = c star_num = 4 … -
How to add a date and time column in my Django default user page in admin
I am using the Django default user model and in my admin, I can see 5 columns which are username, email address, first name, last name, and staff status. I need to add another column here that displays the date joined. Can anyone help here? thanks in advance -
How to call a dropdown list html select with Ajax JQuery in Django
I'd like to choose an option in the first select dropdown list and based on the selected option, the ajax should load the second select dropdown list, how to do it? This is my code: Models: class MaintenanceEquipment(models.Model): equip_id = models.CharField(max_length=30, auto_created=False, primary_key=True) line_nm = models.CharField(max_length=20, blank=True, null = True) sequence = models.CharField(max_length=30, blank=True, null = True) equip_model = models.CharField(max_length=30, blank=True, null = True) def __str__(self): return self.equip_id Views: from django.shortcuts import render from maintenance.models import MaintenanceEquipment def maintenanceIssueView(request): equipment_list = MaintenanceEquipment.objects.all() context = {'equipment_list':equipment_list} return render(request, 'maintenance/maintenanceIssue.html', context) def load_equipment(request): if request.method == 'GET': line = request.GET.get('line_nm') equipment = MaintenanceEquipment.objects.filter(line_nm=line) context = {'equipment': equipment} return render(request, 'maintenance/maintenanceIssue.html', context) urls: urlpatterns = [ path('maintenanceIssueView/', views.maintenanceIssueView, name="maintenanceIssueView"), path('ajax/load_equipment/', views.load_equipment, name="ajax_load_equipment"), ] maintenanceIssue.html: <form method="POST" id="maintenanceForm" data-equipment-url="{% url 'ajax_load_equipment' %}" novalidate> {% csrf_token %} <div style="text-align:left;" class="container-fluid"> <div style="text-align:left;" class="form-row"> <div class="form-group col-md-6"> <label for="line_nm" style="font-size:medium;">Line</label> <select class="form-control" id="line_nm" name="line_nm" > {% for instance in equipment_list %} <option id="{{ instance.line_nm }}" value="{{ instance.line_nm }}">{{ instance.line_nm }}</option> {% endfor %} </select> </div> <div class="form-group col-md-6"> <label for="sequence" style="font-size:medium;">Machine</label> <select class="form-control" id="sequence" name="sequence"> {% for instance in equipment %} <option value="{{ instance.sequence }}">{{ instance.sequence }}</option> {% endfor %} </select> </div> </div> </div> </form> <script> … -
Django Combine Common Values from Joining Two List of Dictionaries
I have 2 Lists of dictionaries, example below: list one = [ {'day': '2021-09-05 00:00:00+02:00', 'airtime_total_for_day': '650.00', 'data_total_for_day': '0'}, {'day': '2021-09-16 00:00:00+02:00', 'airtime_total_for_day': '124.20', 'data_total_for_day': '20.00'}, ] list_two = [ {'day': '2021-09-10 00:00:00+02:00', 'data_bundle_total_for_day': '100.00'}, {'day': '2021-09-16 00:00:00+02:00', 'data_bundle_total_for_day': '50.00'}, {'day': '2021-09-18 00:00:00+02:00', 'data_bundle_total_for_day': '45.00'}, ] I would like to merge the two lists together and at the same time, merge data_total_for_day with data_bundle_total_for_day under the name data_total_for_day. Also, if data_total_for_day & data_bundle_total_for_day happen to fall on the same day which they do on the 2021-09-16, the values need to be added together e.g. data_total_for_day on the 2021-09-16 is: 20.00 data_bundle_total_for_day on the 2021-09-16 is: 50.00 So on that specific day, data_total_for_day needs to be: 70.00 I've struggled and all & any help with be greatly appreciated. Things I tried: https://www.codegrepper.com/code-examples/python/merge+two+list+of+dictionaries+python How to merge two list of dictionaries based on a value join two lists of dictionaries on a single key -
How to make users see other user products in Django [closed]
is it possible to create a link to a different user and see only that users items? I started up a software that allows users to post their products to a site were every user can see the product. The problem is, I want any user to click on that post and it takes the user to a page that has items only by that user -
How to switch to windows desktop via bash
I'm following this instruction https://stackoverflow.com/a/33993532/16250669, but I can't complete step 5, how do I get to C:\Users\kudla\Desktop\food_delivery via bash console if when I enter ls I get output: bash-4.3# ls bin docker-entrypoint.sh lib proc sbin tmp dev etc media root srv usr docker-entrypoint-initdb.d home mnt run sys var -
Open ports 8000 and 3000 on EC2 AWS instance
I am trying to run Django in port 8000 and React in port 3000 on an EC2 AWS instance. I first created the inbound rules for ports 8000 and 3000: Then, I start both Django and React on ip 0.0.0.0 sudo npm start sudo python manage.py runserver 0.0.0.0:8000 And I can check both ports are open and listening: However, when I try to reach the urls http://external_ip:8000/ or http://external_ip:3000/ Nothing is working. However, I can make Django server works if I change 8000 by 80. What am I doing wrong or missing? -
How can i determine number object show per page when using ListView pagination in django?
please how can i determine number of objects/page show(not number of pages) in Django when using ListView Pagination. that's my code in Views.py : from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post class PostList(ListView): model=Post context_object_name='all_post' ordering=['-created_at'] thank you! -
How to configure ID parameters in django_rest_framework APIView
My goal is to specify behavior that allows me to enter an ID into my URL. Currently, I am able to send GET, PUT, and PATCH requests to the URL 'localhost:8000/api/?id=#' where the hash represents any object id. I would like to update my code to understand that if I send a GET/PUT/PATCH request to 'localhost:8000/api/2' that I am looking for and object with id=2 my models.py class player(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) team = models.CharField(max_length=50) position = models.CharField(max_length=50) number = models.IntegerField() def __str__(self): return "{}, {}".format(self.first_name, self.last_name) my serializer.py class playerSerializer(serializers.ModelSerializer): class Meta: model = player fields = ['id', 'first_name', 'last_name', 'team', 'position', 'number'] my views.py from django.shortcuts import render from django.http import HttpResponse, response from django.shortcuts import get_object_or_404 from rest_framework import serializers from rest_framework. serializers import Serializer from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from main.models import player from .serializers import playerSerializer import json class playerList(APIView): serializer_class = playerSerializer throttle_scope = "main_app" def get_queryset(self, *args, **kwargs): players = player.objects.all() return players def get(self, request, *args, **kwargs): try: id = request.query_params["id"] if id != None: player_object = player.objects.get(id=id) serializer = playerSerializer(player_object) except: players = self.get_queryset() serializer = playerSerializer(players, many=True) return Response(serializer.data) def … -
Django - Comparing id of queryset with fetch object id
I am learning django with practicing. I have one object. It has id, name, lastname. Also, I have one queryset. It has same attributes id,name, lastname. All I want is comparing id's. I can compare ids if they both are equal but my problem is if they both are not equal django gives me error like matching query does not exist. because I use filter function. I want to do this operation if icformkeyinput.filter(id=v['Id']): if icformkeyinput.filter(id!=v['Id']): My problem is How can I use != operator? I want to do this because if there is unmatched id between icformkeyinput and v then add v to icformkeyinput. -
django many to many queryset
i have two models : 1----- class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) name = models.CharField(max_length=150) phone = models.CharField(max_length=50) picture = models.ImageField(blank=True, null=True , upload_to='profile' ) profession = models.ManyToManyField(Profession) 2----- class Profession(models.Model): profession = models.CharField(max_length=50) i want to display all the profession that i have and in the same time i want to display the number of accounts that they have this profession like this pic enter image description here -
Cannot connect django to postgres running inside docker container
My django app is not dockerized, but I run postgres inside docker container using docker-compose.yml script. After docker-compose up I can connect to db with dbeaver, but not with django app. Every time I'm getting an error: django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution File docker-compose.yml: version: "3.9" services: db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" - POSTGRES_USER="postgres" - POSTGRES_PASSWORD="postgres" - POSTGRES_DB="postgres" ports: - 5432:5432 volumes: postgres_data Django project file config/settings.py: ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env.str("DB_NAME"), 'USER': env.str("DB_USER"), 'PASSWORD': env.str("DB_PASS"), 'HOST': env.str("DB_HOST"), 'PORT': env.decimal("DB_PORT") } } -
Get data from template to views in Django
How do i get the data (from database) in template to a view that i have for another app? I am building a very simple ecommerce website and would like to save the order of the users and save those products' name and quantity in the table 'Orders'. Here is a snap of my code to make it more clear: Template code Actual page display My view -
i am trying to add choice for candidate. It is giving me error that cannot represent value enums meta instance
i am trying to add choice for candidate. It is giving me error that cannot represent value enums meta instance message Enum AccountsCandidateGenderChoices cannot represent value EnumMeta instance. Is there any way to store choice inside candidate model? class Candidate(models.Model): class Gender(models.TextChoices): MALE = "Male" FEMALE = "Female" gender = models.CharField(max_length=100,choices=Gender.choices,default=Gender.MALE) class CandidateGender(graphene.Enum): MALE = "Male" FEMALE = "Female" mutation{ createCandidate(input: {gender:FEMALE}){ Candidate{ id, gender } } } -
Web3py Interacting with smart contract
Hey I'm working on a project and want to know if I can use python/django to make a frontend dapp where people can mint a token while connected to metamask ? Like signing their account and interact with the smart contract ? I really don't get it why I need to use javascript in order to make a minting process. Can some ligten me so I can continue to focus on python/django to AUTH, INTERACT with the blockchain. -
Django Ajax Not Found "url"
i am trying to use ajax with django: $('.btnMyc').click(function() { $.ajax({ type: "GET", url: "/getpic", data: { username: document.getElementById("usernameid").value }, urls.py: urlpatterns = [ path('', views.vscomain, name="vscomain"), path('getpic',views.send_pic,name="getpic"), ] and there is a function names send_pic in views.py but when i type username and click it i get this error: Not Found: /getpic [21/Sep/2021 14:00:59] "GET /getpic?username=sfdgl HTTP/1.1" 404 2400 -
Error while loading static files in Django
Trying to load static files but it is showing following error. ERROR GET http://127.0.0.1:8000/static/css/user/style.css net::ERR_ABORTED 404 (Not Found) - home:25 GET http://127.0.0.1:8000/static/css/user/style.css 404 (Not Found) - home:25 GET http://127.0.0.1:8000/static/img/logo.png 404 (Not Found) - home:149 GET http://127.0.0.1:8000/static/img/logo.png 404 (Not Found) - home:1 Click here to see error image. CODE -ADMIN settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('Welcome.urls')), path('auth/', include('Authentication.urls')), path('ad/', include('Ads.urls')), path('user/', include('UserDashboard.urls')), path('admin/', include('AdminDashboard.urls')), ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) APPS template <link href="{% static 'css/user/style.css' %}" rel="stylesheet"> Dirs Structure Click here to Project Directory Structure Image CODE EXPLANATION Simply added static files in the root dir and tried to import them in template but css files are not loading But some media files are successfully loaded like this media <link rel="shortcut icon" type="image/jpg" href="{% static 'img/logo.png' %}" />. Also in dir structure, we can see img and css folder at same place in static folder and images from image folder are loaded but css from css folder does not. -
Using saved database settings to generate code (if-statements) [closed]
I currently have an app that generates financial documents based on user-set settings These settings look something like this: Trial Balance ☐ Use main accounts ☐ Include Opening Balances ☐ Print Null Values ☐ Print Account Number All these settings are boolean variables and can easily be checked with if UseMainAccount == True : However, this would obviously take quite a few if statements to complete and can become very tedious. Is there a way to shorten this process (I know in Delphi and some other codes there are "case" statements for this. But would a case statement be possible in Django/Python -
Token generated by django-restframework-simplejwt not valid
This was working just fine before I tried to add social authentication to the project, and now when I send the verification email with the token, the token verifier says that the token is not valid! class ResendVerifyEmail(APIView): serializer_class = RegisterSerialzer def post(self, request): data = request.data # email = data.get('email') email = data['email'] print(email) try: user = User.objects.get(email=email) # print('hello') if user.is_verified: return Response({'msg':'User is already verified','status':'status.HTTP_400_BAD_REQUEST'}) print (user.username) token = RefreshToken.for_user(user).access_token current_site= get_current_site(request).domain relativeLink = reverse('email-verify') absurl = 'http://'+current_site+relativeLink+"?token="+str(token) email_body = 'Hi '+ user.username + ' this is the resent link to verify your email \n' + absurl data = {'email_body':email_body,'to_email':user.email, 'email_subject':'Verify your email'} Util.send_email(data) return Response({'msg':'The verification email has been sent','status':'status.HTTP_201_CREATED'}, status=status.HTTP_201_CREATED) except User.DoesNotExist: return Response({'msg':'No such user, register first','status':'status.HTTP_400_BAD_REQUEST'}) class VerifyEmail(APIView): serializer_class = EmailVerificationSerializer def get(self, request): token = request.GET.get('token') try: payload = jwt.decode(token, settings.SECRET_KEY) # print('decoded') user = User.objects.filter(id=payload['user_id']).first() # print(user) if user.is_verified: return Response({'msg':'User already verified!'}, status=status.HTTP_400_BAD_REQUEST) else: user.is_verified = True # user.is_authenticated = True user.is_active = True # if not user.is_verified: user.save() return Response({'email':'successfuly activated','status':'status.HTTP_200_OK'}, status=status.HTTP_200_OK) # except jwt.ExpiredSignatureError as identifier: except jwt.ExpiredSignatureError: return Response({'error':'Activation Expired','status':'status.HTTP_400_BAD_REQUEST'}, status=status.HTTP_400_BAD_REQUEST) # except jwt.exceptions.DecodeError as identifier: except jwt.exceptions.DecodeError: return Response({'error':'invalid token','status':'status.HTTP_400_BAD_REQUEST'}, status=status.HTTP_400_BAD_REQUEST) also, I have added these … -
Regex Error Finding Details from a bank statement
I am working with Regex and currently I am trying to extract the Name, IFSC and Account No. from the PDF. I am using following code to extract the details. acc_name= " ", '\n'.join([re.sub(r'^[\d \t]+|[\d \t]+:$', '', line) for line in data.splitlines() if 'Mr. ' in line]) acc_no= " ", '\n'.join([re.sub(r'Account Number\s+:', '', line) for line in data.splitlines() if 'Account Number' in line]) acc_code = " ", '\n'.join([re.sub(r'IFSC Code\s+:', '', line) for line in data.splitlines() if 'IFSC Code' in line]) But the data which I am getting back is following: (' ', ' 50439602642') (' ', 'Mr. MOHD AZFAR ALAM LARI') (' ', ' ALLA0211993') I want to remove the commas, brackets and quotes. I am new with regex so any help would be appreciated. -
Upload an csv file then, store data in MCQs format in the model
I'm creating an quiz app in django.The model is like this, class Question(models.Model): questions = models.CharField(max_length=50, unique=True) choice1 = models.CharField(max_length=50, unique=True) choice2 = models.CharField(max_length=50, unique=True) choice3 = models.CharField(max_length=50, unique=True) choice4 = models.CharField(max_length=50, unique=True) correct_answer = models.CharField(max_length=50, unique=True) I want to upload an MCQ-contained file and the model automatically stores the MCQs according to entries. e.g, if the file contains 20 MCQs then all MCQs store in the model according to the pattern given above. -
Django: How to delete Media Files on Digitalocean Spaces/ Amazon S3 automatically when Model instance is deleted
I have the following model defined in my Django-App def directory_path(instance, filename): return 'attachments/{0}_{1}/{2}'.format(instance.date, instance.title, filename) class Note(models.Model): title = models.CharField(max_length=200) date = models.DateField(default=datetime.date.today) # File will be saved to MEDIA_ROOT/attachments attachment = models.FileField(upload_to=directory_path) def __str__(self): return self.title I successfully set up AWS S3/ Digitalocean Spaces to store the media file uploaded via the attachment field. However, when I delete an instance of the model, the file remains in my bucket. What do I have to do, in order to delete the file automatically in my s3 bucket, if the corresponding model intance is deleted? -
How can I change template of account activation Email of django
I created class based view to access uid and token . Here I create one web page which have one button of activate user. I am sending one uid and token to user email. I created class based view to get uid and token. I am sending email on user gmail account. where user get link for activate his account. Email looks like this : You're receiving this email because you need to finish activation process on 127.0.0.1:8000. Please go to the following page to activate account: http://127.0.0.1:8000/activate/Mg/ata7ek-01e823899301fe357286112596a25655 Thanks for using our site! The 127.0.0.1:8000 team .... But now I wish to change this content/template of email for activate account . How can I change this template in django Here is my djoser setting DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL': True, 'SET_USERNAME_RETYPE': True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'email/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS': { 'user_create': 'user_profile.serializer.UserSerializer', 'user': 'user_profile.serializer.UserSerializer', } } How can I change it ?