Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error importing serializers from rest_framework in Django project
I am facing an issue while trying to import serializers from the rest_framework module in my Django project. When I use the following line of code: from rest_framework import serializers I receive the following error message: ImportError: cannot import name 'serializers' from 'rest_framework' I have ensured that Django REST Framework is installed correctly, but I am still encountering this problem. Can someone help me figure out what might be causing this issue? Any suggestions for troubleshooting this error would be appreciated! I have already tried selecting the correct interpreter, and I have verified that both pip and django are installed. I also confirmed that Python is set up correctly, but I am still encountering this issue. I have also added it in the settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'rest_framework', ] -
The view stock.views.eliminar_tipomaterial didn't return an HttpResponse object. It returned None instead
I am doing a CRUD with Django 5.1 I want to delete the data when I press on the delete button it stays in the same but it shows this error: views.py def eliminar_tipomaterial(request, tipomaterial_id): tipomaterial = get_object_or_404(TipoMaterial, pk=tipomaterial_id) if request.method == 'POST': tipomaterial.delete() return redirect('tipomaterial.html') Tipomaterial.html <main class="container"> <div class="table-responsive"> <table class="table table-bordered"> <thead> <tr style="text-align: center;"> <th scope="col">Nombre del material</th> <th scope="col" colspan="2">Acciones</th> </tr> </thead> <tbody class="table-group-divider"> {% for datos in tipomaterial %} <tr> <td> <li class="list-group-item" href="{% url 'detalle_tipomaterial' datos.id %}"> <strong>{{datos.nombre}}</strong> </li> </td> <td> <a class="btn btn-primary" href="{% url 'detalle_tipomaterial' datos.id %}" role="button"> <i class="bi bi-pencil-fill"> Editar </i> </a> <a class="btn btn-danger" href="{% url 'eliminar_tipomaterial' datos.id %}" role="button"> <i class="bi bi-trash3-fill"> Eliminar </i> </a> </td> </tr> {% endfor%} </tbody> </table> </div> </main> enter image description here -
Can you make sortable.js work with boostrap 5 modal?
I'm building a checklist app for fun and I'm trying to use sortable.js with python django. I can make a sortable list work in this example with the html as follows {% extends 'BJJApp/base.html' %} {% load static %} {%load crispy_forms_tags %} {% block content %} <br><br> <div id="standalone-items-container"> {% for item, formset, links in standalone_items_formsets_links %} <div class="modal fade" id="exampleModalToggle-{{ item.id }}" aria-hidden="true" aria-labelledby="exampleModalToggleLabel-{{ item.id }}" data-item-id="{{ item.id }}" tabindex="-1"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalToggleLabel-{{ item.id }}" style="color: {% if item.important %}red{% else %}inherit{% endif %};">{{ item.title }}</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form method="POST" id="main-form-{{ item.id }}" action="{% url 'viewitem' item.id %}"> {% csrf_token %} <div class="form-group"> <label for="title">Title</label> <input type="text" name="title" class="form-control" id="title-{{ item.id }}" value="{{ item.title }}" required disabled> </div> <div class="form-group"> <label for="memo">Memo</label> <textarea name="memo" rows="5" class="form-control" id="memo-{{ item.id }}" disabled>{{ item.memo }}</textarea> </div> <div class="form-group form-check"> <input type="checkbox" name="important" class="form-check-input" id="important-{{ item.id }}" {% if item.important %}checked{% endif %} disabled> <label class="form-check-label" for="important">Important</label> </div> </form> </div> <div id="links-{{ item.id }}"> {% if links %} <ul> {% for link in links %} <li><a href="{{ link.url }}" target="_blank">{{ link.url|urlizetrunc:50 }}</a></li> {% endfor %} </ul> {% else %} … -
Expensive django calculation needs to run on model change
I am working on a django application that has a model with a field that needs to be calculated when the model changes. The calculation itself is relatively expensive (1+ seconds) especially if/when this field is recalculated for a large queryset. It is important that this field is recalculated immediately following the model change because it determines the workflow which the user needs to follow and the field value is propagated to the UI for the user to see. At a minimum the calculation needs to be guaranteed to run after update or some way to indicate the calculation is stale. The current implementation which was not an issue because the calculation was previously less complicated/expensive (before requested changes by the client) is as follows: user makes edit in UI and model is updated API receives changes and applies changes to model model .save() is overridden so the field is calculated and set With this implementation we also disabled the queryset manager on the model to prevent the use of .update() to ensure that field is always recalculated on .save(). I am curious on how others would implement something like this to be as efficient as possible and not relying … -
How to implement thumbnail images into Wagtail’s ModelViewSet?
Is it still possible to implement a thumbnail image in a ModelViewSet listing view? Here is an example for a NewsPost model. class NewsPostViewSet(ModelViewSet): model = NewsPost list_display = ["title", "category", "date_start", "date_end", "live"] add_to_admin_menu = True icon = "calendar-alt" menu_label = "News" The PageListingViewSet has columns with all kinds of columns for different model types. But also no "ImageColumn" to display a thumbnail image. I miss the ThumbnailMixin that the Wagtail ModelAdmin app provided, which is now deprecated. Does anybody know a workaround? -
Django image not showing on webpage
I am following the w3schools tutorial w3schoools-img and trying to display a img on my Django webpage but I am getting a small green icon instead: this is my template: {% extends "book/base.html" %} {% block content %} <h1>Books</h1> <h2>Genre: {{ genre }}</h2> <p>Books: </p> {% load static %} <img src="{% static '71wdAPcG-PL._SY466_.jpg' %}"> {% for i in titles %} <li> {{ i.text }} </li> {%empty%} {%endfor%} {% endblock content %} Is there something I am doing wrong? I have created a static folder with the image in my template folder. Much appreciation! -
django_filters.Filterset with context data from FilterView
I've a LearnerInstance model: class LearnerInstance(models.Model): learner = models.ForeignKey(Learner, on_delete=models.CASCADE) aim = models.ForeignKey(Aim, on_delete=models.CASCADE) ... class Meta: unique_together = ("learner", "aim") def __int__(self): return self.learner def name(self): return f"{self.learner.firstname} {self.learner.surname}" views.py class GroupDetailView(FilterView): model = LearnerInstance template_name = "group_detail.html" table = LearnerGroupTable filterset_class = LearnerInstanceFilter def get_context_data(self, **kwargs): context = super(GroupDetailView, self).get_context_data(**kwargs) queryset = LearnerInstance.objects.filter( learner__group__short_name=self.kwargs["pk"]) f = LearnerInstanceFilter( self.request.GET, queryset=queryset.filter(aim=self.request.GET.get("aim"))) context["table"] = LearnerGroupTable(f.queryset) context["group"] = Group.objects.filter(short_name=self.kwargs["pk"]).values() return super().get_context_data(**context) filters.py class LearnerInstanceFilter(django_filters.FilterSet): class Meta: model = LearnerInstance fields = ["aim"] Question: How do I change the filter to show only the distinct aim options returned by the queryset (all learner instances related to a selected group) within the get_context_data? The database contains all possible aims which are offered through the filter (I know this is due to the filter being linked to the model and aim field), I want to be presented with only a list of aims that are unique to the learners within the current context. -
I need a simple Django queued-email package which DOESN'T use "Pinax"
I have a very simple requirement: I need to queue emails into a database, then send them out via a periodically-scheduled "manage.py" subcommand. I previously used a Pinax-based package to do this, but "Pinax is enormous," and appears to be outdated. I only need this very-specific ONE thing, and not any of the rest. So – while I troll through "djangopackages.com," can anyone quickly suggest something that will come anywhere close to my simple needs? Trying to save [my ...] time here. I know that my requirement is simple and common, and I really don't want to have to build what I need from scratch. I don't like having to "re-do" what I know has already been well-done. -
Django Stripe Checkout Integration: 404 Error on `create-checkout-session` URL
I am working on integrating Stripe Checkout into my Django application, but I'm encountering a 404 error when trying to create a checkout session. I have created the view and URL for handling Stripe's checkout session, but I am getting a 404 error when trying to POST to the endpoint. The error message I get in the browser console is: stripe.js:13 POST http://127.0.0.1:8000/create-checkout-session/71/ 404 (Not Found) stripe.js:33 Error: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON Steps I've Taken: I've defined the URL in urls.py as: # core/urls.py from django.urls import path from . import views urlpatterns = [ path('create-checkout-session/<int:pid>/', views.create_checkout_session, name='create_checkout_session'), ] My create_checkout_session view in views.py is as follows: import stripe from django.http import JsonResponse from django.conf import settings from django.shortcuts import get_object_or_404 from core.models import Product @csrf_exempt def create_checkout_session(request, pid): stripe.api_key = settings.STRIPE_SECRET_KEY product = get_object_or_404(Product, pid=pid) try: checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[{ 'price_data': { 'currency': 'usd', 'product_data': { 'name': product.name, 'description': product.description, }, 'unit_amount': int(product.price * 100), # Convert dollars to cents }, 'quantity': 1, }], mode='payment', success_url=request.build_absolute_uri('/success/') + '?session_id={CHECKOUT_SESSION_ID}', cancel_url=request.build_absolute_uri('/cancel/'), ) return JsonResponse({'id': checkout_session.id}) except Exception as e: return JsonResponse({'error': str(e)}) I've added the following button to my HTML template: <button class="btn btn--e-brand-b-2" … -
How to denormalize hierarchical Django model data for rendering CSV or Excel with Djange REST Framework?
Assume, we are building an address book application with Django REST Framework and want to render an endpoint that exports all persons. Each person can have one or multiple phone numbers. Exemplary data could look like this: [ { 'name': 'Jon Doe', 'phone': [ { 'type': 'home', 'number': '+1 234 5678' } ] }, { 'name': 'Jane Doe', 'phone': [ { 'type': 'home', 'number': '+2 345 6789' }, { 'type': 'work', 'number': '+3 456 7890' } ] } ] As we want to export CSV or Excel tables, we want to denormalize the data so that each phone number gets its own line. A result could look like this: name,phone.type,phone.number Jon Doe,home,+1 234 5678 Jane Doe,home,+2 345 6789 Jane Doe,work,+3 456 7890 The question is, where exactly I would do the denormalization. I see two options: Write a custom Serializer that does the denormalization. On the upside, this would result in a single change that works for every Renderer, so I could have the endpoint export CSV and Excel using, e.g. djangorestframework-csv and drf-renderer-xlsx. On the downside, this would interfere with renderers that do not benefit from denormalization like JSON or XML. Derive each Renderer that needs denormalization and override … -
Postgresql + Django Development Server Won't Open in Browser (connection refused)
My attempt to create/integrate Postgresql database and run Django development server continues to fail and I've followed every step in this tutorial (search page for 'Setting Up PostgreSQL with Django'): (website 1) https://www.hostinger.com/tutorials/django-tutorial When I run the development server and type in the browser http://127.0.0.1:8000 to connect, I get a page cannot be reached. ERR_CONNECTION_REFUSED Thinking it is a firewall issue I then followed the instructions on this page to open both (8000 port & 5432 port to any ip address (I copied example 1 on the page) --> 5432 is the default PostgreSQL port so I included that as well with 8000 just incase, and it still does not work: (website 2) https://linuxconfig.org/how-to-open-allow-incoming-firewall-port-on-ubuntu-22-04-jammy-jellyfish I double checked and know that I entered in my settings.py file the correct Database engine, name, user, password, host, and port because I followed the steps in (website 1). And I tried opening both the 5432 and 8000 port to any ip address incase the page was not opening because of a firewall issue from the example 1 in (website 2). I don't know what else to do. Please help, I am so frustrated! -
Handling data for both JSON and FormData in Angular
So im kinda new to angular and django, but im trying to create a web app kinda similar to Amazon, where the user is able to log in and browse different listings from other user, create his own listings and do basic CRUD operations on his own listings. When creating a listing the user needs to add a title, description, price, location choose a category and subcategory, add values to the attributes, and he can attach images as files. In the database both categories and subcategories have their own "attributes" whose values also need to be inputed by the user. For an example a category is lets say "Pet", that will have a attribute lets say "Age", and for a subcategory "Dog" there will be an attribute "Breed". I found a tutorial online for adding images, and basically im sending them as files, and saving them in a folder on backend. When I try to add a listing, everything works fine except that the attributes are never added to the database. I added some console logs on front to see if im getting them and sending as json and I do, so I think that the problem is on backend … -
Looking for suggestion for "simplest possible" Django email-notification system
In my original website, I brought in "all of Pinax" just to do one(!) thing: to let me queue-up email message requests that would then be sent out, every fifteen minutes, by an externally executed "manage.py" command (every fifteen minutes). I have now realized the error of my ways. And so, kindly suggest to me the SIMPLEST current-Django package which would most easily do this one thing: it lets me queue an email-only message, and it implements a "manage.py" subcommand to send them. Who has already done: "this, just this?" (Trivial request, I know. But by now, I know it's far better to "ask the community" first ...) -
string_if_invalid django or ninja template: custom renderer in selected html string
i'm looking for a solution to selectively not replace missing variables/replace by whatever in django: I have a text, defined by a user, where he can insert variables {{model.myvar}}. In the backend, i render the text and the context to return a text which can be then modified if necessary. So far so good... For UX reasons, the variables can be entered at different times, and the text be generated at any time...So if all the var are not entered, there will be empty strings... What i'm looking for is a way to get the free text with variables, and "generate" it as often as wanted ! So the text is sent to the backend, if the corresponding var is in the context => var is replaced ! but if there is not: return {{myvar}}. Then the txt can be re-generated later with appropriate information ! I deeply searched for a solution with django template and jinja. Indeed i explored "string_if_invalid" for django: but apply in all the app and can create problems. I'm looking for a custom solution which i can apply selectively in selected parts of my codes... -Is it possible ? -How...?! Thanks for your help ! -
Create Post and Upload Multiple Files in Django
I have a table of animals. For each animal I have multiple images. I would like the user to be able to register a new animal and add multiple images to it in one form. As of now no records are created and I do not understand why. I've been struggelig this for hours. I know I could get there by using formsets but would prefer something like this. I suspect the view is causing this, but do not understand why. This is my not-working sollution: upl/models.py from django.db import models from django.core.exceptions import ValidationError def validate_img_extension(value): if not value.name.endswith(".jpg", ".jpeg", ".png"): raise ValidationError("Only .jpg, .jpeg og .png allowed.") class Animal(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) class AnimalImage(models.Model): animal = models.ForeignKey(Animal, on_delete=models.CASCADE) image = models.FileField(upload_to="products/", validators=[validate_img_extension]) upl/views.py from django.shortcuts import redirect, render from .forms import AnimalImageForm, AnimalForm from .models import Animal, AnimalImage def createAnimal(request): animalform = AnimalForm() imageform = AnimalImageForm() if request.method == "POST": animalform = AnimalForm(request.POST) imageform = AnimalImageForm(request.POST or None, request.FILES or None) images = request.FILES.getlist("image") if animalform.is_valid() and imageform.is_valid(): title = animalform.cleaned_data["title"] describ = animalform.cleaned_data["description"] animal_instance = Animal.objects.create(title=title, description=describ) animal_instance.save() for i in images: AnimalImage.objects.create(animal=animal_instance, image=i) return redirect("uplhome") context = {"animalform": animalform, "imageform": imageform} return … -
django allauth - ACCOUNT_UNIQUE_EMAIL doesn't prevent duplicate emails on signup
I'm making a basic website where users sign up with an email, a username, and a psssword. I'm using dj_rest_auth, which wraps allauth to provide a REST API interface. Here's an example registration call: POST: http://127.0.0.1:8000/api/auth/registration/ Body: { "username": "new_user3", "password1": "testtest@123", "password2": "testtest@123", "email": "h@h.com" } These are the flags I've set in settings.py: ACCOUNT_EMAIL_VERIFICATION = 'none' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True Yet, when I send the registration request twice, and only change the username (not email), it goes through just fine: What's the easiest way to have this fail if the email is a duplicate? Ideally I'm looking for something the library itself provides, and not a custom class. -
Receiving Empty request.data When Invoking a Python Service Using Dapr: Bad Request Syntax (400)
I am encountering an issue while invoking a Python service using Dapr. The invocation consistently results in the following error: code 400, message Bad request syntax ('4') After investigating, I found that the error might be related to incomplete or missing order information. However, despite implementing the sample code provided in the Dapr documentation and making several adjustments, the issue persists. Observed Issue When invoking the service, request.data on the receiving end is always empty. As a temporary workaround, I routed the request through a gateway, which worked. However, this is not a sustainable solution for the long term. Environment Details Dapr SDK version: 1.12.1 (Python) Dapr runtime version: 1.12.5 Deployment platform: Azure containers Invocation method: Service-to-service using Dapr HTTP API Attempts to Solve Verified headers and content type (application/json) in the request. Tried different payload formats (stringified JSON and Python dictionaries). Referenced the official Dapr documentation and sample code. Question What could be causing request.data to be empty on the receiving side? Is there a specific configuration or step I might be missing for service-to-service invocation using Dapr in this environment? Additional Information I tried many solutions: Changing the code. Using direct information instead of the Dapr library. Modifying … -
Django crashes when I load a template with a 300,000+ character URI in it
I've put a data:image URI into my django template file (Jinja 2), and when I try to load the page that has this template, django crashes with no error messages. The URI is more than 300,000 characters long. How can I put this image in the page without the site crashing? -
Django keeps telling me that my superuser email violates unique constraint
I'm building a Django/DRF backend and keep getting this error when I try to create a superuser in cli: psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint `"users_useraccount_email_key"` This is strange because I know that I'm using unique emails EVERY time I create a superuser. After inspecting the error message further, I noticed that it said the above exception was a direct cause of the following exception: ... lots of venv related files and then in my /users/managers.py, line 61 Which is just: user.save(using=self._db) At the bottom of the error is: django.db.utils.IntegrityError: duplicate key value violates unique constraint "users_useraccount_email_key" DETAIL: Key (email)=(email@email.com) already exists. I'm using Postgres and using Postgres to generate the UUID, NOT python. class MyRandomUUID(Func): class RandomUUID(Func): template = 'GEN_RANDOM_UUID()' # template = 'UUID_GENERATE_V4()' output_field = 'UUIDField()' I am on Ubuntu and my virtual env is using Python v3.8, Django v4.17 and DRF v3.15. I know these versions are aging but its what the commands installed w/o giving specific versions. And I can no longer login to /admin either. It gives me this error(EVERY TIME): Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive. BEFORE this, I was able … -
Django cannot connect to database in container
I have created docker-compose file version: "3" services: web: build: . command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 depends_on: - postgresql volumes: - .:/app postgresql: image: postgres:latest environment: POSTGRES_DB: pgdb POSTGRES_USER: postgres POSTGRES_PASSWORD: admin ports: - "5432:5432" and when I run compose up, my db runs successfully, but eventually container with django cannot connect to my postgresql setting of project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', # 'NAME': 'diary', # 'USER': 'postgres', # 'PASSWORD': 'admin', # 'HOST': 'localhost', # 'PORT': '5432' 'NAME': os.getenv("DB_NAME"), 'USER': os.getenv("DB_USER"), 'PASSWORD': os.getenv("DB_PASSWORD"), 'HOST': os.getenv("DB_HOST"), 'PORT': os.getenv("DB_PORT") } } dockers logs : 2025-01-13 21:35:18 web-1 | django.db.utils.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory 2025-01-13 21:35:18 web-1 | Is the server running locally and accepting connections on that socket? what can cause such error? Even tho in previous work with same properties all worked correctly -
Django Website throws error after spamming refresh
I have a Django 1.8.4 app that uses python 3.6.9. The problem occurs when i refresh the page like ~10-20 times. I get the following error: One refresh after the error and the website works again. It seems like the cache returns an error message instead of a file. The caching settings are as follows: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'OPTIONS': { 'MAX_ENTRIES': 10000, 'TIMEOUT': 604800, } } I checked memcached logs and I got these messages: Jan 13 16:38:21 ******* systemd[1]: Stopping memcached daemon... Jan 13 16:38:21 ******* systemd[1]: Stopped memcached daemon. Jan 13 16:38:21 ******* systemd[1]: Started memcached daemon. Which doesn't help much. I tried increasing the allocated memory, but the error occured when used up memory was ~160MB / 512MB so it seems like that's not the issue. Setting "Limit the number of simultaneous incoming connections" to 1024 also doesn't help. Does someone have an idead what might be happening? -
Django custom `get_or_create` on model with M2M through model
As title says I'm trying to implement get_or_create method which able to get or create instance with respect to through model. Models: class Component(models.Model): name = CharField() class ConfigComponent(models.Model): config = models.ForeignKey(Config) component = models.ForeignKey(Component) quantity = models.PositiveIntegerField() class Config(models.Model): components = models.ManyToManyField(Component, through="ConfigComponent") So basically I want to check if Config matching input data exists and use it if so. Otherwise - create a new one. But how to consider the quantity of each Component? It is not a big deal to find Config with exact num of components but it may appears that components match but their quantity is different. -
How to create list of object from 2 models with sorting in Django?
I have this model in Django: Class SmallNews(models.Model): date_news = modeles.DateField ... Class BigNews(models.Model): date_news = modeles.DateField ... I want to create list of object(SmallNews + BigNews) and sorting all this objects by DateField. What the best way to do this? -
REACT AND DJANGO
I am running django on port 8000 and react on port 3000 i want to run both on a single port and how should i do it when i deployed project i used all the methods and suggest me something different for this question in detailed format -
Django PIL image not resizing
I am trying to resize the profile picture for my profile model. And I am not seeing what I am doing wrong. Below is the code: def save(self, *args, **kwargs): super().save() img = Image.open(self.profile_picture.path) img.show() img_resized = img.resize((100, 100), Image.Resampling.LANCZOS) img_resized.save() I would like the code to be resized at the dimensions mentioned in the code. I am receiving no errors in the terminal during runserver.