Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Upload a file and populate field model with file name
I'm using Django and want to build an upload file page. When user upload a file, it stores it in a folder. I wan't to get the original file name to populate a field in my model (SourceFile.file). File is well uploaded, but I can't reach request.FILES properties, even with request.FILES.get('uploaded_to') or request.FILES['uploaded_to'] to fill in SourceFile.file with file name. How to achieve this ? My source is official documentation. models.py from django.db import models class SourceFile(models.Model): file = models.CharField() uploaded_to = models.FileField(upload_to ='/uploads/') serializers.py from rest_framework import serializers from .models import * class SourceFileSerializer(serializers.ModelSerializer): class Meta: model = SourceFile fields = ['file', 'uploaded_to'] views.py class SourceFileViewSet(viewsets.ModelViewSet): serializer_class = SourceFileSerializer def list(self, request): return Response("GET API") def upload_file(request): if request.method == "POST": form = SourceFile(request.POST, request.FILES) # Nothing happened file_uploaded = request.FILES.get('uploaded_to') file_name = file_uploaded.name request.POST['file'] = file_name # if form.is_valid(): form.save() return HttpResponseRedirect("/success/url/") else: form = SourceFile() return render(request, "upload.html", {"form": form}) -
How to access relation 'belongs to' from template?
I was wondering if there's a way to access the relation 'Belongs To' using Jinja in a Django project. What I mean is: I have this model representing Student: class Student(models.Model): name = models.CharField(max_length=200, verbose_name="Name:") ... and I have this model representing Enrollment, this class has a foreign key related to student: class Enrollment(models.Model): enroll_number = models.CharField(max_length=10, verbose_name='Number:') ... student= models.ForeignKey(Student, on_delete=models.CASCADE, related_name='enroll_student', verbose_name='Student:') ... If a pass sothing like enroll = Enrollment.objects.get(id=1) and pass to template {{"enroll": enroll}} I know that I can, using Jinja, access student with: {{enroll.student}} But, if I only the student (student = Student.objects.get(id=1)) and pass {{"student": student}} to template, how can access the enrollments with Jinja: something like: {{student.enroll}} (This doesn't work) Even If there's know way, what would be the best practice to resolve this in Django? Laravel, for instance allows us to define a function on the model that we can access in the template. Does anybody could help? -
Django: How to filter django objects based on month?
I am trying to get/count how many orders that were made in a month, i have written some logic to do this, but the issue is this: It does not count how many total orders were made in a month, it spreads different orders on the same month. To be more explicit, look at the reponse below: This is how to the queryset looks now <QuerySet [{'month': 4, 'count': 1}, {'month': 6, 'count': 1}, {'month': 6, 'count': 1}]> This is how to the expected queryset should look <QuerySet [{'month': 4, 'count': 1}, {'month': 6, 'count': 2}]> The 'month':4 is 'month':April and 'month':6 is 'month':June This is the code i have written to do this, but does not work models.py class CartOrder(models.Model): vendor = models.ManyToManyField(Vendor) ... date = models.DateTimeField(auto_now_add=False) views.py import calendar from django.db.models.functions import ExtractMonth orders = CartOrder.objects.annotate(month=ExtractMonth('date')).values('month').annotate(count=Count('id')).values('month','count') print(orders) terminal <QuerySet [{'month': 4, 'count': 1}, {'month': 6, 'count': 1}, {'month': 6, 'count': 1}]> -
How to more concisely make Google authorization on Django Rest Framework?
Began to study DRF. Now I have reached the topic "Google authorization". I started looking for materials on this topic, but there are a lot of them and some of them are already outdated. I'm looking for a more up-to-date description of how it's done now. It would be ideal to find a description with an example "for dummies", where everything is described in great detail. A little about the test project: for the user, a model based on AbstractUser is used now local registration and authorization is used using "Simple JWT" Request: djoser topics do not touch yet I read the topic "Authentication" on the official website of the DRF, I mainly considered "drf-social-oauth2", but I didn’t really understand -
Execute python on Django Queryset
Is there a way to execute python code on a Django Queryset? I am storing data in the db as bytes and I want to convert them to "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB". Is there any way I can convert the them before passing to the view? def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['user'] = ( DataVolume.objects.values('user') .order_by('user') .annotate( imgs=Sum('imgs'), size=SumConvertBytes('user_bytes'), ), ) -
Can I create multiple objects in django admin?
The questions is really simple. I have ItemPicture model which is class ItemPicture(models.Model): name = models.CharField(null=True, max_length=255) picture = models.ImageField(upload_to='shop/static/shop/images/') def __str__(self): return str(f"{self.name} id={self.pk}") def get_url(self): return self.picture.url How can I create, for example, 5 objects at once with django admin? I should be able to upload 5 photos and give them 5 names. django-bulk-admin and django-mass-edit didn't work for me -
sending value form views.py to html using jsonresponse
he=llo, i want to get a value from my view to html using jsonreponse, the problem is that my code work fine in views.py and i can print the data , but when i call the data in ajax it doesn't work it just give 0 as result ( because i declare round_surf = 0 at the beginning ) this the views.py code : def resultat (request): round_surf = 0 info = parametre.objects.filter(pk=1).values()[0] SEUIL = info['PAR_SEUIL'] COLOR = info['PAR_COLOR'] NBR_PAQ = info['PAR_NBRE_PAQUET'] SUR = info['PAR_SUR'] if request.method=="POST": if request.POST.get('captured_image'): captured_image = request.POST.get('captured_image') imgstr = re.search('base64,(.*)', captured_image).group(1) imgstr = base64.b64decode(imgstr) tempimg = io.BytesIO(imgstr) im = Image.open(tempimg) image = ImageOps.grayscale(im) # Appliquer un seuil pour convertir les pixels en valeurs binaires threshold = 100 # Choisir un seuil approprié image = image.point(lambda x: 0 if x < threshold else 1, '1') # Récupérer la longueur et la largeur de l'image width, height = image.size # Calculer le nombre total de pixels total_pixels = width * height image = image.convert('RGB') # Initialiser le compteur de pixels noirs black_pixels = 0 # Parcourir chaque pixel de l'image for x in range(width): for y in range(height): # test if the pixel is white if image.getpixel((x, … -
Custom functionality for editing popup text (like wikipedia link popups) in Summernote
I am trying to implement a feature into admin panel using Summernote to be able to add and edit popup information for parts of text like in Wikipedia. Wikipedia example I have found information on how to add custom buttons to summernote text editor, however implementation of functionality for described feature is too specific to be even referenced anywhere. I expect on a button press to appear a window (like for link insertion that is already implemented in Summernote) with fields for icon appearing in text and image/text appearing in popup. Populating those fields will add code to the editor, that is interpreted as an icon in text, hovering over which will show a popup window with before mentioned content. Maybe someone knows what documentation can help with implementation of such feature. -
ImportError: cannot import name 'displayadmin' from 'organizationsapp.models'
I'm new to python and django. admin.py in organizationsapp: from django.contrib import admin from .models import displa class displayadmin(admin.ModelAdmin): list_display = ['des','pic'] admin.site.register(displa,displayadmin) models.py in organizationsapp: from django.db import models class displa(models.Model): des = models.TextField(max_length=100,blank=True,null=True) pic = models.ImageField(upload_to='display/', blank=True) class Meta: verbose_name = 'ad' verbose_name_plural = 'ad' It says: ImportError: cannot import name 'displayadmin' from 'organizationsapp.models' import name 'displayadmin' from 'organizationsapp.models'? import name 'displayadmin' from 'organizationsapp.models'? -
How to pass link to file in Django views
I am very new to Django and trying display an image on an html page by passing the path to the src from the view. I have this in the 'task1.html' file <figure><img src={% static '{{ main_figure }}' %}></figure> <p>{{ description }}</p> and this in the 'views.py' file def task1(request): return render( request, "App/Tasks/task1.html", { 'main_figure' : "assets/placeholder_img.png", 'description' : "Placeholder image and text" } ) But the image does not show. If I remove the 'main_figure' : "assets/placeholder_img.png", line and change <figure><img src={% static '{{ main_figure }}' %}></figure> to <figure><img src={% static 'assets/placeholder_img.png' %}></figure> the image displays, so the issue seems to be with the views function. I have tried passing different parts of the src from the view, e.g. <img src={{ main_figure }}> with 'main_figure' : "{% static 'assets/placeholder_img.png' %}", and <img src={% static 'assets/{{ main_figure }}.png' %}> with 'main_figure' : "placeholder_img", but it always shows the little image not found icon. Any help would be greatly appreciated, thanks very much. -
How to modify or cancel the soft_time_limit for a running Celery task in Django?
Using Celery with Django, I encountered an issue while using the soft_time_limit on a task. Is there any way to stop or increase the soft_time_limit when a task is being executed? For example, after some lines of code are executed, can I increase the soft_time_limit for that particular task or cancel it altogether so that I can run the task without restrictions? I have tried modifying the soft_time_limit using update_state and signal, but it doesn't seem to work. I also tried using os.kill(os.getpid(), signal.SIGUSR1) to kill the current process, but it still raises the SoftTimeLimitExceeded exception. Any help or suggestions on how to achieve this would be greatly appreciated. Thank you. import signal from celery.exceptions import SoftTimeLimitExceeded @app.task(bind=True, soft_time_limit=10) app.task() def func(self) try: ..... ..... ..... some code app.current_task.request.timelimit = [None, None] or os.kill(os.getpid(), signal.SIGUSR1) .... some code except SoftTimeLimitExceeded: .... -
Django Modals To Admin Site
I want to Show Language of Book In Each BookInstance Table? How Do i do it. Please Guide me Everything Else is Working Fine. Here is the code :- Modals.py Modals.py Admin.py Admin.py Note :- i am new to django -
Django | Error in migration from sqlite3 to MySQL
I want to change my database from sqlite3 to mysql, but every time I do so, I encounter an error whenever I try to retrieve data from the database: Even when I try to log in to admin panel, I get the same error! (createsuperuser works fine): Here are my models: class Website(models.Model): name = models.CharField(max_length=500) URL = models.CharField(max_length=500) Logo = models.CharField(max_length=1000,null=True,blank=True) class Data(models.Model): website = models.ForeignKey(Website, on_delete=models.CASCADE , null=True, blank=True) Target_website= models.CharField(max_length=500,null=True,blank=True) URL = models.CharField(max_length=500,null=True,blank=True) Title = models.CharField(max_length=1000, unique=True) Description = models.TextField(null=True,blank=True) Keywords = models.TextField( null=True,blank=True) Text = models.TextField( null=True,blank=True) Links = models.TextField( null=True,blank=True) Images = models.TextField( null=True,blank=True) Videos = models.TextField( null=True,blank=True) Claps = models.IntegerField(default=0) TimeStamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.Title def change_claps(self, x): self.Claps += x self.save() class CustomUser(AbstractUser): username = None email = models.EmailField(unique=True) first_name = models.CharField(max_length=14) last_name = models.CharField(max_length=14) password = models.CharField(max_length=20) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) #auto_now = True if you want to add a field like "updated_on" favourite_posts = models.ManyToManyField(Data, blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Claps(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='user_likes') data = models.ForeignKey(Data, on_delete=models.CASCADE, related_name='post_likes') class Fav(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='user_favs') data = models.ForeignKey(Data, on_delete=models.CASCADE, related_name='post_favs') Here are my serializers: from rest_framework import … -
What is your way of setting up a new project with Django? Using Docker, Github?
i was just wondering what's your way of starting a new project with django? Do you develop the project and then setup docker or you do it all at the beginning? I know there is no right or wrong but only what's right for us. But i've been struggling finding my way to optimise creating an app using all those services such as docker or railway.app Thanks for your feedbacks -
How to recreate my table in database in Django
i created a table in sqlite3 database by migrate command and then deleted it manually from database how can i recreate the table in database I tryed maigrate command again but its show No migrations to apply. pls someone tell how do i recreate the table in automatic way(by commands) -
Additional arguments to get_queryset in view
I’m looking at code which has: get_queryset(self, *args, **kwargs): return (super().get_queryset(*args, **kargs).order_by(self.name)) What is the purpose of the args and kwargs here and why not do this instead: get_queryset(self): return MyModel.objects.order_by(self.name))``` -
Hi iam getting this error TemplateSyntaxError at / Could not parse the remainder: ''' from '''
TemplateSyntaxError at / Could not parse the remainder: ''' from ''' i tried removing any extra space inside the tags but still it didnt work -
drf-spectacular with custom permission on endpoint
I've got problem with drf-spectacular library. I prepared decorators for my viewset, but I can't see endpoints in this viewset on my schema. I figured out that my custom permission to these endpoints blocks it (When I set my permissions to AllowAny the schema works fine). One permission checks if headers include header-x, the second one asks db about something (simple Queryset). Is there an option to allow swagger to disable these permissions? Or I must to refactor my code to delete them? I tried to modify DRF-spectacular settings, but I couldn't find the proper way to solve it. But when I change SERVE PUBLIC to True I see everything, even though I'm not authorized. I want to show mentioned endpoint only when I'm authorized. "TITLE": "My API", "DESCRIPTION": "My description", "SERVE_INCLUDE_SCHEMA": False, 'SERVE_PUBLIC': False, -
Django inherited template javascript is not working
I have a base template called 'baseUI.html'. I have loaded my static files using {% load static%} .when i inherited to another template the javascript and css seems broken. The console shows Refused to execute script from 'http://127.0.0.1:8000/Ticket/static/dashboard/script.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. but the first rendering is working perfectly but when i rout it to another the directory changes instead calling /dashboard/style.css path('Ticket/<str:id>',RaiseTickets,name='raiseticket'), the django server console shows "GET /User_Management/vyshnav/static/dashboard/ajax.js HTTP/1.1" 404 3118 why the route path is including the code has given below <!DOCTYPE html> <html lang="en"> <head> {% load static %} {%block content%} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Boxicons --> <link href='https://unpkg.com/boxicons@2.0.9/css/boxicons.min.css' rel='stylesheet'> <!-- My CSS --> <link rel="stylesheet" type="text/css" href="{% static 'dashboard/style.css' %}"> <script src="{% static 'dashboard/script.js' %}"></script> <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script> <title>Admin Dashboard</title> </head> <body> <!-- SIDEBAR --> <section id="sidebar"> <a href="#" class="brand"> <i class='bx bxs-institution'></i> <span class="text">{{LoggedUser.First_Name}} {{ LoggedUser.Last_Name}}</span> </a> <ul class="side-menu top"> <li class="active"> <a href="{% url 'home' id=LoggedUser.User_Id %}"> <i class='bx bxs-home'></i> <span class="text">Dashboard</span> </a> </li> <li> <a href="{% url 'User_Management' id=LoggedUser.User_Id %}"> <i class='bx bxs-user'></i> <span class="text">User Management</span> </a> </li> <li> <a href="{% url 'raiseticket' id=LoggedUser.User_Id %}"> <i class='bx … -
Daphne not picking up Websocket Requests in Django Rest Framework
I want to enable secure websocket connection to my Django Rest Framework application. I see that all services are starting correctly, but still when I try to connect via the following URL, the connection does not get established. It just fails with no trace. wss://127.0.0.1:8000/ws/notifications/ Where as it works fine over ws ws://127.0.0.1:8080/ws/notifications/ docker-compose.yml services: api: platform: linux/amd64 build: context: . dockerfile: Dockerfile.dev command: 'sh -c "./manage.py migrate && python manage.py runserver 0.0.0.0:8080"' restart: always networks: - default - fake_microservices volumes: - ./:/app - $HOME/.aws:/root/.aws:ro - /var/run/docker.sock:/var/run/docker.sock - type: bind source: ./docker/cpuinfo_with_fake_speed.txt target: /proc/cpuinfo ports: - 8080:8080 env_file: - ./.env depends_on: - db daphne: platform: linux/amd64 build: context: . dockerfile: Dockerfile.dev command: 'sh -c "daphne -v 3 --access-log daphne.log -b 0.0.0.0 -p 8000 apps.asgi:application"' restart: always working_dir: /app volumes: - ./:/app - /var/run/docker.sock:/var/run/docker.sock asgi.py os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.local") django_asgi_app = get_asgi_application() from channels.routing import ProtocolTypeRouter, URLRouter application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": URLRouter([path('ws/notifications/', NotificationConsumer.as_asgi())]), } ) I can see that Daphne starts with no problems: daphne_1 | 2023-04-06 09:05:27,576 INFO Starting server at tcp:port=8000:interface=0.0.0.0 daphne_1 | 2023-04-06 09:05:27,578 INFO HTTP/2 support enabled daphne_1 | 2023-04-06 09:05:27,578 INFO Configuring endpoint tcp:port=8000:interface=0.0.0.0 daphne_1 | 2023-04-06 09:05:27,580 INFO HTTPFactory starting on 8000 daphne_1 | … -
Django smart select not work if i add CSS style
I have a little problem with django's function: "django-smart-select". Basically django-smart-select works until I add a CSS class to a form-field. Here is my example: in models.py: from django.db import models from smart_selects.db_fields import ChainedForeignKey # Create your models here. class Company(models.Model): ID = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=100) def __str__(self): return self.name class Subcompany(models.Model): ID = models.AutoField(primary_key=True) name = models.CharField(max_length=100) ID_company = models.ForeignKey(Company, on_delete=models.CASCADE) def __str__(self): return self.name class Interventions(models.Model): ID = models.AutoField(primary_key=True) start_date = models.DateField() end_date = models.DateField(blank=True, null=True) hours = models.DecimalField(max_digits=24, decimal_places=1, blank=True, null=True) description = models.TextField() signature = models.CharField(max_length=100, blank=True) ID_company = models.ForeignKey(Company, on_delete=models.CASCADE) ID_subcompany = ChainedForeignKey( Subcompany, chained_field="ID_company", chained_model_field="ID_company", show_all=False, auto_choose=True, sort=True) def __str__(self): return f'{self.start_date}' so in forms.py: from django import forms from django.forms import DateInput, TimeInput, NumberInput, TextInput, Textarea, Select from app1.models import Interventions # Create your forms here. class Forminterventions(forms.ModelForm): class Meta: model = Interventions exclude = ['ID'] fields = ['start_date', 'end_date', 'hours', 'description', 'signature', 'ID_company', 'ID_subcompany'] widgets = { 'start_date': DateInput(attrs={'class': 'inputDate'}), 'end_date': DateInput(attrs={'class': 'inputDate'}), 'hours': NumberInput(attrs={'class': 'inputNumber'}), 'description': Textarea(attrs={'class': 'inputText'}), 'signature': TextInput(attrs={'class': 'inputText'}), 'ID_company': Select(attrs={'class': 'inputCombo'}), 'ID_subcompany': Select(attrs={'class': 'inputCombo'}), } in style.css: .inputDate .inputNumber .inputText .inputCombo{ color: black; font-family: 'EB Garamond', sans-serif; font-size: x-large; text-align: center; width: 100%; } What … -
Django formtools wizard adding extra data with get_context_data
I have different templates for each form, and I get a correct succession of them when I just do this # Create your views here. ``FORMS = [("first", FirstForm), ("address", AddressForm), ]` `TEMPLATES = {"first":"dashboard/profile.html", "address": "dashboard/address.html", }`` `class FormulariosView(SessionWizardView): def get_template_names(self): return [TEMPLATES[sel f.steps.current]] form_list = [FORMS] ` and in the urls.py ` urlpatterns = [ path('dashboard/profile/', views.FormulariosView.as_view(FORMS), name='profile'), ]` but in one of the forms I need to get extra data from a database table so I try to add it like this (underneath the TEMPLATES snippet) ` def get_context_data(self, form, **kwargs): context = super(FormulariosView, self).get_context_data(form=form, **kwargs) context["whatever"] = Paises.objects.all() if self.steps.current == 'address': return context` but if I add that last code snippet, the whole thing crashes and I get no forms display whatsoever. the documentation is unclear and insufficient for this purpose and don't know how to continue. -
Django test database isn't deleted after test completion
Background Django-pgpubsub listens for PostgresSQL triggers by running python manage.py listen. This command continuously runs and serves as a lightweight alternative to Django signals and celery for sending emails when a Shipment model instance's status field changes to certain values. Problem The integration test calls the python manage.py listen command in a separate process using subprocess. The test passes but the test database remains and I have to manually delete it after to prevent the next test from failing due to a duplicate database. Whatever teardown functionality that comes with django-pytest is being called since this outputs upon test completion: Destroying test database for alias 'default' ('test_my_project_database') The Test @pytest.mark.django_db(transaction=True) # needed to work def test_shipment_status_notifications_with_listen_command_subprocess(testuser): user = testuser # model instances setup for the test notification_settings = NotificationSettings.objects.get(user=user) notification_settings.failed_attempt = True notification_settings.save() cust_email = "test@test.com" customer = Customer.objects.create(email=cust_email) order = Order.objects.create(customer=customer) shipment = Shipment.objects.create(user=user, order=order) listen_command = [ "python", str(settings.ROOT_DIR / "manage.py"), "listen", ] env = os.environ.copy() # we need to update these env vars to use the actual test database instead of the live one # the process uses the live database by default env.update( { "DATABASE_URL": f"postgresql://{config('POSTGRES_USER')}:{config('POSTGRES_PASSWORD')}@127.0.0.1:5432/test_{config('POSTGRES_DB')}", } ) listen_process = subprocess.Popen( listen_command, env=env, ) time.sleep(2) # … -
from ticket.ticketapp import views ModuleNotFoundError: No module named 'ticket.ticketapp'
Just started working with Django. I created an app, mapped it on INSTALLED_APPS list and wrote a simple function in views.py. but getuser() method in the views.py not able to import in the urls.py `models.py class user(models.Model): username = models.CharField(max_length=255) password = models.CharField(max_length=255) email = models.EmailField() `**views.py** `from django.shortcuts import render from models import user from django.http import JsonResponse def getuser(request): data = user.objects.all() return JsonResponse(data,safe=False)`` urls.py `from django.contrib import admin from django.urls import path from ticket.ticketapp import views urlpatterns = [ path('admin/', admin.site.urls), path('airline/', views.getuser()) ]` [enter image description here](https://i.stack.imgur.com/QAIe3.png) from ticket.ticketapp import views ModuleNotFoundError: No module named 'ticket.ticketapp'` -
How can I connect backblaze b2 bucket to a django project to store media and static files?
I want to shift from AWS to Backblaze, I tried to follow the documentation on django storages to simply modify a little my already exisiting aws configuration but I just kept having errors. My current aws configuration is like this: AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = None AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} DEFAULT_FILE_STORAGE = 'myproject.storages.MediaStorage' AWS_QUERYSTRING_AUTH = False STATIC_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATIC_LOCATION}/' STATICFILES_STORAGE = 'myproject.storages.StaticStorage' MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'myproject.storages.MediaStorage'