Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Call a viewset in another viewset with POST method
I want to call a function of a viewset in another viewset, with POST method. I succeed this with GET : params = {"number" : 44} zm = ZoneViewSet.as_view({"get": "zm"})(request._request, **params).render().content but, I can't with POST, I don't known how to do that :(, I've this error "GET method not allowed" : params = { "target": datetime.now().strftime(self.format_date), "value": 9, "origin": "auto", } post_zm = AccessViewSet.as_view({"post": "add"})(request._request, **params).render().content Can you help me please ? Thanks F. -
Pass in dynamic href using Django include template tag AND url tag
I'm trying to reuse a component and invoke it multiple times using the include tag. But when I want to pass in a url, I can't figure out the syntax. Usually it would be something like: <a href="{% url 'slug' %}">{{link_title}}</a> But as I'm already using an include, I want to do something equivalent to: # parent template: {% include 'my-template.html' with slug='someslug' link_title='My Link Title' %} # include template: <a href="{% url '{{slug}}' %}">{{link_title}}</a> I currently get django.urls.exceptions.NoReverseMatch from this code -
nginx+uwsgi stops responding after auto reload
I have a docker container based off Alpine 3.16 It runs nginx/uwsgi with supervisord for a django based app. This Dockerfile has been pretty much the same for several years now. Auto reload worked fine. Suddenly today after the container rebuilt, auto-reload fails in a strange way - it get hung up for minutes and then works - here is the log: 2023-02-20 14:57:28,771 INFO RPC interface 'supervisor' initialized 2023-02-20 14:57:28,771 INFO RPC interface 'supervisor' initialized 2023-02-20 14:57:28,771 INFO supervisord started with pid 1 2023-02-20 14:57:28,771 INFO supervisord started with pid 1 2023-02-20 14:57:29,774 INFO spawned: 'nginx' with pid 7 2023-02-20 14:57:29,774 INFO spawned: 'nginx' with pid 7 2023-02-20 14:57:29,777 INFO spawned: 'uwsgi' with pid 8 2023-02-20 14:57:29,777 INFO spawned: 'uwsgi' with pid 8 [uWSGI] getting INI configuration from /usr/lib/acme/lib/wsgi/uwsgi.ini 2023-02-20 14:57:29 - *** Starting uWSGI 2.0.21 (64bit) on [Mon Feb 20 14:57:29 2023] *** 2023-02-20 14:57:29 - compiled with version: 12.2.1 20220924 on 15 February 2023 09:44:04 2023-02-20 14:57:29 - os: Linux-6.1.11-arch1-1 #1 SMP PREEMPT_DYNAMIC Thu, 09 Feb 2023 20:06:08 +0000 2023-02-20 14:57:29 - nodename: b5d838731ef0 2023-02-20 14:57:29 - machine: x86_64 2023-02-20 14:57:29 - clock source: unix 2023-02-20 14:57:29 - pcre jit disabled 2023-02-20 14:57:29 - detected number of … -
'Response' object has no attribute 'get' in django
AttributeError: 'Response' object has no attribute 'get' in django enter image description here -
Static files not loading in django app + nginx server + docker
I have a django app I want to host on virtual machine via a docker container and I am using an nginx server to run the application. The problem now is i am not sure how to configure the nginx server to ensure that static files are being served. This is how the admin page loads without static files Here are my configuration files Dockerfile FROM python:3.10 ENV PYTHONUNBUFFERED=1 RUN mkdir -p /kings WORKDIR /kings COPY requirements.txt /kings/requirements.txt COPY ./kings /kings RUN pip install -r /kings/requirements.txt COPY ./entrypoint.sh /kings/entrypoint.sh CMD ["sh", "/kings/entrypoint.sh"] docker-compose.yml version: '3' services: kings-app: build: context: . dockerfile: ./DockerFile volumes: - .:/kings ports: - "8000:8000" image: kings-app:kings container_name:kings-ap depends_on: - kings-redis environment: - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASSWORD=${DB_PASSWORD} - DB_HOST=${DB_HOST} - DB_PORT=${DB_PORT} - ALLOWED_HOSTS=${ALLOWED_HOSTS} - REDIS_HOST=${REDIS_HOST} - REDIS_PORT=${REDIS_PORT} kings-redis: image: redis:alpine container_name: kings-redis nginx: image: nginx:alpine container_name: kings-nginx ports: - "1337:80" volumes: - ./nginx/default.conf:/etc/nginx/nginx.conf - ./static:/kings/static depends_on: - kings-app nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; upstream app_server { server kings-app:8000; } server { listen 80; server_name localhost; location /static/ { alias /kings/static/; } location / { proxy_pass http://app_server; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; … -
How to convert date in python
Iam using fullcalendar fullcalendar From my web template iam getting 2 dates in django a startdate and an enddate Getting my startdate: start = request.GET.get('start', None) I need a datetime for my django model, so iam getting an error: django.core.exceptions.ValidationError: ['“Mon Feb 20 2023 16:07:47 GMT+0100 (Midden-Europese standaardtijd)” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] Can i convert it to datetime? -
Django-Delete window/Browsing history
I want to delete the browsed pages record from browser back button and want to redirect to a specific page. Is there a way to do this? -
How to create a django generic relation to the same model like foreignkey to self
I am building a comment model which i made generic using the django recommended way like so class GenericRelationship(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() date_created = models.DateTimeField(default=timezone.now) class Meta: abstract = True class Comment(GenericRelationship): created_by = models.ForeignKey( "account.User", on_delete=models.CASCADE, related_name="comments", related_query_name="comment", ) mentions = models.ManyToManyField( "account.User", related_name="mentions", related_query_name="mention" ) content = QuillField() text_content = models.TextField() likes = GenericRelation(Liked, related_query_name="comment") class Meta: ordering = ["-date_created"] indexes = [ models.Index(fields=["content_type", "object_id"]), ] def __str__(self): return self.created_by.username but in my case a comment can also have comments and i want a reverse relationship(related_query_name) with itself and wont be able to refer to the Comment class like so class Comment(GenericRelationship): ... comments = GenericRelation(Comment, related_query_name="comment") i dont know if i could use a string with self inplace of concrete class i tried using the self but i dont know if its correct cause no real migrations can be made since it's just a reverse relationship: therefore i wont be able to see errors -
I got a problem with send a random message from DRF to all users(Aiogram)
The code doesn't throw any errors, but it doesn't work the way I would like it to. It doesn't send the message to the users. I put a print on the time function, but apparently it didn't work. I've been messing around with this for a very long time and don't understand where I went wrong from aiogram import Bot from aiogram.types import ParseMode from aiogram.utils import exceptions from servises.advertisement_services import advertisements_service from servises.subscription_services import subscription_service async def send_message(user_id, message): try: await Bot.send_message(chat_id=user_id, text=message, parse_mode=ParseMode.HTML) except exceptions.BotBlocked: print(f"Target \[ID:{user_id}\]: blocked by user") except exceptions.ChatNotFound: print(f"Target \[ID:{user_id}\]: invalid user ID") except exceptions.RetryAfter as e: print(f"Target \[ID:{user_id}\]: Flood limit is exceeded. Sleep {e.timeout} seconds.") await asyncio.sleep(e.timeout) return await send_message(user_id, message) except exceptions.TelegramAPIError: print(f"Target \[ID:{user_id}\]: failed") async def send_message_to_all_users(message): users = subscription_service.get_users() for user in users: user_id = user\['account_id'\] await send_message(user_id, message) async def send_random_message_to_all_users(): current_time = datetime.datetime.now().strftime('%H:%M') print(f"Current time: {current_time}") if current_time == '17:20': response = advertisements_service.all_advertisement() messages = response.json() message = random.choice(messages) await send_message_to_all_users(message) async def scheduler(): while True: await send_random_message_to_all_users() await asyncio.sleep(5) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.create_task(scheduler()) loop.run_forever() -
Excluded fields is appears django fomrs
I wants to exclude the email and image fields but during the rendering it still shows both fields.. class UserRegisterForm(UserCreationForm): username = forms.CharField(max_length=10, widget=forms.TextInput(attrs={'class': 'form-control','placeholder':'username'})) email = forms.EmailField(max_length=20, widget=forms.EmailInput(attrs={'class': 'form-control','placeholder':'Email'})) password1 = forms.CharField(label="Password", widget=forms.PasswordInput(attrs={'class': 'form-control','placeholder':'Password'})) password2 = forms.CharField(label="Confirm Password", widget=forms.PasswordInput(attrs={'class': 'form-control','placeholder':'Confirm Password'})) image = forms.ImageField(required=False) class Meta: model = User fields = ['username', 'password1', 'password2'] exclude = ('email','image',) profile.html <div class="col-sm-5 offset-1"> <div class="form-group"> <form method="post"> {% csrf_token %} {{ form|crispy }} <div class="text-center mt-3"> <button type="submit" class="btn btn-primary btn-lg">Update</button> </div> </form> </div> Additionally when I tried fields = "__all__" exclude = ('email','image',) it shows information such as Last login,Superuser status,Groups which is visible at /admin [] How can i render only specific fields..? -
Django transaction rollback failed
I have problems in facing for transaction rollback. So I try to change the is_active status. As I input 10 for is_active(BooleanField), Validation Error will be raised as 10 is invalid. When I excute the following codes, id=2 's status will change to 1 and id="5" status will not be changed. What I want is I want even id="2" status also rollback and does not change. Could any please kindly assist? data = { "2":"1", "5":"10" } save_id = transaction.savepoint() try: with transaction.atomic(): for key, value in data.items(): User.objects.filter(id=key).update(is_active=value) except Exception as e: print(e) transaction.savepoint_rollback(save_id) return False transaction.savepoint_commit(save_id) return True I want even id="2" status also rollback and does not change. Could any please kindly assist? -
Integrity Error in Django project (NOT NULL constraint failed)
I am making auctions site right now and when i try to set my boolean to True/False by clicking a button, i get this error: NOT NULL constraint failed: auctions_bid.bid_offer It revealed after I added listing.save() to POST button Here is the code: Views: if request.method == "POST": # listing.owner = bid_owner # listing.price = bid_offer listing.isActive = False listing.save() Here is where i get error if request.method == "POST": #BID FORM new_bid = request.POST.get("new_bid") f = Bid(bid_offer = new_bid, listing_offer = listing, bid_owner = request.user) f.save() return HttpResponseRedirect(f'./{itemID}') Form itself: <form action = "{% url 'auctions:listing' itemID %}" method = "post"> {% csrf_token %} {%if user.id == owner.id%} <input type = "submit" value = "Accept" id = "accept_bid"> {% endif %} </form> Bid model: class Bid(models.Model): bid_offer = models.IntegerField() listing_offer = models.ForeignKey(Listing, on_delete = models.CASCADE, related_name = "listings", null = True) bid_owner= models.ForeignKey(User, on_delete = models.CASCADE) Listing Model: class Listing(models.Model): title = models.CharField(max_length= 64) description = models.CharField(max_length= 128) img = models.ImageField(upload_to = 'auctions/media/images') isActive = models.BooleanField(default= True, blank=True) owner = models.ForeignKey(User, on_delete = models.CASCADE, related_name="user") categories = models.ForeignKey(Category, on_delete = models.CASCADE, blank= True, null = True, related_name = "category", default = "None") price = models.IntegerField(default = 0) When I … -
How to debug a dockerized django in Visual Studio Code?
I am facing problems integrating the VS Code debugger into my project which is dockerized. About my project, it was not made by me, so as much I entered before, I am facing some challenges with Docker, but also learning. We use this command to access the local host: docker-compose -f docker-compose.dev.yml up -d And this is the docker-compose.dev which is here as file: /.vscode /config /example_app ... .dockerignore .gitignore docker-compose.dev #The one who we up And this is the file volumes: postgres_data_test: {} hashes: {} product_api_root: {} services: postgres: image: postgres:10 volumes: - postgres_data_test:/var/lib/postgresql/data - ./backups:/backups ports: - "8889:5432" environment: - POSTGRES_USER=example - POSTGRES_PASSWORD=example django: build: context: . dockerfile: Dockerfile.dev command: python /app/manage.py runserver 0.0.0.0:8000 volumes: - .:/app - hashes:/hashes - product_api_root:/product-api-root ports: - "8000:8000" environment: - POSTGRES_USER=example - POSTGRES_PASSWORD=example - DATABASE_URL=postgres://example:example@postgres:5432/example - REDIS_URL=redis://redis:6379/0 - DJANGO_SETTINGS_MODULE=config.settings.local depends_on: - postgres - redis redis: image: redis:6.2.6 I have been trying two options to debug it First option This is the one which VS Code itself documented which is configuring the tasks.json and launch.json inside the .vscode folder: For reference: https://code.visualstudio.com/docs/containers/debug-python This is the launch.json that I tried (I tried a lot but this was the last one, the others I tried … -
Inertia Link not redirecting on click (this.resolveComponent is not a function)
I'm trying to get Django, Inertia and Vue running. I followed this doc (including the referred ones inside that): https://pypi.org/project/inertia-django/ While it works basically (the Vue pages/components render, pages load), I can't use the <Link> component. It renders and shows the correct destination on hovering, but when you click on it, the console shows Uncaught (in promise) TypeError: this.resolveComponent is not a function and it's not redirecting. Although it's changing the page, I can see the corresponding get request in the django server console. The router.visit() function works fine. main.html {% load django_vite %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% vite_hmr_client %} {% vite_asset 'js/main.js' %} <title>Django-mysite</title> <script src="https://cdn.tailwindcss.com"></script> </head> <body> {% block inertia %}{% endblock %} </body> </html> main.js import 'vite/modulepreload-polyfill' import {createApp, h} from 'vue'; import {createInertiaApp } from '@inertiajs/vue3'; const pages = import.meta.glob('./pages/**/*.vue'); createInertiaApp({ resolve: async name => { return (await pages[`./pages/${name}.vue`]()).default }, setup({el, App, props, plugin}) { const app = createApp({render: () => h(App, props)}) app.use(plugin) app.mount(el) }, }) vite.config.js const { resolve } = require('path'); import vue from '@vitejs/plugin-vue'; module.exports = { plugins: [vue()], root: resolve('./static/src'), base: '/static/', server: { host: 'localhost', port: 3000, open: false, … -
Django: Internal error popped in the first page of list view but normal in other pages
My project has an Order model and a corresponding ListView integrated with a Paginator. I run the code successfully in local development. There is no problem rendering the first and other pages of orders. Also, even after I deployed my project on Heroku, it rendered perfectly. However, the ListView now popped out internal error when I was viewing the first page but no problem at all in case of other pages (e.g page 2, 3 etc). Having checked all the codes in the template, view and model, I still couldn't find the problem. Any insights on this please? What other part am I missing? Thank you. -
Django duplicate column name after dropping and re-creating table
I'm new to Django and am working on my first project. I have multiple tables in the project (I'm using the default sqlite3). One of the tables 'C' is empty. All of the other tables have already been populated with data. Among them table 'M' has a foreign key that is linking it to C's id field (c_id). At some point I changed the max_length of C's id field (c_id) from 5 to 4. I run migrations after that and got an error: django.db.utils.IntegrityError: The row in table 'myapp_M' with primary key '00001' has an invalid foreign key: myapp_M.c_id contains a value '' that does not have a corresponding value in myapp_C.c_id. the field 'c' in 'M' table that is a foreign key has blank=True. I tried adding null=True and running migrations again but it did not help. I decided that maybe dropping the C table, since it's still empty, and creating it again might solve the problem. I have dropped it manually using SQL DROP TABLE, and then used this tutorial to re-create it: https://techstream.org/Bits/Recover-dropped-table-in-Django When I'm running the migrations I am getting the error: django.db.utils.OperationalError: duplicate column name: c_id (which is the first column defined in my model) … -
How to have vscode syntax highlight for django template tag in js
Is there a way to have a proper django syntax highlight in vscode when using django template tag in a tag in templates ? -
How to run a bokeh server app without 'bokeh server --show' command in Django project?
I have a Django project in which I need to add graphs with python callbacks implemented in Bokeh. How to run a bokeh server app from django view without 'bokeh server --show my_app.py' command? I found realization with commandline, but I don't know how i should retun it as HTTPResponse from the Django view. -
Test email does not arrive in mail.outbox when sent by Django-RQ worker
I've set up a test within Django that sends an email, in the background, using Django-RQ. I call the code that enqueues the send_email task, then, I get the django-rq worker, and call .work(), with burst=True. In my console, I can see the django-rq worker picking up the job, and confirming that it's been processed successfully. However, the email never arrives in Django's test mail.outbox. Here is the test code: def test_reset_password(self): c = Client() page = reverse_lazy("accounts:password_reset") response = c.post(page, {'email': 'joe@test.co.uk'}) self.assertRedirects(response, reverse_lazy("accounts:login"), 302, 200) django_rq.get_worker(settings.RQ_QUEUE).work(burst=True) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Password reset instructions') And here's the output from the console when the test is run: Found 2 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). .Worker rq:worker:0e599ef7e7e34e30a1b753678777b831: started, version 1.12.0 Subscribing to channel rq:pubsub:0e599ef7e7e34e30a1b753678777b831 *** Listening on default... Cleaning registries for queue: default default: send() (214c3a65-c642-49f2-a832-cb40750fad2a) default: Job OK (214c3a65-c642-49f2-a832-cb40750fad2a) Result is kept for 500 seconds Worker rq:worker:0e599ef7e7e34e30a1b753678777b831: done, quitting Unsubscribing from channel rq:pubsub:0e599ef7e7e34e30a1b753678777b831 F ====================================================================== FAIL: test_reset_password (accounts.tests.AccountsTest.test_reset_password) ---------------------------------------------------------------------- Traceback (most recent call last): File "/workspace/accounts/tests.py", line 30, in test_reset_password self.assertEqual(len(mail.outbox), 1) AssertionError: 0 != 1 ---------------------------------------------------------------------- Ran 2 tests in 1.686s FAILED (failures=1) Is it possible the email is going to … -
Django Channels Data Compression
Is there a way to compress stream data sent via Django-Channels consumer? Couldnt find any information in Documentation. Is it not recommended to compress stream data? -
How to create models in django for index and data that already exists in elasticsearch. And also paginate the data fetched
My data is stored in elasticsearch database.I want to fetch this data using django ,paginate and display in the front end I have tried search function of elasticsearch dsl and django paginator.But on click of next page querying the whole set again makes it inefficient.Hence want to convert similar to django queryset. There will be no write operation to Elastic search -
How to call an api in django signals
Can someone share a code about how to call an api in django signals.Here is some code that i have done: @receiver(pre_delete, sender=Product) def pre_delete_profile(sender, **kwargs): print("You are about to delete something!") -
combine serializer choicefield and serializermethodfield
I have class Person with qualification field. class QUALIFICATION_CHIOCES = [('mt', 'Matriculation'), ('pr', 'pre_university'), ('gd', 'graduate'), ('pg', 'post_graduate'), ('ot', 'other')] class Person(models.Model): name = models.CharField(max_length=255) qualification = models.CharField(choices=QUALIFICATION_CHIOCES, max_length=2) serializer class PersonSerializer(serializers.ModelSerializer): qualification = serializers.SerializerMethodField('get_qual') class Meta: model = Person def get_qual(self, obj): return obj.qual Now i want to want add below line in the above code not able to figure it out as i am using custom field name qual which doesn't exist. qualification = serializers.ChoiceField(choices=QUALIFICATION_CHIOCES) if i simply add the above line i get the error like the field is required. now how can i accept the input with custom_variable meanwhile check with the choices. -
Django shipping method
I have a question about shipping in django. I would like to automate shipping so that automatically when the courier delivers the package the status in the database changes to delivered, etc.... Someone could direct me to some reading on how to do this. Or is it a good standard to just make the shipments in django-oscar and give an admin-panel that will quite transparently change them non-automatically? Or is it standard to capture emails and pull the data you need from them and based on that make a django-celery-task that will do that? -
Django+ DRF + Celery: Schedule the same task for different objects in database in different time for each object
I am working on an HR application, where a company has a branch and each branch has its working days policy in which the branch decides the hours of start and end of work day and the hour when the day is absence for employee if they didn't checked in and the weekend days, class WorkingDaysPolicy(TimeStampedModel): WeekendDays = ( (5, "Saturday"), (6, "Sunday"), (0, "Monday"), (1, "Tuesday"), (2, "Wednesday"), (3, "Thursday"), (4, "Friday"), ) id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) branch = models.ForeignKey( Branch, on_delete=models.CASCADE, blank=True, null=True, related_name="branch_working_days", ) number_of_daily_working_hrs = models.PositiveSmallIntegerField( _("Number of daily working hours") ) weekend_days = MultiSelectField( _("Weekend days"), choices=WeekendDays, null=True, blank=True ) normal_overtime_hourly_rate = models.FloatField( _("normal overtime hourly rate"), null=True, blank=True ) day_starts_at = models.TimeField(_("Working day starts at"), blank=True, null=True) day_ends_at = models.TimeField(_("Working day ends at"), blank=True, null=True) absence_Starts_at = models.TimeField(_("Absence Starts at"), blank=True, null=True) now I have a background task that must work exactly at the absence_Starts_at time and only on the working days. I tried to import the WorkingDaysPolicy model on celery.py to loop over its objects and assign a task for each branch but the app crashed on starting the dev server and raised raise AppRegistryNotReady("Apps aren't loaded yet.") How can I run …