Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset of related objects
Having the following model: class Company(models.Model): name = models.CharField(max_length=10) class Department(models.Model): name = models.CharField(max_length=10) company = models.ForeignKeyField(to=Company) persons = models.ManyToManyField(to=Person, on_delete=models.PROTECT) class Person(models.Model): name = models.CharField(max_length=10) I would like to get a queryset of all persons in a company Using def persons_by_company(company_name): l = [] for d in Department.objects.filter(company__name=company_name): for p in d.persons: l.append(p) return l would be slow does return a list and not a queryset (is not filterable, etc) What would be the way to get a queryset here? -
How to add my already purchased SSL certificate to my free Heroku app?
I already have an SSL certificate that I bought with my domain from Namecheap, but when I go to add the certificate to Heroku it says I need to either have a Hobby or Professional dyno to be able to use SNI SSL? Does this mean you can't have Https:/ websites with the free version of Heroku? Or is there any way to upload my SSL certificate not using SNI SSL? -
Async Django 3.1 with aiohttp client
Is it possible now, after the start of porting django to async to use aiohttp client with django? My case: server receives a request; server sends another request to another server; server decodes the response, saves it into DB, and returns that response to the client; Andrew Svetlov mentioned that aiohttp "was never intended to work with synchronous WSGI" two years ago. (https://github.com/aio-libs/aiohttp/issues/3357) But how the situation looks now? Django seems to almost support async views. Can we use aiohttp with asgi django? I know, I can create an aiohttp server that handles requests, then populates some queue, and queue handler that saves responses into database, but here I am missing a lot from django: ORM, admin, etc. -
Using NATS.io with Django
I'm trying using NATS in a Django project. But can't find exaples how include it. Nats documentations show how include it as simple file https://github.com/nats-io/nats.py I need publish from view. And subscribe to NATS somewere. -
How to dynamically create an entry through many to many field?
I have models.py class Lesson(models.Model): title = models.CharField(max_length=50) description = models.TextField(blank=True) def __str__(self): return self.title class Course(models.Model): title = models.CharField(max_length=50) description = models.TextField() lessons = models.ManyToManyField(Lesson) #course can have multiple lessons and lesson can belong to multiple courses. def __str__(self): return self.title what I want is when I try to save an instance of Course, I should be able to add new lessons allong with those already present in Lesson Model. The Lesson instance should be created in Lesson model and then many to many reference added to that Course model. ' I have additinal field in forms.py for add new lessons. The input will be quamma separated Lessons. forms.py class CourseForm(forms.ModelForm): add_more = forms.CharField(widget=forms.Textarea) class Meta: model = Course fields = ['title','description','lessons'] labels={ "title": "Course Title" } How to achieve it ? -
Django CMS - General workarounds when problem solving in Django CMS [closed]
I'm working with Django CMS and I like a lot of it, but there does show a hand full of problems when using it. To take an example the toolbar don't push the content down... so it lays over the navigation bar, so I fixed it by make a section in the CSS that I comment out when ever I'm not working on the site, that pushes body down. This it okay if it was just this, but there keeps coming up small problems, how do you guys deal with them? Right now I use JS to fix some of the things, is that the same way you guys do it or do you have you own models file you create every new project that solves the problems there is? -
Django url passing as many parameters as you want delimited by /
How can I define the URL pattern so that I can pass to an URL as many parameters as I want? I really researched the documentation and other stackoverflow questions but I didn't found something similar to that. I need this to work as a filter for an ecommerce website. I would like to achieve something like this: urlpatterns = [ path('test/<str:var1>-<str:var2>/<str:var3>-<str:var4>/...', views.test, name='test'), ] And in my view function I would define it like that: def test(request, *args, **kwargs): # Do whatever you want with kwargs return HttpResponse('Test') -
SMTPAuthenticationError at /accounts/signup/ allauth django on sending confirmation email
Hi there I'm encountering an issue on my app in production whereby I'm using allauth to handle my authentication, when i try to signup I get redirected to an error page showing an error in sending a confirmation email on signing up Looking at it I thought it might be due to having my google account setting (since I'm using google for smtp host ) for allowing less secure apps to be off but it is on so I'm stuck on how to solve this. I'm thinking of removing email from signup process since no confirmation email will be sent in that case Note that the redirect works perfectly fine on my development server -
API endpoint to return Django model choices
I have a program with a Django backend (Django + Django RestFramework) with a React frontend. In my React frontend I need to create a dropdown to display a list of options that are valid choices for my Django model ("Foo," "Bar," and "Baz"). models.py from django.db import models from model_utils import Choices from model_utils.fields import StatusField from model_utils.models import TimeStampedModel class MyCustomModel(TimeStampedModel): STATUS = Choices("Foo", "Bar", "Baz") details = models.TextField() status = StatusField() serializers.py from rest_framework import serializers from custom.models import MyCustomModel class MyCustomModelSerializer(serializers.ModelSerializer): class Meta: model = MyCustomModel fields = "__all__" views.py from rest_framework import generics from custom.models import MyCustomModel from custom.serializers import MyCustomModelSerializer class DetailsView(generics.ListCreateAPIView): queryset = MyCustomModel.objects.all() serializer_class = MyCustomModelSerializer urls.py from django.urls import path from custom.views import DetailsView app_name = "custom" urlpatterns = [ path("api/custom/details/", DetailsView.as_view(), name="details"), path("api/custom/details/statuses/", DetailStatusesView.as_view(), name="detailStatuses"), # <-- how to implement this? ] Given what I have already layed out above...I want to implement the view so that when I go to my "detailStatuses" endpoint, I am returned a response like (which is just a list of values defined in MyCustomModel): { "statuses": [ "Foo", "Bar", "Baz" ] } -
Django Model with API as data source
I want to create a new model which uses the https://developer.microsoft.com/en-us/graph/graph-explorer api as a data source as i want to have additional info on the user. Using a computed property on the model does not work as it is going to query for each instance. So i want to have the model relate to a new model which has the api as it´s data source. I could not find anything on this topic -
Django autocomplete light auto unfocus
I'm using django-autocomplete-light and work on tags. I type a tag, find it and choose it but when I do that, the field "unfocus" it-self and get out of the input. So I have to re-click in the field to continue to type tags, over and over again if I want to choose tags. Is there a way to stop that? Thank you. Best regards. -
Django count persons by month and year
I've been debugging for I while but I can't get the right result. In my django application I have extended the auth_user to add more fields: from django.contrib.auth.models import User class Person(User): api_id = models.CharField(max_length=255) api_key = models.CharField(max_length=255) Now, I want to count users by year and month according to the date they joined: Person.objects.annotate(year=TruncYear("date_joined"), month=TruncYear("date_joined")).values("year", "month").annotate(count=Count("pk")) However, all I get is a count=1 for each user in the database without grouping them by year and month. This is the actual query being executed: SELECT CAST(DATE_FORMAT(CONVERT_TZ(`auth_user`.`date_joined`, 'UTC', 'Europe/Madrid'), '%Y-01-01 00:00:00') AS DATETIME) AS `year`, CAST(DATE_FORMAT(CONVERT_TZ(`auth_user`.`date_joined`, 'UTC', 'Europe/Madrid'), '%Y-%m-01 00:00:00') AS DATETIME) AS `month`, COUNT(`mt_api_app_person`.`user_ptr_id`) AS `count` FROM `mt_api_app_person` INNER JOIN `auth_user` ON (`mt_api_app_person`.`user_ptr_id` = `auth_user`.`id`) GROUP BY CAST(DATE_FORMAT(CONVERT_TZ(`auth_user`.`date_joined`, 'UTC', 'Europe/Madrid'), '%Y-01-01 00:00:00') AS DATETIME), CAST(DATE_FORMAT(CONVERT_TZ(`auth_user`.`date_joined`, 'UTC', 'Europe/Madrid'), '%Y-%m-01 00:00:00') AS DATETIME), `auth_user`.`date_joined` ORDER BY `auth_user`.`date_joined` DESC All count=1 seem to occur because of the GROUP BY [...] 'auth_user'.'date_joined' which is grouping the entries by the whole datetime and not just month and year. Any clues of what's happening here? If I do the same query but with the User I get what I want. -
How to execute docker-entrypoint-initdb.d/init.sql files AFTER database is created?
I have a Django app with Docker I want to initialize my database based on init.sql file when running docker-compose up 2 containers are correctly built and init.sql file is available in db_container but docker logs db_container show an error indicating that database has not been migrated yet: ERROR: relation table1 does not exist Database is created when entrypoint.sh files is executed (command python manage.py migrate) I do not understand when init.db is executed? Dockerfile FROM python:3.8.3-alpine WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev RUN apk --update add libxml2-dev libxslt-dev libffi-dev gcc musl-dev libgcc openssl-dev curl RUN apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev RUN pip3 install psycopg2 psycopg2-binary COPY requirements/ requirements/ RUN pip install --upgrade pip && pip install -r requirements/dev.txt COPY ./entrypoint.sh . COPY . . # Run entrypoint.sh ENTRYPOINT [ "/usr/src/app/entrypoint.sh" ] entrypoint.sh #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." # nc = netcap -z = scanning while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi python manage.py flush --no-input python manage.py migrate exec "$@" docker-compose.yml version: '3.7' services: web: ... depends_on: - … -
I want to create Flutter app using Django backend
I want to learn flutter with django backend is there is a any course where I can get complete information about flutter with django and I also want to create a professional and production level shopping application which has fully functional with frontend and backend using flutter and django so there is any course so I can learn about this -
How can I make one of the fields in admin.TabularInline conditional?
Is there a way how can I make one of the fields in admin.TabularInline conditional? for example class ParameterInline(admin.TabularInline): form = ParameterForm fields = ["ParameterA", "ParameterB"] What if I wanted to display the ParameterB only if something else was set to, for example, True? Thanks in advance. -
How to update a table in postgres with query result from another table
I was using Django queryset to sum up DurationField (Interval) but it gives me wrong results and just find out in the documentation that DurationField are not reliable. How do I do the following queries in Postgres? Django Queries: aggr_hours = TimeLog.objects.filter(employee=employee_id, end_date__gte=(2020-10-1 ).annotate(sum_hours=(Sum(F('time_worked'), output_field=DurationField()))) Then I will use aggr_hours to update the other table like this; Employee.objects.filter(id=employee_id).annotate(total_hours=Subquery(aggr_hours.values( 'sum_hours')[:1], output_field=DurationField())).update(hours=F('total_hours')) Everything sql syntax I tried threw an error File "<ipython-input-34-6dcf7e015594>", line 1 UPDATE payroll_employee ^ SyntaxError: invalid syntax -
How to add more fields to custom User in Django?
I'm trying to pass more fields to my user when it gets registered but no luck. so far the only thing I can get in validated_data is username and password. How can I get data such as is_doctor there? Or perhaps I'm looking at the wrong place. the fields do get created in the User table with their defaults, I can't override them with true, though. class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_secretary = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password', 'is_doctor', 'is_secretary', 'is_patient') extra_kwargs = {'password': {'write_only': True, 'required': True}} def create(self, validated_data): # validated_data only contains username and password. I wish it could have 'is_doctor' user = User.objects.create_user(**validated_data) token = Token.objects.create(user=user) return user class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (AllowAny,) Below is JavaScript in the frontend trying to create new user in the api function registerUserAndDoctor(values) { const credentials = { ...values //contains 'is_doctor: true' } fetch(`${process.env.REACT_APP_API_URL}/api/user/`, { method: "POST", headers: { "Content-type": "application/json" }, body: JSON.stringify(credentials), }) .then((resp) => resp.json()) .then((res) => { console.log("res USER>>", res); }) .catch((error) => console.log(error)); } -
Filtering by annotated field of a related model
I am calculating a field on the fly (=not storing in the DB) and need to filter a related model by that field. My questions are as follows: Any ideas how can I filter over related fields that are calculated? I would like to understand how Django handles queries (e.g. whether / if / when it is returning a QuerySet and operating on that or if it's hitting the DB directly). If someone could point out to me the relevant documentation, that would be much appreciated! Additional information My Models (models.py) from .managers import StackManager, PartManager class Build(models.Model): ... class Part(models.Model): build = models.ForeignKey('Build', models.CASCADE, related_name='parts') x_min = models.FloatField() x_max = models.FloatField() y_min = models.FloatField() y_max = models.FloatField() z_min = models.FloatField() z_max = models.FloatField() volume = models.FloatField() objects = PartManager() class Stack(models.Model): build = models.OneToOneField('Build', models.DO_NOTHING, related_name='stack') height = models.FloatField() objects = StackManager() My Model Managers and QuerySet Managers (managers.py) class StackQuerySet(models.QuerySet): def calc(self,**kwargs): valid_parts = self.filter( build__parts__y__lte=F('height'), ) \ .annotate( total_built_parts_volume = Sum(F('build__parts__volume')) ) return valid_parts class StackManager(models.Manager): def get_queryset(self): return StackQuerySet(self.model, using=self._db) class PartManager(models.Manager): def get_queryset(self): return super().get_queryset()\ .annotate( x = F('x_max') + F('x_min'), y = F('y_max') + F('y_min'), z = F('z_max') + F('z_min') ) What I am … -
django commands ' py manage.py runserver / makemigrations / migrate' not working as expected
Hi there I wanted to run a project ive been working on but on running py manage.py runserver i got unfamilliar output in the command line instead of the usual output showing that the development server is running I have no clue whatsoever has caused this Its the same thing if i run makemigrations or migrate any pointers -
Integrate Opencv with Django
I want to integrate OpenCV into my django Project. I'm have no idea of how to do that. I've gone through some tutorials and customized my code as follows: Image Model: import os import datetime import uuid from django.db import models from django.contrib.auth import get_user_model from config import abstract_model from PIL import Image import numpy as np from django.core.files.base import ContentFile from .utils import get_detected_image from io import BytesIO User = get_user_model() class FileManager: @staticmethod def photo_path(instance, filename): basefilename, file_extension = os.path.splitext(filename) date = datetime.datetime.today() uid = uuid.uuid4() return f'Chekced_Images/{instance.user.email}/{uid}-{date}{file_extension}' class RawImage(abstract_model.BaseAbstractModel): user = models.ForeignKey( User, on_delete=models.DO_NOTHING, related_name='checked_images' ) image = models.ImageField(upload_to=FileManager.photo_path, null=True, blank=True) is_detected = models.BooleanField(default=False, blank=True, null=True,) def __str__(self): return f'{self.user}\'s checked image on {self.posted_on}' def save(self, *args, **kwargs): # Open Image pil_img = Image.open(self.image) # convert image to array cv_img = np.array(pil_img) # check the image img = get_detected_image(cv_img) # convert the image from the array detected_img = Image.fromarray(img) # Save image buffer = BytesIO() detected_img.save(buffer, format='png') image_png = buffer.getvalue() self.image.save(str(self.image), ContentFile(image_png), save=False) super().save(*args, **kwargs) Object detection Function as follows: import cv2 as cv import numpy as np def get_detected_image(image): main_image = cv.imread('./needle_image.jpg', cv.IMREAD_REDUCED_COLOR_2) template = cv.imread('./template_image.jpg', cv.IMREAD_REDUCED_COLOR_2) result = cv.matchTemplate(main_image, template, cv.TM_CCOEFF_NORMED) # Get the best … -
Python Django framework to process image in client side
I am very new to Python and Django framework. Requirement: Company B buys Company A, the existing company has n-number of user guide images(which has company A's logo on top). A small change was made by company B in logos. The plan is to patch on top of the existing image with a new logo. I have created a POC tool using python and libraries called Tkinter, PIL, OS. Inputs as an absolute path. Button 'Get image' will iterate all the images inside the folder using OS, display preview image and process each image by PIL. Now, I am trying to do the same as a web application. So I took the Django framework in python. Here, User will choose an existing image folder and new log image by HTML file type. Since I don't need a database, whether the Django framework is a good way of approaching to process the image in the client-side? Should I go with forms.FileField, static files concepts? which are quite hard to understand. Otherwise, should I need to go with forms.CharField(get the absolute path as input)? Preview the image is looks difficult without Django DB modules. I am tried analysing these thing couples of … -
TypeError at / __init__() takes 1 positional argument but 2 were given
I copied this code from maxg203 https://github.com/maxg203/Django-Tutorials I had another errors but I managed to solve them but when it came to this one I stayed for a solid 4 hours trying to solve it and until now I didn't manage to I am still a beginner in Django My Models.py: from django.db import models from django.contrib.auth.models import User class Post(models.Model): post = models.CharField(max_length=500) user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Friend(models.Model): users = models.ManyToManyField(User) current_user = models.ForeignKey(User, related_name='owner', null=True, on_delete=models.CASCADE) @classmethod def make_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user=current_user ) friend.users.add(new_friend) @classmethod def lose_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user=current_user ) friend.users.remove(new_friend) my Views.py: from django.views.generic import TemplateView from django.shortcuts import render, redirect from django.contrib.auth.models import User from home.forms import HomeForm from home.models import Post, Friend class HomeView(TemplateView): template_name = 'home/home.html' def get(self, request): form = HomeForm() posts = Post.objects.all().order_by('-created') users = User.objects.exclude(id=request.user.id) friend = Friend.objects.filter(current_user=request.user) friends = friend.users.all() args = { 'form': form, 'posts': posts, 'users': users, 'friends': friends } return render(request, self.template_name, args) def post(self, request): form = HomeForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() text = form.cleaned_data['post'] form = HomeForm() return redirect('home:home') args = {'form': form, 'text': … -
Why I get ERR_CONNECTION_RESET error on file uploading large files to Django rest API?
I have an Angular client-side and Django rest API for the backend that is running on the Nginx web server. I pass the file as FormData from the client-side to the server-side. On the server-side I get file data and write it as a file. When files are small (about 1mb to 2mb) everything works fine but I want to upload larger files I get ERR_CONNECTION_RESET. Why that happens and how can I fix it? -
DJANGO-how to add TokenAuthentication to url (HttpResponse)
I have function that is : def Program(requests ): . . . return HttpResponse() and that does many stuffs like adding data to dataBase and when I request it from urls.py by GETMETHOD , it does many stuffs urls.py: from django.urls import path , include from .tes import Program urlpatterns = [ path('newgp/', Program, name='Program' ), ] and its allow any for all of the requests now I want to authenticate this url by Authorization-Token but I dont know how! HELP PLEASE -
Store json api result into ManyToManyField
I created a classic model in which there is a ManyToManyField. The objective is to fill the ManyToManyField field with the results of the API. I can't manage to save the data correctly in this field. The idea would be to check if this field already exists according to the API results: if the result already exists then you just have to select it. If it doesn't exist then you have to create it and then select it. I don't really understand how that works? Could you please help me to understand? class ListAliments(models.Model): name = models.CharField(max_length=40, unique=True) slug = models.SlugField(editable=False) status = models.IntegerField(choices=STATUS, default=1) def save(self, *args,**kwargs): if not self.slug: self.slug = unique_slugify(self, slugify(self.name)) super(ListAliments, self).save(*args, **kwargs) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=190) aliments = models.ManyToManyField('ListAliments',blank=True,related_name='listaliments_post') url_image = ... def save(self, *args, **kwargs): if not self.slug: self.slug = unique_slugify(self, slugify(self.title)) if self.url_image: request = ... response = ... if response: self.aliments = response[0]['outputs']['data']['concepts']['name'] super().save(*args, **kwargs)