Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail PageRevision errors from loaddata
When I use dumpdata / loaddata to snapshot my live Wagtail sites to my sandbox, I sometimes get pages which I can't edit on my sandbox. These are always pages which the Wagtail admin explorer has marked "live + draft". They produce a 500 error, can't currently handle on_delete types other than CASCADE, SET_NULL and DO_NOTHING but the stack trace shows the cause is a ContentType matching query does not exist. The only way to make them editable on the sandbox is to remove the PageRevision for each of the pages locally, via Django/python shell. Is there an approved way to fix these pages to remove the spurious drafts? -
Error converting data type nvarchar to Datetime While Calling Store Procedure in Django
I am trying to pass datetime value to the store procedure of mssql but getting this error: django.db.utils.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Error converting data type nvarchar to datetime. (8114) (SQLExecDirectW)') Here is the code: fromDate = datetime(2022, 1, 1) toDate = datetime(2022, 12, 31) dealershipId = request.GET['dealershipId'] cursor = connection.cursor() cursor.execute(f"EXEC proc_LoadJobCardbyDateRange [@Fromdate={fromDate}, @Todate={toDate}, @DealershipId={dealershipId}]") result = cursor.fetchall() I have tried to pass datetime object in order to execute store procedure. I also tried to pass datetime as string but the same error persists. I also tried different formats but it didn't work as mentioned in some solutions that I have searched for. Please guide me as to why I am having this issue and what's the correct solution to this can be? -
Django password hashing different from python passlib pbkdf2 library
Using django admin, I have created a user email: cuteemail@example.com password: ccpass!ccpass The hashed password stored in the database is pbkdf2_sha256$260000$alGB1h2BRHwn83nz9fSJ3V$qippfbL8g59KPoDh+cIEh70TQCjuWeH8017VcLLpDIY= All I know is that django is generating the password hash using PBKDF2 algorithm. I need to run a pure python script that inside a part of it, it checks if a password is matching a hash. I have found a library passlib. I can provide the password and rounds. But where does the django salt come from? from passlib.hash import pbkdf2_sha256 password = 'ccpass!ccpass' db_hashed_password = 'pbkdf2_sha256$260000$alGB1h2BRHwn83nz9fSJ3V$qippfbL8g59KPoDh+cIEh70TQCjuWeH8017VcLLpDIY=' salt = db_hashed_password.split('$')[2].encode() pbkdf2_sha256.hash(password, rounds=260000, salt=salt) result: $pbkdf2-sha256$260000$YWxHQjFoMkJSSHduODNuejlmU0ozVg$qippfbL8g59KPoDh.cIEh70TQCjuWeH8017VcLLpDIY The resulted password hash apparently looks the same except minor differences. The pbkdf2-sha256 has a dash instead of an underscore but this is not a problem. I can fix it. The main problem is that I do receive a . instead of + in the actual hash part. How to fix this? Can I blindly replace all . with + ? -
Django Rest Framework - datetime sent as str gets changed to different timezone when being saved to database?
I sent the following: {'ticker': 'XYZ', 'last_price': 394.05, 'last_date_time': '2022-10-04 15:57:18'} When it was saved in DB: ticker: XYZ last_price: 394.05 last_date_time: 2022-10-04 11:57:18 I am not sure how or why this gets changed. models.py class StockPriceModel(models.Model): ticker = models.CharField(max_length=30, blank=False, db_index=True) last_price = models.FloatField(blank=True, null=True) last_date_time = models.DateTimeField(db_index=True) created_at = models.DateTimeField(auto_now_add=True) The auto_now_add field is also showing incorrect time. It doesn't correspond to my date time setup in settings as below: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Dubai' USE_I18N = True USE_L10N = True USE_TZ = True -
difference between Django ORM datetime and Postgre datetime value
I have developed an application with Django and recently changed my DB from Sqlite to Postgresql. I have found the following inconsistency between datetime values in DB and results of Django orm: and: You can see the difference between hours, mins and seconds. It should be noted that the column type is datetime and there is not any inconsistency if i use sqlite. -
How to join two different modal in django?
I'm using django 3.2. And DB name postgres. I'm stuck in a problem where i want to combine two modals. I have following two modals 1- Profiles 2- Ratings foreignKey(Profiles) now I want to return profiles list with their ratings. And this is what i'm unable to achieve. Actually I don't know how to do that. I think it can be done by inner join by profile_id but how to do this with django ? My code : @api_view(['GET']) @permission_classes([IsAuthenticated]) def profile_list(request): if request.method=="GET": kind = kind.lower() paginator = CustomPagination() paginator.page_size = 10 print("dat da da da da ==>> ",request.data) coordinates = request.data["coordinates"] nearby_count = Profile.objects.nearby_count(coordinates) total_count = nearby_count total_page = total_page_counter(nearby_count) profiles_queryset = Profile.objects.nearby_ground_list(coordinates) ## Rating.objects ???? page_data_of_profiles=None try: page_data_of_profiles = paginator.paginate_queryset(profiles_queryset, request) except: pass serializer = ProfileSerializer(page_data_of_profiles, many=True) return Response({"status":"success","message": "Ok","total_count":total_count,"total_page":total_page, "data": serializer.data},status=status.HTTP_200_OK) -
how i make a qr code generator in django?
I'm working on an existing project with Django and I need to add a qr code that generate the profile info from database , but unfortunately I didn't find a helping documentation so if u have any idea of what I'm facing hit me up with an advice or a link and thank you -
Django AWS cannot be access from public IP
I've been trying to put my Django application as docker in AWS ECS and it works as intended when accessing from inside. Then I tried to add an ALB so I can access my application but so far failed to do so. I have exposed port 8000 in docker where my application runs and in task definition mapped it to port 80 in host. It's up and running as a ECS cluster service where the VPC subnet choice is the same as in the ALB. My ALB is listening to both 80 and 8000 ports and forwarding to the target group which also has port 80. I have used a single security group for this allowing both ports with all IPs I'm struggling to figuring out what went wrong here. -
Django Action Append Slash
I am making development, and my POST request come like config/alert and I am trying to catch it with action decorater below.BUT Django does not catch it It wants config/alert/ but It is not possible to change incoming url add the SLASH. @action(methods=['post'], detail=False, url_path='alert') def get_post(self, request, pk=None, *args, **kwargs): How can I modify the action to listen without slash in POST request? -
Error in activation via URL sent to email in user registration system using DRF
I wanted to add a registration system to the API using DRF. The user receives an activation url by email and can activate his account. I am having problems decoding this sent token, i.e. it is taking the token as invalid. views.py I created a registration system and followed it up with an activation system. class RegisterView(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data user = User.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('email-verify') absolute_url = "http://" + current_site + relativeLink + "?token=" + str(token) email_body = "Hi " + user.username + ". Use link below to verify your email \n" + absolute_url data = {"email_body": email_body, "to_email": user.email, "email_subject": "Verify Your Email"} Util.send_email(data) return Response(user_data, status=status.HTTP_201_CREATED) class VerifyEmail(views.APIView): serializer_class = EmailVerificationSerializer token_param_config = openapi.Parameter( 'token', in_=openapi.IN_QUERY, description='Description', type=openapi.TYPE_STRING) @swagger_auto_schema(manual_parameters=[token_param_config]) def get(self, request, *args, **kwargs): token = request.GET.get("token") try: payload = jwt.decode(token, settings.SECRET_KEY) user = User.objects.get(id=payload['user_id']) if not user.is_verified: user.is_verified = True user.save() return Response({"email": "Successfully activated"}, status=status.HTTP_200_OK) except jwt.ExpiredSignatureError: return Response({'error': 'Activation expired'}, status=status.HTTP_400_BAD_REQUEST) except jwt.exceptions.DecodeError: return Response({"error": "Invalid token"}, status=status.HTTP_400_BAD_REQUEST) serializers.py from rest_framework import serializers from .models import User class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(min_length=6, max_length=50, write_only=True) … -
why Django redirect function returns to the same page
I have a website where there are different groups. As soon as you click on one of the groups, you are redirected to the details page of that group. This click happens via a post method, where the name of the group is sent to the server. There I check if it is a POST method, and since I use several on the page, I also check which one it is ['post-function']. Then the name of the group is stored in the session (this is important for a later function). Afterwards it should be redirected to the detail page. However, I always end up on the same page. In the console I can see that the details page is loading, but I am somehow redirected to the main page. these are my URLS: urlpatterns = [ path('admin/', admin.site.urls), path('', index, name='home'), path('send', send, name='send'), path('datasheet/', datasheet, name='datasheet'), path('datasheet/intents/', intents, name='intents'), ] datasheet is the page where all the groups are listed and can be clicked for the detail page here are my views: def datasheet(request): # error handling if 'error' not in request.session: error = "no_error" else: error = request.session['error'] del request.session['error'] # post methods if request.method == 'POST': # … -
Foreign Key USER Django Model: django.db.utils.IntegrityError: (1062, "Duplicate entry
I'm trying to use User as a foreign key for Time for an API, but I'm getting this error message when I try to add another time django.db.utils.IntegrityError: (1062, "Duplicate entry '20' for key 'time.user_id'") My model: class Time(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.DO_NOTHING) start = models.CharField(max_length=10, default=None, null=True, blank=True) end = models.CharField(max_length=10, default=None, null=True, blank=True) My view: @api_view(['POST']) def TimeNew(request, email): try: user = User.objects.get(email=email) except User.DoesNotExist: return JsonResponse({'message': 'ERRO'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'POST': time_data = JSONParser().parse(request) time_data['user'] = user.id time_serializer = TimeSerializer(data=time_data) if time_serializer.is_valid(): time_serializer.save() return JsonResponse(time_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(time_serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Keeping CharFields in array instead of multiple variables
Right now I'm using various variables to store fields, and it works well, but I'd like to move them to lists. Is there a way to do this? What I have now: lessonNameFirst = models.CharField('8:30-10:00', max_length = 50) additInfoFirst = models.CharField('Additional info', max_length = 50) lessonNameSecond = models.CharField('10:15-11:45', max_length = 50) additInfoSecond = models.CharField('Additional info', max_length = 50) lessonNameThird = models.CharField('12:30-14:00', max_length = 50) additInfoThird = models.CharField('Additional info', max_length = 50) lessonNameFourth = models.CharField('14:10-15:40', max_length = 50) additInfoFourth = models.CharField('Additional info', max_length = 50) What I'm looking for: lessonName = [ models.CharField('8:30-10:00', max_length = 50), models.CharField('8:30-10:00', max_length = 50), models.CharField('8:30-10:00', max_length = 50), models.CharField('8:30-10:00', max_length = 50) ] additInfo = [ models.CharField('Additional info', max_length = 50), models.CharField('Additional info', max_length = 50), models.CharField('Additional info', max_length = 50), models.CharField('Additional info', max_length = 50) ] -
5 seconds delay(pause) from django+apache
I am running a site with django+apache+ssl+mysql+cloudfron+s3. However, I discovered that the ttfb time increases significantly when the first connection and caching setup time ends at some point. (response starts after pause for about 5 seconds) After uninstalling Apache, I tried debugging in debug mode and in Gunicorn. There were no issues with ttfb in debug mode. However, I found out that I had the same problem when using Gunicorn. So I looked all over apache, db, ssl, django template rendering, etc. I don't know what's causing the bottleneck. Which part should I look at more? Oh, and I also found that if I send a request twice in a row (click the second link right after the first link is clicked), I get a response right away without any pause. Please advise. I think my head is going to break... -
How to server static files in the folder without folder 'static'? Django
I have my index.html and static files in this structure: templates: folder: index.html css js images another_folder: index.html css js images I want that staticfiles finder will look for static in templates by domain name in request. Please, without 'static' folder and {% load static %} tag. Thanks. -
Cronjob is not ran in Elastic Beanstalk
I am running Django in Elastic Beanstalk, platform: Python 3.7 running on 64bit Amazon Linux 2/3.4.0. I need to create a cronjob that runs a custom Django management command once every five minutes. I created the following file to .ebextensions/cron.config: files: "/etc/cron.d/mycron": mode: "000644" owner: root group: root content: | 5 * * * * root /usr/local/bin/myscript.sh "/usr/local/bin/myscript.sh": mode: "000755" owner: root group: root content: | #!/bin/bash source /var/app/venv/*/bin/activate && python3 manage.py mycommand exit 0 commands: remove_old_cron: command: "rm -f /etc/cron.d/mycron.bak" And redeployed the enviroment with eb deploy. However, the cron job does not get run. My questions are: What have I done wrong? How can I see if the cron.config file gets processed? How can I check that some cronjob gets ran? -
Error after running makemigrations in django app
I have developed a django app and I want to use postgres to store some results. For that reason I have the following docker-compose.yml: version: '3.2' services: elasticsearch: container_name: elasticsearch build: context: elasticsearch/ args: ELK_VERSION: $ELK_VERSION volumes: - type: bind source: ./elasticsearch/config/elasticsearch.yml target: /usr/share/elasticsearch/config/elasticsearch.yml read_only: true - type: volume source: elasticsearch target: /usr/share/elasticsearch/data ports: - "9200:9200" - "9300:9300" environment: ES_JAVA_OPTS: "-Xmx256m -Xms256m" ELASTIC_PASSWORD: changeme links: - kibana networks: - elk logstash: container_name: logstash build: context: logstash/ args: ELK_VERSION: $ELK_VERSION volumes: - type: bind source: ./logstash/config/logstash.yml target: /usr/share/logstash/config/logstash.yml read_only: true - type: bind source: ./logstash/pipeline target: /usr/share/logstash/pipeline read_only: true ports: - "5000:5000" - "9600:9600" expose: - "5044" networks: - elk depends_on: - elasticsearch kibana: container_name: kibana build: context: kibana/ args: ELK_VERSION: $ELK_VERSION volumes: - type: bind source: ./kibana/config/kibana.yml target: /usr/share/kibana/config/kibana.yml read_only: true ports: - "5601:5601" networks: - elk app: container_name: app build : ./app volumes: - ./app/:/usr/src/app - /usr/src/app/node_modules/ # make node_module empty in container command: npm start ports: - "3000:3000" networks: - elk nginx: container_name: nginx build: ./nginx volumes: - ./nginx/config:/etc/nginx/conf.d - ./nginx/log:/var/log/nginx ports: - "80:80" - "443:443" links: - app:app depends_on: - app networks: - elk filebeat: container_name: filebeat build: ./filebeat entrypoint: "filebeat -e -strict.perms=false" volumes: - ./filebeat/config/filebeat.yml:/usr/share/filebeat/filebeat.yml - … -
Django Rest not receiving large base64 images through POST
I have a REST API in Django that is able to process JSON data, small base64 images are working by large images like 3MBs are failing to be processed. The images are saved to the folder. -
How to get select options from django models?
I am not able to render product in my order model on my html page. I am trying to find out the problem here. but as i select form.product.model_name it should get me the model names, but its blank in options. Below I am attaching the code to check it out, in my models.py from cgi import print_form from email.policy import default from enum import unique from django.db import models # Create your models here. class ProductModel(models.Model): product_id = models.CharField(max_length=100,unique=True, default = '0') product_name = models.CharField(max_length=100, default=" ") model_name = models.CharField(max_length=100, default=" ") def __str__(self): return str(self.product_id) productchoice = (ProductModel.objects) class OrderModel(models.Model): order_id = models.AutoField(unique=True, primary_key=True) Customer_name = models.CharField(max_length=100) Father_name = models.CharField(max_length=100) Village = models.CharField(max_length=100) Tehsil = models.CharField(max_length=100) District = models.CharField(max_length=100) State = models.CharField(max_length=100) product = models.ForeignKey(ProductModel, on_delete = models.CASCADE, default= 0) def __str__(self): return str(self.order_id) in my view.py from email import message_from_binary_file from django.shortcuts import render from .models import OrderModel, ProductModel from .forms import OrderForm, ProductForm from django.http import HttpResponse, HttpResponseRedirect from django.contrib import messages from django.contrib.messages import get_messages # Create your views here. def home(request): order_form = OrderForm if request.method == 'POST': order_form = OrderForm(request.POST) if order_form.is_valid(): order_form.save() messages.success(request, ('Your data was successfully added!')) return HttpResponseRedirect('/') else: messages.error(request, … -
Data input from template file is not storing in .txt file in Django Python ( Get method)?
I'm trying to store some data from a html form in a .txt file. But when I store data from my variable used to recieve data it give "None". But when I pass string directly it successfully store. def write(request): p_no = request.GET.get('p_no') # temp = "% s" % p_no # Str_value = '{}'.format(p_no) temp = p_no.__str__() with open('C:\\Users\\The Goat\\Desktop\\testp\\Files\\sample.txt', 'w+') as f: testfile = File(f) testfile.write(temp)+ testfile.close f.close return render(request,'index.html') -
Object data becomes empty after serializing
user = User.objects.filter(id=payload['id']).first() carts = AddToCart.objects.filter(user=user) sum_price = 0 for i in carts: sum_price += int(i.product.price) context = { 'carts': carts, 'sum_price': sum_price, } print(context) serializer = AddToCartSerializer(context, many=True) return Response(serializer.data) **printed 'context' in a terminal looks like this {'carts': <QuerySet [<AddToCart: AddToCart object (3)>]>, 'sum_price': 100}. But after serializing it becomes empty. Can someone help me? ** This is an output in a postman [ {}, {} ] AddToCart models.py class AddToCart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) AddToCartSerializer serializers.py class AddToCartSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='User') product = serializers.ReadOnlyField(source='Product') class Meta: model = AddToCart fields = ['user', 'product'] -
how to get the id of an entry based on the name in Django?
i have created the following model in Django to store my groups in a database: class Group(models.Model): name = models.CharField(max_length=1000) now i would like to get the id of a group by its name in my views.py. How do I do that? with the Group.objects.get() method i can filter by name, but there i get the whole row and not only the id -
This engine did not provide a list of tried templates
Wup, I'm trying to deploy a localhost web using Django but I get the following error: TemplateDoesNotExist at / templates/index.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1.2 Exception Type: TemplateDoesNotExist I was looking tutorials and docs but I didn't found the answer. Here is my settings.py import os ALLOWED_HOSTS = ['*'] DEBUG = True SETTINGS_PATH = os.path.normpath(os.path.dirname(__file__)) TEMPLATE_DIRS = ( os.path.join(SETTINGS_PATH, 'templates'), ) ROOT_URLCONF = 'FortyTwop.urls' SECRET_KEY = 'This is a secret key' also urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ] And views.py from email import message from http.client import HTTPResponse from django.shortcuts import render # Create your views here. def index(request): return render(request, 'templates/index.html') My path tree: . ├── FortyTwop │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── templates │ │ └── index.html │ ├── tests.py │ ├── urls.py │ └── views.py └── manage.py What Im doing bad or what I didn't have in the settings?, this project is just for test. -
Change input value that used in different function. Django
So, I have an input field and I'm using that input field to save and edit a data. Basically, I use the same form to save and edit to database. in my form.html I have this input. <label for="bar-title">Chart Title: </label> <input class="bg-white border shadow rounded w-96" type="text" id="bar-title" name="bar-title" /> in my save.html, save function. function saveBarChart() { data = {}; data.title = $("#bar-title").val(); $.ajax({ url: '{% url "url" %}', type: "POST", data: { id: id, csrfmiddlewaretoken: "{{ csrf_token }}", chart_data: JSON.stringify(data), }, }) .done(function (response) { console.log(response); //once send I will save the input value to database// }) .fail(function (error) { if (error) notify(error); }); } in my edit.html. I tried to set the value of input field by using the data from database. And if I tried to change the input field nothings change. function setFormsValue(id) { $.ajax({ type: "GET", url: `{% url 'get_data' %}${id}`, }).done(function (response) { $(".update-barchart-wrapper input[name=bar-title]").val(response.name.title); }); } When I try to change the value by inputting some data into input field nothings changing. function editChartForm() { var chartsRow = {}; chartsRow.title = $("#bar-title]").val(); console.log(chartsRow) } -
How can I access an object from a nested serializer? KeyError
Hope someone can help me! I want to return requestid and partsid after a POST request. requestid is already reflected, but calling partsid sends me KeyError. How can I access this object from a separate table referenced as nested? See code for reference: # models.py class requestTable(models.Model): requestid = models.AutoField(primary_key=True) requestname = models.CharField(max_length=100, null=False) class partsTable(models.Model): partsid = models.AutoField(primary_key=True) validatorid = models.ForeignKey(userTable, on_delete=models.CASCADE) request = models.ForeignKey(requestTable, related_name='parts', on_delete=models.CASCADE) # views.py class RequestListCreateView(generics.ListCreateAPIView): queryset = requestTable.objects.all() serializer_class = RequestCreateSerializer filter_backends = [DjangoFilterBackend, SearchFilter] filterset_fields=['requesterid', 'requestid'] search_fields= ['requestname'] def create(self, request, *args, **kwargs): write_serializer = RequestCreateSerializer(data=request.data) write_serializer.is_valid(raise_exception=True) instance = self.perform_create(write_serializer) headers = self.get_success_headers(write_serializer.data) return Response({"Request ID": write_serializer.data['requestid']}) #How can I show partsid here? When I add "Parts ID": write_serializer.data['partsid'], it sends me KeyError #serializers.py class PartSerializer(serializers.ModelSerializer): class Meta: model = partsTable fields = ['partsid', 'validatorid'] class RequestCreateSerializer(serializers.ModelSerializer): parts=PartSerializer(many=True) class Meta: model = requestTable fields = ['requestid', 'requestname', 'parts'] def create(self, validated_data): parts_data = validated_data.pop('parts') request = requestTable.objects.create(**validated_data) for part_data in parts_data: partsTable.objects.create(request=request, **part_data) return request class RequestListSerializer(serializers.ModelSerializer): parts=PartSerializer(many=True, read_only=True) class Meta: model = requestTable fields = ['requestid', 'requestname', 'parts']