Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
Pillow not found after building wheels
I am running django project on docker which runs fine but I setup a production environment which installs pip packages from built wheels. but now am getting error trying to run migration am getting: "(fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow" Here is my dockerfile # BUILDER # ########### # pull official base image FROM python:3.8.3-alpine as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install system dependencies RUN apk update \ && apk add gcc musl-dev postgresql-dev zlib \ python3-dev jpeg-dev zlib-dev openssl-dev libffi libffi-dev # lint RUN pip install --upgrade pip RUN pip install flake8 COPY . . RUN flake8 --ignore=E501,F401,E731,E722,F403,F405 . # install dependencies COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt ######### # FINAL # ######### # pull official base image FROM python:3.8.3-alpine # create directory for the app user RUN mkdir -p /home/app # create the app user RUN addgroup -S app && adduser -S app -G app # create the appropriate directories ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME WORKDIR $APP_HOME # install dependencies RUN … -
CSV file import-Django(Only 1 row of data is getting imported)
I am trying to upload CSV file content to database but observed that only first row of data is getting updated and also if data with same value present then it's simply ignoring. And also can we use open with logic so that once task is completed it should get close automatically. My Views.py import csv, io from django.shortcuts import render from django.contrib import messages # Create your views here. # one parameter named request def contact_upload(request): # declaring template template = "testapp/upload.html" data = Movie.objects.all() # prompt is a context variable that can have different values depending on their context prompt = { 'order': 'Order of the CSV should be releasedate, moviename, hero, heroine, rating', 'profiles': data } # GET request returns the value of the data with the specified key. if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] # let's check if it is a csv file if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') data_set = csv_file.read().decode('UTF-8') print(data_set) io_string = io.StringIO(data_set) next(io_string) # setup a stream which is when we loop through each line we are able to handle a data in a stream for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created … -
Django Project is not getting displayed/created
I am using virtual environment to create a django project. On running "django-admin startproject tutorials", command is getting executed successfully, but project is not yet created. On running the same command("django-admin startproject tutorials") again. it is throwing error as CommandError: 'C:\Users\abhinavkumar\Documents\mysql.python\tutorials' already exists. While doing dir I can see that tutorials is not present. Directory of C:\Users\abhinavkumar\Documents\mysql.python 30-09-2020 17:50 <DIR> . 30-09-2020 17:50 <DIR> .. 28-09-2020 10:36 <DIR> database 16-09-2020 12:08 <DIR> venv 04-09-2020 17:01 <DIR> __pycache__ 0 File(s) 0 bytes 5 Dir(s) 865,337,741,312 bytes free -
Django CMS - Content only shown if on /?edit and logged in?
Hello there Django folks! I think there is some info I missed somewhere in the documentation, I have a project where I only can se the content if I am logged in. Perhaps it's a setting somewhere, anyone have a clue where I should look for answers? -
Radio button doesnt appear on my default DjangoModelform. I cant find the issue?
This is my model where I want my Gender field to appear as radio button. class Passenger(models.Model): # book_id = models.OneToOneField(Booking, # on_delete = models.CASCADE, primary_key = True) First_name = models.CharField(max_length=200, unique=True) Last_name = models.CharField(max_length=200, unique=True) Nationality = models.CharField(max_length=200, unique=True) Passport_No = models.CharField(max_length=200, unique=True) Passport_Exp_Date = models.DateField(blank=False) Contact_Number = models.CharField(max_length=200, unique=True) Email = models.EmailField(max_length=200, unique=True) Customer_id = models.CharField(max_length=50) Gender = models.CharField(max_length=50) This is my Passenger form. class PassengerForm(forms.ModelForm): Passport_Exp_Date = forms.DateField(widget=forms.widgets.DateInput(attrs={'type': 'date'})) CHOICES = [('M', 'Male'), ('F', 'Female'), ('O', 'Others')] Gender = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) class Meta: model= Passenger fields = '__all__' -
Image upload above 1 mb gives 500 server error django on app engine
I have been trying to upload images on my website but it shows 500 server error on uploading large files how can I solve this issue. Can anyone link a tutorial or solution to this issue? Thanks in advance -
The current path, <code>hooktest/</code>, didn't match any of these
I have an django project whith single app and I am trying to configure URL path but can't. My project structure is: -- 05 #parent directory -- env #virtualenv -- tools #django project located directory which was created by django-admin manage.py -- tools __init__ urls.py settings.py etc -- webhooks #here is my app __init__.py urls.py views. py etc In my tools/urls.py the following instructions from django.contrib import admin from django.urls import path, include from webhooks.views import hook_receiver_view urlpatterns = [ path('admin/', admin.site.urls), path('hooktest/',hook_receiver_view,name='hook'), ] My webhooks/views.py contain from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.http import require_http_methods @require_http_methods(["GET","POST"]) def hook_receiver_view(request): return HttpResponse('success') While I am trying to access url specified in tools/urls .py by curl http://example.com/hooktest/ It's return me the following error <p> Using the URLconf defined in <code>tools.urls</code>, Django tried these URL patterns, in this order: </p> <li> admin/ </li> <p> The current path, <code>hooktest/</code>, didn't match any of these. What I am doing wrong. Anyone guide me. Thanks in advance -
Django Template - Value Iteration
I am using following code to calculate total price for each item in shopping cart. How should I calculate grand total for whole cart - sum of each "total" from code below? I did read docs (Built-in template tags and filters) but didn't managed to figure it out. {% for key,value in request.session.cart.items %} Total {{ value.price|multiply:value.quantity }} {% endfor %} -
How to manage multiple device login with django rest framework?
So I have an app in which I previously managed login logout with access tokens. When login, an access token will be generated and it will be sent to FE. Access token will be stored in FE (Front end) and it will define if the user is logged in or not. When the user logs out, access token will be deleted from both FE and BE (Back-end database). In this scenario, logging in with the same account in multiple devices is not possible and also had other issues. Now I want to add multiple device login and some other features. So far I have thought of providing a maintaining a refresh token and access token in the database. The expiration of access token and refresh token will be around 5 minutes and 1 month respectively. When access token will expire during user is logged in, it will check if the refresh token is valid and if valid, new access token will be generated. Access token and refresh token both will remain after logging out to allow multiple device login. But I am not satisfied with this idea and I think there are some best practices and tools that I can … -
Use django models in an external .py file
I am trying to make a telegram bot that needs access to a database of a django app. I want to avoid making webservices in views.py to manage content because I don't want to make an API an just want to keep things separated by the moment, so I need to access to the django ORM in the telegram bot. I have imported the models in my bot main file but I get this message: File "C:\Python37-32\lib\site-packages\django\apps\registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Once I get this message, I add the app to settings adding this line to the INSTALLED_APPS variable: 'localadmin.apps.BotConfig' and the next lines in the apps.py file: class BotConfig(AppConfig): name = 'localadmin.bot' Having in mind that there's a folder called "bot" which have the main.py file that launches the bot. So, I think, everything was in order, but, with this changes, I get the next error message. File "C:\Python37-32\lib\site-packages\django\apps\registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. So I guess my problem, is that I need to use a proper django app to use the models, but I can't do this, due that …