Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Received(queue) or Executing multiple tasks at same time in celery
I added 10 tasks in celery process. It picks one by one (default celery process). After the completion of first task it picks the second task received and executed . Those tasks are not depending on each other. so I want to run simultaneously or I want to received all the 10 tasks in queue(celery console) and executing one by one. -------------- celery@rana-04 v5.1.2 (sun-harmonics) --- ***** ----- -- ******* ---- Windows-10-10.0.18362-SP0 2021-08-16 13:18:28 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: compfie2:0x2507baac198 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: - *** --- * --- .> concurrency: 8 (solo) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery Celery Command : celery -A rana worker --loglevel=INFO --without-gossip --without-mingle --without-heartbeat -Ofair --pool=solo Any command changes or configurations needed ? Thanks in advance -
change table data to corresponding one in javascript
I have a web app, backend using Django, frontend using HTML5. In the HTML5 page, there's a table, the data are from restful API. I want to change the table data in JavaScript, that is, I want a different table data in different JavaScript if conditions. <table id = "thisTable" contenteditable = 'true' class = "table table-bordered table-sm" width = "100%" cellspacing = "0" style = "font-size: 1.0rem;" id = "bk-table" data - toggle = "table" data - toolbar = "#toolbar" data - cookie = "true" data - cookie - id - table = "materialId" data - show - columns = "true" data - show - refresh = "true" data - show - fullscreen = "true" data - show - export = "true" data - height = "650" { # data - sticky - header = "true" # } { # data - sticky - header - offset - left = "7em" # } { # data - sticky - header - offset - right = "7em" # } data - click - to - select = "true" data - id - field = "id" data - show - footer = "true" data - url = "/api/materials/" data - query … -
Django select multiple model instances of the same user
I have this: user = request.user notifications = Notification.objects.filter(user=user) budget = Budget.objects.filter(user=user) Is there a way to get this data into one query? I was looking into a Subquery or a join query, but I don't know if it can be done. Any idea? -
How to make annotation for foreign key in Django?
I need to replace _points property by annotation so that I have the opportunity to sort entries in the Django admin panel by this value. My model: class CustomUser(models.Model): inviter = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) @property def _points(self): res = CustomUser.objects.filter(inviter_id=self.id).count() return res My admin: class CustomUserAdmin(admin.ModelAdmin): list_display = ['created', 'updated'] def get_queryset(self, request): qs = super(CustomUserAdmin, self).get_queryset(request) qs = qs.annotate(points=(HOW TO CALCULATE _points HERE?).order_by('points') return qs -
How should I write a serializer where a foreign key cold be set by SlugRelatedField OR by the foreign key serializer?
I have a serializer as follow: class MySerializer(serializers.ModelSerializer): """ Serializer for mymodel """ version = VersionSerializer() device = DeviceSerializer() camera = CameraSerializer(many=True) My code needs to be able to create instance of mymodel knowing only one field on my camera foreign key. I can create another serializer like this: class MySerializerSlugRelated(serializers.ModelSerializer): """ Serializer for vision """ version = VersionSerializer() device = DeviceSerializer() camera = serializers.SlugRelatedField(slug_field='my_slug_field', many=True, queryset=Camera.objects.all()) But it seems kind of dirty to recreate an other serializer just to be able to get one field in a different way, is there a clean way to do this ? Thanks -
I'd like to apply the code from the view to the template tag
I am a student who is learning Django. Code created in view to float an optionless product. I want to change this to a template tag and print out p-tags only for products without options, how can I change it? option_test = Option.objects.values_list('product_code').filter(product_code=None) views.py def product_detail(request, id, product_slug=None): current_category = None categories = Category.objects.all() product = get_object_or_404(Product, product_code=id, slug=product_slug) designated_object = Designated.objects.filter(rep_price='True') element_object = Element.objects.all() photo_object = Photo.objects.all() option_object = Option.objects.all() value_object = Value.objects.all() delta = product.due_date - datetime.now().date() delta_result = delta.days print(delta_result) option_test = Option.objects.values_list('product_code').filter(product_code=None) return render(request, 'zeronine/detail.html', {'product': product, 'option_test':option_test, 'current_category': current_category, 'categories': categories, 'designated_object': designated_object, 'element_object': element_object, 'photo_object':photo_object, 'option_object': option_object, 'value_object': value_object, 'delta': delta, 'delta_result': delta_result, }) template <p>hello.</p> -
Debugger in Django not stopping at breakpoints after the initial setup
I'm having a problem with the debugger in Django (which I've run both by pressing the green arrow as well as F5). I've set a number of breakpoints on the URLs and the Views, and the debugger stops on the breakpoints only the first time when setting up the server, but when the server is up and I go to the browser (to invoke a URL or a View), the debugger don't "freeze" the browser as it should and let me walk trough the breakpoints, but just goes straight trough as if it wasn't run at all. I've read that this could be caused by some bug in Python version 3.9 > so I've downgraded to using Python 3.8.0 in my environment, but still no luck. I'm using the interpreter connected to the current virtual environment I'm in: I'm using: Django version 3.2.4 Python 3.8.0 (also tried with Python 3.9.6) Pipenv for virtual environment version 2021.5.29 Launch.JSON: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/jobs/manage.py", "args": [ "runserver" ], "django": true, … -
How to customize the admin dashboard for a specific model in Django when adding?
How customize the admin dashboard for a specific model in Django? I have some models. I want to add a JS or CSS file in the admin dashboard when I add an object? -
How to make to structure the model for this type of problem in django?
I want to make a table like in image but i am confused how to structure the model to do it in django? -
Templateview in django has gone error "Field 'id' expected a number but got 'form_file' "
This is my view.py file `class UploadTemplateView(TemplateView): template_name = 'reports/from_file.html' ` This is my urls.py file path('save/', create_report_view, name='create-report'), path('', ReportListView.as_view(), name='main'), path('from_file/', UploadTemplateView.as_view(), name='form-file'), path('<pk>/', ReportDetailView.as_view(), name='detail'), path('upload/', csv_upload_view, name='upload'), path('<pk>/pdf/', render_pdf_view, name='pdf'), ]``` When I try to access my page it cost an error "Field 'id' expected a number but got 'form_file' The only way to fix it is by changing the pathname to number. How can I define pathname as a string -
Serve React with docker and nginx, which is already serving django
I am creating a web-app using the django + react + nginx + docker tech-stack. I can successfully serve my django REST API, admin panel and its static files using nginx but cannot serve the react app after build. I can see the browser tab logo, but it seems my index.html is not found. I get a bunch of 404s in the logs. It seems like it is always looking inside the django's /var/www/staticfiles directory. I have dockerised all the web-app components and this are the relevant components that are used once I get docker-compose up and running: My docker-compose.yml: version: "3.9" services: client: build: context: ../client/ container_name: my_client image: my/client networks: - my_network volumes: - client:/client/build ... nginx: container_name: my_nginx_server image: nginx depends_on: - client - web_service networks: - my_network ports: - 80:80 - 8080:8080 restart: always volumes: - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro - client:/var/www/client - static:/var/www/staticfiles/static networks: my_network: driver: bridge volumes: client: db: static: When I inspect the nginx container, all the files are successfully inside /var/www/client. My react app Dockerfile: FROM node:14.17.5-alpine as build WORKDIR /usr/src/client # Set up env ENV PATH /client/node_modules/.bin:$PATH # Install app dependencies COPY ./ ./ RUN yarn install --silent # Create build dir RUN yarn … -
Trying to fetch data from api by id search using flutter and the http.get is not parsing the data get from api
Future<List> fetchGraduates() async { var response = await http.get( Uri.parse('http://127.0.0.1:8000/graduates/image_api/A/ur4444/09')); var response2=await http.get( Uri.parse('http://127.0.0.1:8000/graduates/student_api/A/ur4444/09')); Map<String, dynamic> studentData = jsonDecode(response.body); Map<String, dynamic> imageData = jsonDecode(response2.body); Map<String, dynamic> data = { 'id': studentData['student'], 'first_name': studentData['first_name'], 'middle_name': studentData['middle_name'], 'last_name': studentData['last_name'], 'image': imageData['image'], 'institution': studentData['institution'], }; -
How to use serializer field and make response of the data from the choice field in django rest framework
How to use serializer field in DRF models.py class User(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=255, null=True, unique=True) birthdate = models.DateField(null=True, blank=False) gender_choice = [ ('male','male'), ('female','female') ] gender = models.CharField(max_length=255, choices=gender_choice, default='male', null=True) the rest ans is in the below -
Django Rest Framweork - Why first pagination offset starts from 0 and how to change it to 1?
I am trying to create a custom Limit and Offset Paginator but first page starts from zero which I don't know why!. The offset limit is set to 1 but within url it starts from 0, what I want is to start offset from zero which in my case is page parameter. from rest_framework.pagination import LimitOffsetPagination min_num = 10 max_num = 50 class ApiPagination(LimitOffsetPagination): default_page = 1 min_limit = min_num max_limit = max_num min_offset = min_num max_offset = max_num limit_query_param = 'size' offset_query_param = 'page' def get_paginated_response(self, data): next_url = self.get_next_link() previous_url = self.get_previous_link() first_url = self.get_first_link() last_url = self.get_last_link() return Response( { 'Data': data, 'Links': { 'Self': first_url, 'Last': last_url, 'First': first_url, 'Next': next_url, 'Prev': previous_url, }, 'Meta': { 'TotalPages': self.count - self.limit if self.offset not in [0, 1] else 1, 'Count': self.count, } } ) def get_first_link(self): pass def get_last_link(self): pass -
Django App deployed on Heroku works despite wrong SECRET_KEY
In my Django project I have an .env file which holds my DJANGO_SECRET_KEY environment variable: export DJANGO_SECRET_KEY=dummysecretkey123 I added a reference to the .env file in my .gitignore file before I initialized the repo, so the SECRET_KEY should not be visible in any repo tracked by git In my settings.py I set my SECRET_KEY as follows: SECRET_KEY = env.str("DJANGO_SECRET_KEY") For deployment on Heroku I added SECRET_KEY via Config Vars in the Heroku Dashboard - everything worked as expected. Then out of curiosity, I changed the SECRET_KEY in Heroku to a wrong value to see its effect. To my surprise the app was still online and working. I restared all dynos, but nothing changed. Then I checked the Heroku server's environment variables via heroku run python manage.py shell > import os > print(os.environ) and could see the deliberately set wrong value for SECRET_KEY What am I missing here? Isn't the purpose of the SECRET_KEY to protect my app, meaning that if it is not set properly, the app should not be working? -
Having trouble displaying entry posts and comments on front page
I have tried to solve this issue for at least 8 hours and I am probably missing something very simple. But since I am very new to programming I want to reach out for a little help. I am working on a simple page where visitors can post entries (think small blog post) and other visitors can comment on the post entries. Currently you can visit each post and see the comments by going directly into them (example: testsite.com/discussions/1 (or 2, 3 etc). But I can't for the life of me figure out how to display all posts and their respective comments on ONE page. Here is my Models-view: from django.db import models import uuid from django.db.models.fields import AutoField # Create your models here. class Post(models.Model): entry = models.CharField(max_length=2000) image = models.ImageField(null=True, blank=True, default="default_post.jpg") created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.entry class Comments(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) comment_entry = models.CharField(max_length=2000, blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created_on'] def __str__(self): return self.comment_entry Here is my Views: from django.shortcuts import get_object_or_404, render from .models import Post, Comments # Create your views here. def discussion(request, post_id): post = get_object_or_404(Post, pk=post_id) return render(request, 'discussions/discussions.html', {'post': post, 'replies': Comments.objects.filter(post_id=post_id)}) And here is … -
Sending S/MIME Signed Mails with Django
Is there a way to use the wrappers provided by Django to send signed or even encrypted emails? We use S/MIME in our company and it's required that all mails are signed. I currently send emails via SendGrid: EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = "<email_password>" EMAIL_PORT = 587 EMAIL_USE_TLS = True -
How do I store a cloned data into the database
I have the following page right now which is using django form with 3 different models and they are all linked upon saving. Image:Page shown upon adding new device But if i add another module and save. It only saved the last cloned row into the database, ignoring whatever I have type in the 1st row for module. Image: Adding new device with extra module How do I solve this? Below are my following codes: views.py def device_add(request): if request.method == "POST": device_frm = DeviceForm(request.POST) ##Part A1 dd_form = DeviceDetailForm(request.POST) di_form = DeviceInterfaceForm(request.POST) if device_frm.is_valid(): # Create and save the device # new_device here is the newly created Device object new_device = device_frm.save() if dd_form.is_valid(): # Create an unsaved instance of device detail deviceD = dd_form.save(commit=False) # Set the device we just created above as this device detail's device deviceD.device_model = new_device # If you did not render the hostname for the device detail, set it from the value of new device deviceD.hostname = new_device.hostname deviceD.save() if di_form.is_valid(): deviceI = di_form.save(commit=False) deviceI.modulekey= new_device deviceI.hostname = new_device.hostname deviceI.save() new_device=Device.objects.all() return render(request, 'interface/device_added.html',{'devices':Device.objects.all()}) # if invalid (dd_form) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) # If invalid (device_frm) else: return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) … -
Can't pass String from react to django using axios
I'm trying to send a request from react to django that has the following body: { "category":"string" } I send the request from react like this: axiosInstance .get(`answers/`, { category:currentQuiz },config).then((res) => { console.log(res.data) }) .catch((function (error) { console.log(error) })) where currentQuiz is a string gived as parameter to my function. In my django View that's how i get the data and process it: def get(self,request): data = request.data['category'] print(data) # quizName The problem is that my django view doesn't receive any data, only an empty dictionary ( i tried to modify data = request.data[category] in data = request.data and it will print an empty dictionary). print(data) With data = request.data[category] returns: data = request.data['category'] KeyError: 'category' [16/Aug/2021 09:29:43] "GET /api/answers/ HTTP/1.1" 500 19145 I tested my django view with the following body using PostMan and everything works properly, so the problem must be caused by the frontend: { "category":"Protecție" } I tried the following methods but it won't work: 1) axiosInstance .get(`answers/`, { data : { category:currentQuiz } },config).then((res) => { console.log(res.data) }) .catch((function (error) { console.log(error) })) 2) axiosInstance .get(`answers/`, { category:JSON.stringify(currentQuiz) },config).then((res) => { console.log(res.data) }) .catch((function (error) { console.log(error) })) -
django template backend for Jinja2
is there difference between TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', ....... }, ] and (imported from django-jinja package) TEMPLATES = [ { "BACKEND": "django_jinja.backend.Jinja2", ....... }, ] -
How to format django timezone.now()
The default format of django timezone.now() example Aug. 15, 2021, 1:00pm how to convert this into 2021-8-15 thanks in advance! -
Django ModuleNotFoundError: No module named 'EmailIngestionDemo.EmailIngestionDemo'
Im trying to write a django web that will retrieve data from postgresql and display on it. But whenever I run my application it show me: from EmailIngestionDemo.EmailIngestionDemo.models import EmailData ModuleNotFoundError: No module named 'EmailIngestionDemo.EmailIngestionDemo' On my views.py I import my EmailData from EmailIngestionDemo.EmailIngestionDemo.models: Views.py from django.shortcuts import render from EmailIngestionDemo.EmailIngestionDemo.models import EmailData def showdata(request): results = EmailData.obj.all() return render(request, 'index.html',{"data":results}) This is my path: settings: import os from pathlib import Path # 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/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'xxx' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'EmailIngestionDemo' ] 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', ] ROOT_URLCONF = 'EmailIngestionDemo.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'EmailIngestionDemo.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME':"EmailData", 'USER':"postgres", 'PASSWORD':"xxx", 'HOST':"localhost", 'PORT':'5432' } } # … -
My function call the return before the rest of the code
So I am trying to loop through the list of classes see if there is a match or not if there is a match return a Response and say there is a match otherwise register the student I am using django and django-restframework Here is my code @api_view(['POST']) @permission_classes([IsAuthenticated,]) def createOrderForOnlineClasses(request): user = request.user data = request.data Class = OnlineClass.objects.get(id= data["classId"]) orderCred = { 'pin' : 'SOME_PIN', 'amount' : int(Class.totalPrice), 'callback' : 'http://localhost:3000/verify/', } for i in user.userprofile.onlineClass.all(): if i.id == Class.id: return Response({"details": "Already registered"}, status=status.HTTP_400_BAD_REQUEST) try: response = requests.post("https://panel.aqayepardakht.ir/api/create", data=orderCred) if response.status_code == 200 and not response.text.replace('-',"").isdigit(): # url ='https://panel.aqayepardakht.ir/startpay/'+response.text registeredClass = RegisterStudentForOnlineClass.objects.create( user=user, totalPrice = int(Class.totalPrice), transId = response.text, onlineClassName= Class ) serializer = RegisterForClassSerializer(registeredClass , many=False) print(serializer.data) return Response(serializer.data) else: return Response({"details": "Error"} , status= status.HTTP_400_BAD_REQUEST) except Exception as e: return Response({"details": f"{e}"}) return Response({"details":f"{Class}"}, status=status.HTTP_400_BAD_REQUEST) So the problem is the function call the return Response({"details":f"{Class}"}, status=status.HTTP_400_BAD_REQUEST) first and the rest wont work Thank you :) -
Send data with POST-request wont work in Django with AJAX
First of all: I know, there are a few solutions for this online, but they wont work for me (because they use e.g. Jason or are just outdated) I work on a project in Django and want to use ajax for one task: I want to pass data, after it was processed by ajax, from my template file to my views file (with a POST request), to again make it visible in my templates file. Templates-file --> Proccessed data --> POST-request --> views.py --> Template-file But it just wont work for me. My HTML-Templates-File: ... <script type="text/javascript"> var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); function csrfSafeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $.ajax({ url: "/save", data: { 'value': inputDataArray //I have already defined "inputDataArray" before }, success: function (res, status) { alert(res); alert(status); }, error: function (res) { alert(res.status); } }); </script> My views.py file: def save(request): if request.method == 'POST': request_getdata = request.POST.get("value", None) return render(request, "response.html", {"data":request_getdata}) So I try display it at "response.html"... {{data}} ...but it just will reload the current page and does not pass any data to the response.html-file. Does anyone knows what my … -
DRF-How to save foreign keys data using APIView
everyone, I am absolutely a beginner in DjangoRestFramework. I have confusion to deal with relationships in DRF. How do I save foreign keys data using APIView? models class User(AbstractUser): email = models.EmailField(max_length=255, unique=True) is_client = models.BooleanField(default=False) is_professional = models.BooleanField(default=False) class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='client') ## class Professionals(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='professional') ## class HireProfessional(models.Model): client = models.ForeignKey(Client, related_name='user', on_delete=models.CASCADE) professional = models.ForeignKey(Professionals, on_delete=models.CASCADE, related_name="professsional") hire_start_date_time = models.DateTimeField(default=timezone.now) Serializers class ProfessionalSerializer(serializers.ModelSerializer): profilePicture = serializers.ImageField(allow_empty_file=True, use_url='professional/profiles', required=False) skill = SkillSerializer(many=True,read_only=True) class Meta: model = Professionals fields = fields = ['first_name', 'last_name', 'profilePicture', 'profession', 'phone_number', 'experience', 'skill', 'charge_fee', 'about_me'] class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = ['user_id', 'first_name', 'last_name', 'phone_number', 'profilePicture'] class UserSerializer(serializers.ModelSerializer): client = ClientSerializer() professional = ProfessionalSerializer() class Meta: model = User fields = ('email', 'username', 'is_client', 'is_professional', 'client', 'professional') class HireProfessionalSerializer(serializers.ModelSerializer): client = ClientSerializer() professional = professionalSerializer() class Meta: model = HireProfessional fields = ['id','client', 'professional', 'hire_start_date_time'] This is a hiring app. Client able to hire to professional client=logged in user professional=passed id or username through URL like: path('hire-professional/<professional id or username>', views) Does anybody have any idea? how to solve it.