Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding a new field to a existing model in django
I created a model in django. Migrated, then forgot I'd missed a field. I've added that field in (author) and now I am getting an error. I've tried make migrations again but I get this... gitpod /workspace/bookends (main) $ python3 manage.py makemigrations books You are trying to add a non-nullable field 'author' to books without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py Select an option: When I run the server in admin then click on books I get this error message. enter image description here This is my model code enter image description here This is my admin.py code enter image description here -
How to override default error messages in a django.forms subclass? - django 4.2.3
I am in a spanish language country, so I need to show messages in spanish, can't use defaults error messages. I am making tests, so I create a django.forms subclass with 1 char field, set it to required, set a min and max length. Used the error_messages parameter to set errors in spanish but still showing default messages. I don't know what am I doing wrong. Data is saved correctly the only problem is the error messages. forms.py from django import forms class CreateNewList(forms.Form): nombre = forms.CharField(label="Nombre", max_length=200, min_length=3, required=True, error_messages = { 'required': "El campo nombre es requerido", 'min_length': "El campo nombre debe ser minimo de 3 caracteres", 'max_length': "El campo nombre debe ser menor a 200 caracteres" }) views.py def crear(response): form = CreateNewList(response.POST or None) if response.method == "POST": if form.is_valid(): n = form.cleaned_data["nombre"] t = ToDoList(nombre=n) t.save() return render(response,"main/crear.html", {"form": form}) With and empty input (https://i.stack.imgur.com/DIIsm.png) Any help will be very appreciated. -
Is there a way to paginate Django's admin page that uses the django-nested-admin lib?
I have an admin page using NedstedStackedInLine, and the problem is that in the inside model, i have to many occurrences of the secondary model. Is there a way to paginate the inside models to not cause 502 error when the users tryng to access the page in a production scenario. Running localy the page is loaded, but with many seconds because of the large amount of occurences? Here is the code to ilustrate the problem. class CityInlineAdmin(NestedStackedInline): model = City class NestedStateAdmin(NestedStackedInline): model = State inlines = (CityInlineAdmin,) class CountryAdmin(NestedModelAdmin): inlines = (NestedStateAdmin,) I have already tried the django-admin-inline-paginator, but appears that this lib does not suport the Nested case. -
Why do I get response of an API request handled by an (exited) gunicorn worker?
Gunicorn config (only for testing): workers = 1 max_requests = 2 timeout = 30 graceful timeout = 1 (all other unspecified/default) Log events: FIRST REQUEST: [2023-07-25 16:01:29 +0000] [9485] [DEBUG] [pre_request] POST <API> - worker pid **9485**|ppid 29517|age 3|nr 0|max_requests 2|alive True|nr_pre 1|nr_post 0|sub_p_count 0 RESPONSE OF FIRST REQUEST: [2023-07-25 16:01:44 +0000] [9485] [DEBUG] [post_request] POST <API> - worker pid **9485**|ppid 29517|age 3|nr 1|max_requests 2|alive True|nr_pre 1|nr_post 1|sub_p_count 0 SECOND REQUEST: [2023-07-25 16:01:51 +0000] [9485] [DEBUG] [pre_request] POST <API> - worker pid **9485**|ppid 29517|age 3|nr 1|max_requests 2|alive True|nr_pre 2|nr_post 1|sub_p_count 0 WORKER EXIT: [2023-07-25 16:01:51 +0000] [9485] [INFO] Autorestarting worker after current request. (graceful timeout of 1s) [2023-07-25 16:01:53 +0000] [9485] [INFO] Worker exiting (pid: **9485**) [2023-07-25 16:01:53 +0000] [9485] [DEBUG] Worker exited RESPONSE OF SECOND REQUEST: [2023-07-25 16:02:04 +0000] [9485] [DEBUG] [post_request] POST <API> - worker pid **9485**|ppid 29517|age 3|nr 2|max_requests 2|alive False|nr_pre 2|nr_post 2|sub_p_count 0 Unable to figure out if it is the expected behavior? -
Kafka Producer not producing through gunicorn and supervisor
I'm facing an odd situation because i can't seem to make my Kafka Producer work through my normal application flow. So in my `settings.py` file I create a global producer by calling this function: def init_producer(broker_url, delivery_timeout, retry_interval): try: return Producer( { "bootstrap.servers": broker_url, "delivery.timeout.ms": delivery_timeout, "request.timeout.ms": retry_interval, } ) except Exception as exception: logger.error( f"Couldn't connect to broker {broker_url} because of exception {exception}" ) and then I do this in `settings` file : producer = init_producer( KAFKA_BROKER_URL, KAFKA_DELIVERY_TIMEOUT, KAFKA_RETRY_INTERVAL ) After that I then have a `post_save` signal in my model that runs the producing message when an instance of my model is saved in the database: @receiver(post_save, sender=MyModel) def update_report(sender, instance, **kwargs): produce_message(instance.id) Then in my `produce_message` file I do the following: def produce_message(instance_id): try: data = json.dumps( { "id": instance_id, "client": CLIENT, "database": "NAME", } ) producer.produce( KAFKA_REPORT_TOPIC, data.encode("utf-8"), on_delivery=report_transaction_handler, ) producer.poll(1) except Exception as error: logger.log( "MONITORING", f"Error {error} on producing message for Instance {instance_id}", ) My handler function does the following: def report_model_handler(err, msg): """Called once for each message produced to indicate delivery result. Triggered by poll() or flush().""" if err is not None: value = simplejson.loads(msg.value().decode()) logger.log( "MONITORING", f"Couldn't produce message {msg.value()} to topic … -
Django Celery and Celery Beat Daemon Documentation
I am working on deploying a django app with celery/celery beat to production. I can run everything just fine with celery running as a daemon with systemctl after following the documentation: https://docs.celeryq.dev/en/stable/userguide/daemonizing.html#example-django-configuration. But the documentation is a bit confusing...do celery and celery beat need to be setup as a service with systemctl if you are using django? Or is the documentation showing that you need to configure both the service and django as it shows? -
i am using postgresql shell (this file and directory is not found) help please?
You are now connected to database "test" as user "postgres". test=# \i C:/Users/ANUJ MISHRA/Downloads/human.sql C:/Users/ANUJ: No such file or directory i am feeling very tired to solve this problem, i expecting my problem will solve here -
Django adding and showing favorites
I want the logged in user to click the favorite me button and it adds the food item to the users dashboard. Here's the model class Favorite(models.Model): consumable_id = models.ForeignKey(Consumable, on_delete=models.CASCADE) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.name Here's the template for favorite me <div class="fav-me"> <hr /> <button id="fav-btn">Favorite Me</button> </div> Here's the template for user dashboard <div class="dash-header"> <h2>Your favorite items</h2> <div class="fav-item"> {% if favorites %} {% for favorite in favorites %} <h4>Name:{{ cunsumable.name }}</h4> <p>${{ consumable.price }}</p> <button>X</button> {% endfor %} {% else %} <p>You don't have any favorites</p> {% endif %} </div> </div> Here's my views def dashboard(request, consumable_id): fav_consumables = Favorite.objects.order_by('-id') favorite_consumables = [] for fav in fav_consumables: favorite_consumables.append(Consumable(id=fav.consumable_id)) context = { 'favorites' :fav_consumables } return render(request, 'accounts/dashboard.html', context) -
How to completly delete a Django application which has dependencies with another app?
My Django project has several applications and I would like to delete one of them. To do that, I removed the models of this app and everything was fine, but after I removed the application from INSTALLED_APPS and its files, Django complains about dependencies with another application. django.db.migrations.exceptions.NodeNotFoundError: Migration anotherapp.0009_entitystatus dependencies reference nonexistent parent node ('apptodelete', '0002_alter_anotherapp_code') I've tried to reverse migrations for the app I want to remove with the zero option and Django unapplied migrations, but then after I remove the files it keeps complaining because dependencies are still present in the migration files of the other application. $ python manage.py migrate apptodelete zero What is the proper way to do that ? -
How to intergate a Django app into a Wagtail CMS
I have a small django app with some CBV's (f.i. a HTMX/ListView) I want to integrate this app in an exciting Wagtail site: So it is part of Wagtail pages, the menu structure and I can make use of Streamfields on those Django app pages. How can I achieve this? Looking for an example. Lot of examples how to integrate Wagtail into a Django app, but not the other way around. -
Frameworks for beginners [closed]
As a beginner which framework should I learn first, and which is the framework that is a must to learn. I know languages like python, java, javascript, c/c++, etc. I heard about Flask & Django but I am not sure which one to learn first. -
django restframework channels send multiple socket messages at in one go
I want to send an update message to the screen every time its details update. problem is frequent updates end up sending multiple messages to the screen. I want to wait 1 minute to watch for all the changes and send one message to the screen. I am using the Django signal to watch for changes in the database. Here is my code. //views.py class ScreenWebListCreateView(PermissionOrganizationMixins, OrganizationQuerySetMixin, generics.ListCreateAPIView): queryset = ScreenWeb.objects.all() serializer_class = ScreenWebSerializer def perform_create(self, serializer): serializer.save(organization=self.request.organization) # retrieveupdatedestroyapiview class ScreenWebRetrieveUpdateDestroyView(PermissionOrganizationMixins, generics.RetrieveUpdateDestroyAPIView): queryset = ScreenWeb.objects.all() serializer_class = ScreenWebSerializer lookup_field = 'pk' def perform_update(self, serializer): serializer.save(organization=self.request.organization) //signals.py @receiver(post_save, sender=ScreenWeb) def send_socket_message_on_screen_web_update(sender, instance, created, **kwargs): send_update_message_socket_tv(instance.screenCodeApp) @receiver(post_delete, sender=ScreenWeb) def send_socket_message_on_screen_web_delete(sender, instance, **kwargs): send_update_message_socket_tv(instance.screenCodeApp) is there a way to wait for some time to include all changes and then send an update message? -
How to select multiple relative objects of a single object at once Django ForeignKey
So I have two classes one is Book and another one is Category initially I have add the foreign key in Book which points to Category. class Category(models.Model): class Meta: verbose_name_plural = "Categories" category = models.CharField(max_length=20) def __str__(self): return self.category class Book(models.Model): book_title = models.CharField(max_length=20) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.book_title And it works fine I was able to select a category from a selected book inside the admin panel But now I want to select books from category section so that I can select all the books which are of that single category. And for that I changed the code in the following way class Book(models.Model): book_title = models.CharField(max_length=20) def __str__(self): return self.book_title class Category(models.Model): class Meta: verbose_name_plural = "Categories" category = models.CharField(max_length=20) book = models.ForeignKey(Book, on_delete=models.PROTECT) def __str__(self): return self.category The upper code returns tons of errors. Let suppose I have four books in Book table and one category in Category table. so now I want to relate all those books to that category in Category table by just opening a single category. What happening right now is that I have to open each book entry and relate to it's category. But I want a drop … -
How to fix the following group_send communication issue in Django
I want to create a websocket which will send a group message, but the following code does not seem to be working. The function that must be called is not being called, and wrapping it in a async_to_sync, results in a error. Here is the code: async def receive(self, text_data): # Store the message in the database message = json.loads(text_data) name = message['name'] text = message['message'] document = {'name': name, 'message': text} # Send the message to all connected clients # await self.send(text_data=json.dumps(message)) await self.channel_layer.group_send( self.room_group_name, { 'type':'chat_message', 'message':message } ) collection.update_one( {}, {'$push': {'text': document}} ) async def chat_message(self, event): # Send the message to all connected clients print("Message sent to group") message = event['message'] await self.send(text_data=json.dumps({'type':'chat','message': message})) However when I use await self.send(text_data=json.dumps(message)) It does work, only the group_send is not working. Below is the frontend(SvelteKit) code if needed: socket = new WebSocket("ws://127.0.0.1:8000/ws/chat"); socket.addEventListener("open", () => { console.log("Connection is successful!"); }); socket.onmessage = (e) => { const message = JSON.parse`your text`(e.data); console.log("Received message:", message); messages = [...messages, message]; }; });``` -
Django project is not displaying web page [closed]
When I include the Jinja syntax in my django project, the content of the webpage will not display so I viewed the page source and found out that some of the code are missing but when I remove the Jinja it will display but without fetching data from the database {% extends 'shop/base.html' %} {% load static %} {% block title %}Address{% endblock title %} {% block main-content %} <div class="container my-5"> <div class="row"> <h3>Welcome <span class="text-capitalize">{{request.user}}</span></h3> <div class="col-sm-2 border-end"> <ul class="list-unstyled"> <li class="d-grid"><a href="{% url 'profile' %}" class="btn ">Profile</a> </li> <li class="d-grid"><a href="{% url 'address' %}" class="btn btn-primary" >Address</a> </li> </ul> </div> <div class="col-sm-8 offset-sm-1"> <div class="row"> {% for ad in add %} <div class="col-sm-6"> <div class="card m-2"> <div class="card-body"> <h3> Address {{forloop.counter}}</h3> <p>Name: {{ad.name}}</p> <p>Locality: {{ad.locality}}</p> <p>Mobile: {{ad.mobile}}</p> <p>City: {{ad.city}}</p> <p>State: {{ad.state}}</p> <p>Zipcode: {{ad.zip_code}}</p> </div> </div> </div> {% endfor %} </div> </div> {% endblock main-content %} -
How to stop/cancel the celery task by passing 'task_id' to a python function in django?
I have celery task Id, I want to send it as query param to a django url endpoint and cancel/revoke the task using that task_id. Is it possible? If so, how? -
TypeError: MyUserManager.create_superuser() missing 1 required positional argument: 'username'
I'm trying to create a super-user using this command: "python manage.py createsuperuser", but I can't. Here's the error: "TypeError: MyUserManager.create_superuser() missing 1 required positional argument: 'username'". Here's my code: ''' class MyUserManager(UserManager): def create_superuser(self, username: str, email: str | None, password: str | None, **extra_fields: Any) -> Any: self.username = extra_fields['phone'] REQUIRED_FIELDS = ['username'] return super().create_superuser(username, email, password, **extra_fields) def create_user(self, username: str, email: str | None = ..., password: str | None = ..., **extra_fields: Any) -> Any: username = extra_fields['phone'] return super().create_user(username, email, password, **extra_fields) ''' -
Which Logging Method is Better?
When I define a logger in Django as follows logger.warning(f"{log_event_base}.celery_task.run", {"reason": "n/a"}) The SonarQube application gives a warning like this String formatting should be used correctly python:S3457 When I did some research, I found that f-string would be more performant, and when I looked at the sonarqube documentation, I saw some information that it might catch some errors at runtime. However, I think there might be a problem here as well If I use f-string, will Sentry have more of the same error? For example: logger.error("Failed to retrieve URL %s", url) logger.error(f"Failed to retrieve URL {url}") Which of these uses is more suitable for Sentry I tried logging with F-String but there may be problems with Sentry -
automatic dns registration with python selenium (bot) [closed]
in the project I am doing, I make dns settings manually when websites are written. but I want to do it automatically. so a website will be written and this dns part will be added automatically. i want to do this with python selenium. I manually register it manually, I get the dns from google and register it in my own interface. I want to do it automatically with python selenium bot can you help me -
How to deal with Django Cascade deletion and django-simple-history?
I'm working on a django project and i'd like to developp an history application to show every changes in my models. I installed the package django-simple-history that seems to be the easier and the most used. The thing is, that it raises an error when i try to delete an object involved in the ForeignKey of a child Model. Here is an example: class ParentModel(models.Model): age = models.IntegerField() name= models.CharField(max_length = 30, blank=True) history = HistoricalRecords() class ChildModel(models.Model): parent_objects = models.HistoricForeignKey(ParentModel, on_delete=models.CASCADE) book = models.CharField(max_length = 20, blank=False) history = HistoricalRecords() So i have to tables, and one refers to the other by a ForeignKey (i used the package's HistoricForeignKey in my code but it's the same). Then i access to the historic objects like this: from django.apps import apps apps.get_model("ParentModelHistorical").objects.all() apps.get_model("ChildrenModelHistorical").objects.all() The problem is when i delete a ParentModel's object. So all the related ChildrenModel's objects are also delted (the CASCADE deletion). And when i try to access again the historic objects i get this : apps.get_model("ParentModelHistorical").objects.all() #-> no errors, everything's fine apps.get_model("ChildrenModelHistorical")..objects.all() #-> ERROR : MyApp.models.parent_object.DoesNotExist: parent_object matching query does not exist. So what i understand is that the historic object of the Child Model is raising an … -
How to get a job in Canada from Amritsar
Canada is a dream place to live and work for many Indians as other countries people want to go there. There are many Indian companies in Canada hiring working on job visa The highest level of life, a wide range of career opportunities, excellent working conditions, experience, competitive earnings, and a low unemployment rate are all factors. Above all, Canada offers the best-paying jobs on the planet. It’s no surprise that many Indians move to Canada in search of work. After all, Canada, like every other foreign country, has its own set of restrictions for international workers. We’ll show you how to get a job in Canada if you’re from India. Let’s dive in! Fly-High is one of the most prominent and best immigration consultants in Amritsar to Canada & across the globe If you want to meet the demands of industries and labour markets in different provinces, Canada relies on the services of experts, trained young, and skilled workers. That demand has resulted in several job openings for deserving, skilled, and experienced candidates. It might not easy to get a Canadian work permit in India. -
Using django-filters with MPTT Model
I have a MPTT model ProductCategory class ProductCategory(MPTTModel): class MPTTMeta: order_insertion_by = ["name"] class Meta: verbose_name = "Category" verbose_name_plural = "Categories" name = models.CharField(max_length=255, verbose_name="Название категории") parent = TreeForeignKey( "self", on_delete=models.PROTECT, null=True, blank=True, related_name="children", db_index=True, verbose_name="Parent category", ) def __str__(self): return f"{self.name}" which have a ForeignKey to ProductInfo model class ProductInfo(models.Model): class Meta: verbose_name_plural = "Product info" verbose_name = "Products info" product = models.OneToOneField("Product", on_delete=models.CASCADE, null=True, verbose_name="Product") category = TreeForeignKey( "ProductCategory", on_delete=models.PROTECT, related_name="productinfo", null=True, verbose_name="category id", ) Now I want to filter unique product categories. That is, I don't want to receive all product categories, but only unique ones. My views.py class CategoryListAPIView(ListAPIView): allowed_methods = ["get"] serializer_class = CategoryListSerializer filter_backends = (DjangoFilterBackend) filterset_class = CategoryFilter def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) def get_queryset(self): return ProductCategory.objects.filter(id__in=ProductInfo.objects.filter(product__in=Product.objects.filter(store__user=self.request.user)) .filter(category_id__isnull=False) .values("category") .distinct() ) So, I get queryset type <class 'mptt.querysets.TreeQuerySet'> How should I create a FilterSet class to filter product categories in such way: api/v1/categories/?category_ids=1,2,3 My filters.py class ListFilter(filters.Filter): def filter(self, qs, value): if not value: return qs self.lookup_expr = "in" values = value.split(",") return super(ListFilter, self).filter(qs, values) class CategoryFilter(FilterSet): order_by_field = "ordering" ordering = OrderingFilter( fields=( "name", ) ) category_ids = ListFilter(field_name="id") class Meta: model = ProductCategory fields = [ … -
load static files not working even after referencing
I am trying to modify a bootstrap made webpage for my project the thing is the statis files (collectively assets) are put inside the folder so the project name is Portfolio then the static file is in tha path /static/Portfolio/static/ inside that static folder we get the /assests folder - > Portfolio/static/Portfolio/static/assets like this now i tried to do the {% load static %} method in my index.html page few of the css got applied here is the director . ├── css │ └── style.css ├── img │ ├── apple-touch-icon.png │ ├── favicon.png │ ├── hero-bg.jpg │ ├── portfolio │ ├── profile-img.jpg │ └── testimonials ├── js │ └── main.js ├── scss │ └── Readme.txt └── vendor ├── aos ├── bootstrap ├── bootstrap-icons ├── boxicons ├── glightbox ├── isotope-layout ├── php-email-form ├── purecounter ├── swiper ├── typed.js └── waypoints now here this is my header of my .HTML file {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <title>Siddharth D</title> <meta content="" name="description"> <meta content="" name="keywords"> <!-- Favicons --> <link href= " {% static 'assets/img/favicon.png' %}" rel="icon"> <link href= " {% static 'assets/img/apple-touch-icon.png' %}" rel="apple-touch-icon"> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet"> <!-- Vendor … -
Using Patch to add a new instance of a nested field when using a RetrieveAPIView in Django Rest Framework
I have a set up a route for a RetrieveAPIView and am testing it in Postman using PATCH. I am writing a value into a nested field, which is working but deletes all other instances of that nested model. Here is what I enter in 'JSON body' in Postman { "cards": [ 9 ] } When I PATCH the value '9', it deletes all other 'card' instances. I was expecting it to simply add that 'card' instance without taking the others away. This is an example of the response: { "id": 19, "name": "collector two", "email": "two@example.com", "cards": [ 9 ] } Here is my view code class CollectorRetrieveView(generics.UpdateAPIView): queryset = Collector.objects.all() serializer_class = SmallCollectorSerializer permission_classes = [HasAPIKey | IsAuthenticated] lookup_field = 'email' Serializer class SmallCollectorSerializer(serializers.ModelSerializer): class Meta: model = Collector fields = ["id", "name", "email", "cards"] Route path("collector_retrieve/<email>", CollectorRetrieveView.as_view(), name="collector_retrieve"), I tried to PATCH 'card' 9 without deleting the other card instances -
Thumbnail display problem in django templates - sorl-thumbnail
I hope you're all well. I'm making a small Django site, for the frontend I wanted to integrate thumbnail to properly visualize the graphics of the site but this is not displayed So I went through 3 steps with the sorl-thumbnail github: pip install sorl-thumbnail in the django settings, specify 'sorl.thumbnail' in the apps section Put the following lines in a template where I want to display a thumbnail {% load thumbnail %} {% thumbnail item.image "100x100" crop="center" as im %} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"> {% endthumbnail %} But nothing is displayed. Do you have any idea why?