Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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'] -
Display only upload field
I want to display only upload field on my project but need to save in my models(db): email address, file and date_time(this data was read from openpgp key) It's works like: User uploads file(openpgp public key) on website and my script reads email and date_time from file. I'm a newbie in django Source code: models.py: class Users_Keys(models.Model): email = models.EmailField(max_length=255) file_key = models.FileField(max_length=255) date_time = models.DateField() forms.py: from django import forms from .models import Users_Keys class KeyForm(forms.ModelForm): class Meta: model = Users_Keys fields = ('email', 'file_key', 'date_time') view.py: def upload_key(request): if request.method == 'POST': form = KeyForm(request.POST, request.FILES, request.POST) if form.is_valid(): form.save() return render(request, 'index.html') else: form = KeyForm() return render(request, 'upload.html',{ 'form':form }) upload.html: {% extends 'background.html' %} {% block content %} <h2>Add KEY</h2> <form method="POST" enctype="multipart/form-data"> <button class="btn btn-outline-success" type="submit">Upload</button> {% csrf_token %} {{ form }} </form> {% endblock %} -
Why is my delete viewonly deleting the latest entry?
I'm trying to get my delete_entry view to delete the correct entry, however whichever delete button I click, it's referring to the same item_id. I have changed the view so that it prints the entry to be deleted rather than deleting it, and whichever button I choose from the list, it selects the same entry. Is there something in my view that isn't working? My edit functionality is working as expected, so is it worth just changing delete_entry to work in the same way as EditHealth? Health_hub_history.html: {% for item in stats %} <tr> <td>{{ item.user }}</td> <td>{{ item.weight }} </td> <td>{{ item.date }}</td> <td>{{ item.run_distance }}</td> <td>{{ item.run_time }}</td> <!-- Button trigger modal --> <td> <a href="edit/{{ item.id }}"><button type="button" class="btn btn-primary"> Edit </button> </a> </td> <td> <button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#staticBackdrop"> Delete </button> </td> <!-- Modal --> <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel">Are you sure you want to delete this entry?</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> If you just need to amend something, try the edit button. </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button> <a href="delete/{{ item.id }}"><button class="btn btn-danger">I'm sure</button></a> … -
Class Based View Reverse URL not reversing to URL with id
I have different views trying to add a product for one member created on the app not a user with authentication more of a one admin management system. below is my code kindly help much appreciated. I get an error django.urls.exceptions.NoReverseMatch: Reverse for 'read_hairbty' with no arguments not found. 1 pattern(s) tried: ['read_hairbty/(?P[0-9]+)$'] Views.py Create Appointment class HBTYOrderView(BSModalCreateView): model = HbtyOrder template_name = 'accounts/modals/hairbty/create_hbtyordr.html' form_class = HairbtyOrderForm success_message = 'Success: Appointment was created.' success_url = reverse_lazy('read_hairbty') View Appointment class HBTYReadView(generic.ListView): model = HbtyOrder context_object_name = 'hairbty' template_name = 'accounts/modals/hairbty/read_hbty.html' allow_empty = True pk_url_kwargs = 'hbtycustomer_id' paginate_by = 100 def get_queryset(self): qs = self.model.objects.filter(hbtycustomer_id=self.kwargs['pk']).order_by('-date_created') p_f = HbtyOrdersFilter(self.request.GET, queryset=qs) return p_f.qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = HbtyOrdersFilter(self.request.GET, queryset=self.get_queryset()) return context Urls.py path('read_hairbty/<int:pk>', views.HBTYReadView.as_view(), name='read_hairbty'), path('create_hairbtyorder/', views.HBTYOrderView.as_view(), name='create_hairbtyorder'), -
redis-server installation error on ubuntu 18.04
error I'm trying to install redis-server for celery use, but I'm getting an error. how can i resolve it? -
Based on the dropdown value ,store the form data to respective tables in django
Django, I have 3 models, In the html form there is a drop down menu with three value, based on the dropdown value selected ,the data from the form should be stored in the respective model table. Like if the first dropdown selected then on form submission the data should be stored in the first table, and so on. Please provide some inputs on this, thanks.