Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Debugging Django request lifecycle
What's the first function Django executes after receiving a request? I need to put a breakpoint just at the moment Django receives the request and observe the methods being called next, step by step. For example, I call localhost:8000/test where do I insert the very first breakpoint to see how the middleware processes the request? -
Django Rest Framework - Why am I getting a CSRF cookie not set on only one URL when there is NO difference from the other forms
I have this URL for someone to rate an opportunity: path("opportunities/rate/", RateOpportunity.as_view), I am using a Vue application to make a post request and all the other forms on the site work fine and I can make the requests and post content but this specific endpoint gives me a CSRF cookie not set error. There is no difference between this form and the other forms. This is the view I am using: class RateOpportunity(generics.CreateAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = OpportunityRateSerializer name = "rate-opportunity" def get_queryset(self): id = self.kwargs["pk"] return Opportunity.objects.all().filter(opportunity=id) Why am I getting this error only on this endpoint and not any one of the others? -
how to remove deprecated code from the old django migration files
I am removing dead code in my django apps, and realized that one of the functions is being used in an old migration file. What is the correct way to remove this code from the old migration file without causing database issues? -
Add payment in django project to extend an expiration date of posts./
I have a project where the user can post an Ad and this Ad will be available only for 30 days. I need to add a payment method to extend the Expiration date of the Ad. Here is my Ad creation view . class AdvertiseCreateView(APIView): permission_classes = [IsAuthenticated] def post(self, request): serializer = AdvertiseSerializer(data=request.data) user = request.user if serializer.is_valid(): print(user) serializer.save(owner = user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) List view: class AdvertisesListView(APIView): def get(self, request): advertises = Advertise.objects.filter(Q (expiration_date__gt = Now())) serializer = AdvertiseSerializer(advertises, many=True) return Response(serializer.data, status = status.HTTP_200_OK) Models: class Advertise(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="advertise") category = models.CharField(max_length= 200, choices = CATEGORY) location = models.CharField(max_length= 200, choices = LOCATIONS) description = models.TextField(max_length=600) price = models.FloatField(max_length=100) expiration_date = models.DateField(default = Expire_date, blank=True, null=True) #Expire date come from another file created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) class Meta: ordering = ['created_at'] def __str__(self): return self.category So the thing is when the user make his payment the expire date extends. I need help in payment part. Thanks in Advance. -
Request url without pagination django rest
All my sistem has pagination. I want request a single url without pagination, but as a request param, not in my remove in my application, because sometimes I want with pagination and sometimes without. Anyone can help me? -
ERROR: Failed building wheel for twisted-iocpsupport
error image I was trying to install daphne===4.0.0 but I keep getting this error, ERROR: Failed building wheel for twisted-iocpsupport -
Write a test to check if a post has been removed from the old group
I need to check that the post has disappeared from the old group page. I need to get my old group for her slack. old_group_response = self.authorized_client.get( reverse('group_list', args=(self.group.slug,)) ) And compare that old_group_response.context['page_obj'].paginator.count equals zero. This means that there are no posts in our old group. And check another new group, that there is 1 post there. How can I write it in the right way? I know what rubbish is written here (I'm just learning), this is what I was able to sketch. from django import forms from django.test import Client, TestCase from django.urls import reverse from ..models import Group, Post, User NEW_POST = reverse('posts:post_create') class PostFormTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.author_auth = User.objects.create_user(username='test auth') cls.not_author = User.objects.create_user(username='Not Author') cls.group = Group.objects.create( title='Test group_title', slug='test_slug', description='Test description') def setUp(self): self.authorized_client = Client() self.authorized_client.force_login(PostFormTests.author_auth) self.authorized_client_not_author = Client() self.authorized_client_not_author.force_login( PostFormTests.not_author) def test_post_old_group_response(self): """ Check if a post has been removed from the old group.""" post = Post.objects.create( group=PostFormTests.group, author=PostFormTests.author_auth, text='test post') group_2 = Group.objects.create( title='Test group_title2', slug='test_slug2', description='Test description2') posts_count = Post.objects.count() form_data = { 'text': 'text_post', 'group': group_2.id} old_group_response = self.authorized_client.get( reverse('posts:group_list', args=(self.group.slug)), data=form_data, follow=True) self.assertEqual( old_group_response, reverse( 'posts:post_detail', kwargs={'post_id': post.pk})) self.assertEqual(Post.objects.count(), posts_count) self.assertEqual(old_group_response.context[ 'page_obj'].paginator.count == 0) -
Why would a django-rest-framework test return a different response than an identical post via postman?
Context: I'm currently rewriting my django-rest-framework implementation to use a custom permissions class. In the process, I am writing tests to make sure that any future changes don't break anything. Related Objects: View class EventViewSet(viewsets.ModelViewSet): serializer_class = EventSerializer permission_classes = [ReadOnly, CheckPermission] def get_permissions(self): # This passes the kwargs needed for the permission check to the permission class if self.action in ['create'] and self.request.user.is_authenticated: return [CheckPermission(capability='events', action='write')] if self.action in ['retrieve', 'list']: return [CheckPermission(capability='events', action='read')] elif self.action in ['update', 'partial_update'] and self.request.user.is_authenticated: return [CheckPermission(capability='events', action='edit', org=Organization.objects.get(short_name=self.request.data['organizationChange']))] elif self.action == 'destroy' and self.request.user.is_authenticated: return [CheckPermission(capability='events', action='edit')] return super().get_permissions() def get_queryset(self): user = self.request.user if 'org' in self.request.query_params: org = Organization.objects.get(short_name=self.request.query_params['org']) # check if user has necessary permissions for the specific organization perm = CheckPermission(capability='event', org=org, action='read').has_permission(self.request, self) if perm: return Event.objects.filter(organization=org, removed=False) else: #return public events for that org return Event.objects.filter(organization=org, type=0, removed=False) else: try: q1 = Event.objects.filter(type=0, removed=False) if user.is_authenticated: memberships = AccountRoleMembership.objects.filter(user=user, removed=False, role__removed=False, role__capabilities__removed=False, role__capabilities__capability__name='event', role__capabilities__read=True) orgs = get_orgs(memberships) if orgs.count() > 0: for org in orgs: # check if user has necessary permissions for events with a specific organization perm = CheckPermission(capability='event', org=org, action='read').has_permission(self.request, self) if perm: q1 = q1 | Event.objects.filter(organization=org, type=1, removed=False) return q1 else: … -
Complex JSON Serialization in Django
I have a complex JSON (trimmed) [ { "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents": [ { "decimals": "-6", "unitRef": "usd", "period": { "instant": "2021-09-25" }, "value": "35929000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "instant": "2020-09-26" }, "value": "39789000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "instant": "2019-09-28" }, "value": "50224000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "instant": "2022-09-24" }, "value": "24977000000" } ], "NetIncomeLoss": [ { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2021-09-26", "endDate": "2022-09-24" }, "value": "99803000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2020-09-27", "endDate": "2021-09-25" }, "value": "94680000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2019-09-29", "endDate": "2020-09-26" }, "value": "57411000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2021-09-26", "endDate": "2022-09-24" }, "segment": { "dimension": "us-gaap:StatementEquityComponentsAxis", "value": "us-gaap:RetainedEarningsMember" }, "value": "99803000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2020-09-27", "endDate": "2021-09-25" }, "segment": { "dimension": "us-gaap:StatementEquityComponentsAxis", "value": "us-gaap:RetainedEarningsMember" }, "value": "94680000000" }, { "decimals": "-6", "unitRef": "usd", "period": { "startDate": "2019-09-29", "endDate": "2020-09-26" }, "segment": { "dimension": "us-gaap:StatementEquityComponentsAxis", "value": "us-gaap:RetainedEarningsMember" }, "value": "57411000000" } ] } ] I have created the following class to use so that its easier to massage the data in @dataclass class Period: instant: … -
Docker: Cannot COPY from parent directory while building the image
I am trying to use docker-compose up -d for deploying my django application. The problem is that my Dockerfile and docker-compose.yml are in one directory, but need access to a requirements.txt from the parent directory. Minimal Example: Filestructure: requirements.txt (file) docker (directory) docker/Dockerfile (file) docker/docker-compose.yml (file) Dockerfile: FROM python:3.10-slim COPY ./../requirements.txt /requirements.txt docker-compose.yml: version: '3' services: django: container_name: django_123 build: context: ./.. dockerfile: ./docker/Dockerfile expose: - "8000" The setup works on Docker Desktop 4 on Windows 10, but not on Ubuntu 22. I get the error: Step 1/2 : COPY ./../requirements.txt /requirements.txt COPY failed: forbidden path outside the build context: ../requirements.txt () ERROR: Service 'django' failed to build : Build failed I already read that I should build the image from the parent directory, but I get the same error message. What could be the problem? And why does it work on Windows and not on Ubuntu? -
How to use install django_debug_toolbar
I am trying to run django_debug_toolbar I followed the instructions at: https://django-debug-toolbar.readthedocs.io/en/latest/installation.html I also saw several YouTube videos, this should be working. Here's the code ` import debug_toolbar from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('__debug__/', include(debug_toolbar.urls)), ]` I tried to install django_debug_toolbar, but it gives a 404 -
Django Python Link Dropdown Element to Database
I am working on creating a web application that will generate a report for visiting different office locations. I have implemented the choices option in a model and placed all the different offices within the choices. One of the things we have to do is take inventory of the equipment in the office ex. computers in use, computers not in user, monitors in use, monitors not in use, etc. I am wanting to make it so that essentially each inventory report is linked to the correct location based on what the user has selected so that these reports can be called later. I currently do not have a ton of code as I decided to focus on the inventory portion first. But is it even possible to link whatever the user selects as the location as the way to call previous reports? Also, would I need to create a model for each location they would be the same as the below model? Below is what I have like a said not much from django.db import models OFFICE_CHOICES = ( ('Akron, OH', 'AKRON'), ('Atlanta, GA', 'ATLANTA'), ('Austin, TX', 'AUSTIN'), ('Birmingham, AL', 'BIRGMINGHAM'), ('Boston, MA', 'BOSTON'), ('Charleston, SC', 'CHARLESTON_SC'), ('Charleston, WV', 'CHARLESTON_WV'), … -
Trying to Display Pandas DataFrame in Django HTML Output
I am currently trying to display a dataframe in HTML output with Django. Currently I have designed a view that takes in a couple csv files, runs some functions on them and then outputs a results dataframe. I am now trying to get this results dataframe to be on my html output. views.py: results_html = results.to_html(index=False) return render(request, 'home.html', {'results_html': results_html}) home.html: <html> <body> <table>{{results_html|safe}}</table> </body> </html> My home.html is in the templates folder within my overall app folder. I am trying to get this table to be displayed after clicking a button and also allow the ability to add design to the table to make it more visually appealing. I have been researching on this site and other and tried their solutions and the table still doesn't output. -
How to deal 'WSGIRequest' object has no attribute 'Get'
I am a django beginner even programming beginner this issue I have found one day still can not work out views.py from django.shortcuts import render, redirect from django.template import loader from .models import Topic from django.contrib.auth.models import User from .forms import TopicForm # Create your views here. def home(request): q = request.Get.get('q') topics = Topic.objects.filter(name__icontains=q) context = {'topics':topics} template = loader.get_template('home.html') return render(request, 'home.html', context) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Topic(models.Model): name = models.CharField(max_length=200) description = models.TextField() home.html <body> {% include 'navbar.html' %} <div> <div> <h3>Topic</h3> {% for topic in topics %} <a href="{% url 'home' %}?q={{topic.name}}">{{topic.name}}</a> {% endfor %} </div> </div> </body> I tried if statment still not work -
WebSocket connection to 'ws://localhost:8000/ws/' failed: in djangorest
(index):77 WebSocket connection to 'ws://localhost:8000/ws/' failed: (anonymous) @ (index):77 2127.0.0.1/:1 Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received i want to make websoket in my app and i always get this errror i installed djangorestchannel and redis-channel and still erorr found image of errorhere -
Python Django views.py filter button doesn't work
My models.py: class Recipe(models.Model): recipe_title = models.CharField("Назва Рецепту", max_length=50) recipe_text = models.TextField("Текст Рецепту") recipe_image = models.ImageField(default="", null=True, blank=True, upload_to="recipeImages/") isHot = models.BooleanField(default=False) isVegan = models.BooleanField(default=False) author_name = models.CharField("Імʼя автора", max_length=100) pub_date = models.DateTimeField("Дата публікації") def __str__(self): return self.recipe_title def isHOT(self): if self.isHot == True: return self.recipe_title My views.py: def index(request): latest_recipes = Recipe.objects.order_by('-pub_date')[:5] search_query = request.GET.get('search', '') if 'ishot' in request.POST: recipes = Recipe.objects.filter(isHot=True).all() else: recipes = Recipe.objects.all() if search_query: recipes = Recipe.objects.filter(recipe_title__icontains=search_query) else: recipes = Recipe.objects.all() return render(request, 'recipes/list.html', {'latest_recipes': latest_recipes, 'recipes': recipes}) 'search_query' function works, 'ishot' function itself works as well, but filter 'recipes = Recipe.objects.filter(isHot=True).all()' doesn't -
ModuleNotFoundError: No module named 'requests.adapters' when using pyfcm
I'm trying to use pyfcm library in my django project , by adding it to requiements.txt but I noticed that it is getting an error that mainly comes because of trying to import from requests library .. here is the error : rolla_django | from pyfcm import FCMNotification rolla_django | File "/usr/local/lib/python3.10/dist-packages/pyfcm/__init__.py", line 14, in <module> rolla_django | from .fcm import FCMNotification rolla_django | File "/usr/local/lib/python3.10/dist-packages/pyfcm/fcm.py", line 1, in <module> rolla_django | from .baseapi import BaseAPI rolla_django | File "/usr/local/lib/python3.10/dist-packages/pyfcm/baseapi.py", line 6, in <module> rolla_django | from requests.adapters import HTTPAdapter rolla_django | ModuleNotFoundError: No module named 'requests.adapters' and here is my requirements.txt Django~=4.1.1 djangorestframework~=3.13.1 django-extensions pymysql~=1.0.2 requests tzdata psycopg2-binary django-crontab pyfcm -
Foreign key in django signals
i need use node in created method signals, but raise this error my signals : @receiver(post_save, sender=AUTH_USER_MODEL) def create_user_progress(sender, instance, created, **kwargs): specialties = instance.specialties section = SectionSpecialties.objects.filter(specialties=specialties) section_slice = section.values_list('section_id', flat=True) node = Nodes.objects.filter(sections__in=section_slice) if created: Progress.objects.create(user=instance, node=node) my error : Cannot assign "<QuerySet [<Nodes: dsdsd - cccc>, <Nodes: chizi nemiyare - cccc>]>": "Progress.node" must be a "Nodes" instance. -
Read the time and run a function
I have a Django app which collects start time and date from the user and store in the sqlite. I want to read the date & time from database and run a function only during that time. Could anyone suggest a best way to do this? I tried with scheduler and no luck -
Django queryset related field lookup with filtering the last object
I am building a Price comparing django app, i came across this scenario where i need to filter the Last price for each seller in a related field lookup. Seller model : class Seller(models.Model): name = models.CharField(max_length=250, null=True) Part model : class Part(models.Model): name = models.CharField(null=True, blank=True, max_length=250, unique=True) Seller model : class Price(models.Model): seller = models.ForeignKey(Seller, on_delete=models.CASCADE, null=True, blank=True, related_name='sellerprice') part = models.ForeignKey(Part, on_delete=models.CASCADE, null=True, blank=True, related_name='partprice') price = models.FloatField(null=True, blank=True) added = models.DateTimeField(auto_now_add=True, null=True, blank=True) Each item for sale has 4 price history ordered by "added" and each price has the seller name next to it. views Queryset : parts = Part.objects.all() Template : {% for part in parts %} {% for y in part.partprice.all %} <a href="{{y.part.amazonURL}}"><p>${{y.price}} {{y.seller}}</p></a> ... ... ... {% endfor %} {% endfor %} price table : Problem is: I am trying to query : LAST PRICE per PRODUCT for each SELLER ordered by newest ADDED date so far i tried : >>> for part in parts: ... for price in part.partprice.all().order_by('price')[:4]: ... print(price) result : (NGK 3951) $4.0 Amazon @2023-01-09 20:36:37.083544+00:00 (NGK 3951) $5.0 Amazon @2023-01-09 20:26:12.961078+00:00 (NGK 3951) $5.5 Rockauto @2023-01-09 20:26:31.890411+00:00 (NGK 3951) $7.0 Ebay @2023-01-09 20:26:20.358864+00:00 (Bosch Automotive 9603) $1.0 … -
Defining different apps in a one page template-Django
I'm trying to deploy a website and I need to use different apps. The website is one page that elements change and you can see different pages. But the problem is that because I'm using different apps the Django needs url to call the views.py function and I don't want separated urls for each app. I want to have an template that receives all the views.py variables from different apps and show them. The models are already registered. Directory: models.py: class AboutpageText(models.Model): aboutText = models.TextField() class Icons(models.Model): iconName = models.CharField(max_length=255) def __str__(self): return self.iconName class ServiceItems(models.Model): serviceIcon = models.CharField(max_length=255) serviceName = models.CharField(max_length=255) serviceText = models.TextField() def __str__(self): return self.serviceName views.py: def aboutpage(request): aboutpageText = AboutpageText.objects.all() icons = Icons.objects.all() serviceItems = ServiceItems.objects.all() return render(request, "index.html", context={"aboutpageTexts": aboutpageText, "serviceItems": serviceItems, "icons": icons}) aboutpage_app/urls.py: urlpatterns = [ path('', views.aboutpage) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) index.html(template): {% for aboutpageText in aboutpageTexts %} <strong>{{ aboutpageText.aboutText }}</strong> {% endfor %} The values are not passed to the index.html I tried to have a views file called mainView.py in the main directory(where manage.py is) and pass all values from apps views file to this file then send the variables to template, But the didn't work too. -
Problem with gunicorn and nginx while deploying django project to digitalocean
I am trying to host a django project using digitalocean on a domain. While the project is visible in the ip address, it does not work with the domain. These are the exact steps I tried. Can you please help sort this issue. Thank you. sudo apt update sudo apt install python3-pip python3-dev nginx sudo pip3 install virtualenv mkdir ~/projectdir and cd~/projectdir source env/bin/activate pip install django gunicorn django-admin startproject test_project ~/projectdir ~/projectdir/manage.py makemigrations ~/projectdir/manage.py migrate sudo ufw allow 8000 sudo fuser -k 8000/tcp gunicorn -w 2 -b 0.0.0.0:8000 --chdir /home/MY_USER_NAME/projectdir/test_project test_project.wsgi deactivate sudo vim /etc/systemcd/system/gunicorn.socket Pasted the following content by using vim: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target sudo vim /etc/systemd/system/gunicorn.service Pasted the following content through vim: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=MY_USER_NAME Group=www-data WorkingDirectory=/home/MY_USER_NAME/projectdir ExecStart=/home/MY_USER_NAME/projectdir/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ test_project.wsgi:application [Install] WantedBy=multi-user.target sudo systemctl start gunicorn.socket sudo systemctl enable gunicorn.socket sudo vim /etc/nginx/sites-available/test_project/ Pasted the following content using vim: server { listen 80; server_name IP_ADDRESS www.MY_DOMAIN MY_DOMAIN; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/MY_USER_NAME/projectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } sudo ln -s /etc/nginx/sites-available/test_project /etc/nginx/sites-enabled/ sudo systemctl restart nginx … -
remove Django "channels" package INFO logs
I recently started using the channels package in Django (versions: channels==3.0.4 and channels-redis==3.3.1) The application is sending massive amount of unwanted logs for each request i make to Django: {"time": "2023-01-11 16:12:09 UTC", "msg": "HTTP %(method)s %(path)s %(status)s [%(time_taken).2f, %(client)s]", "logger": "edison", "level": "INFO", "log_trace": "/Volumes/dev/venv3.8/lib/python3.8/site-packages/channels/management/commands/runserver.py"} the log seems exactly the same no matter what request i send. I tried to set the channels logging level to ERROR using logging.getLogger('channels').setLevel(logging.ERROR) just like i do with other packages but it doesn't help any ideas what I need to do to remove those logs? -
Cannot run migration from Django on Docker to MariaDB installed on host
I created a Django project running on Docker, and I successfully connected from the container to the host MariaDB server as an URL host.docker.internal:3306 with the command sudo docker run -p 8000:8000 --add-host=host.docker.internal:host-gateway -d kms1212/jsis:latest. But due to several problems(I can't remember why I did it), I removed the original database, created a new database, and modified settings.py. Then I ran the modified Docker image that is built from Dockerfile: FROM ubuntu:22.04 ENV PYTHONUNBUFFERED 1 RUN apt-get -y update RUN apt-get -y install build-essential python-is-python3 pip mysql-client libmysqlclient-dev RUN mkdir /usr/local/workdir WORKDIR /usr/local/workdir COPY requirements.txt . RUN pip install --upgrade pip RUN pip install -r requirements.txt COPY jsis . EXPOSE 8000 CMD ["bash", "-c", "python manage.py makemigrations && python manage.py showmigrations && python manage.py migrate && gunicorn --bind 0.0.0.0:8000 -k uvicorn.workers.UvicornWorker jsis.asgi:application"] I dropped and recreated the database and checked that no old constraints and tables were left, but despite my effort, I got some error messages from the container log like this eventually: No changes detected admin [ ] 0001_initial [ ] 0002_logentry_remove_auto_add [ ] 0003_logentry_add_action_flag_choices auth [ ] 0001_initial [ ] 0002_alter_permission_name_max_length [ ] 0003_alter_user_email_max_length [ ] 0004_alter_user_username_opts [ ] 0005_alter_user_last_login_null [ ] 0006_require_contenttypes_0002 [ ] 0007_alter_validators_add_error_messages [ … -
What is the best way to raise an exception in case of BadHeaderError in django unit testing?
Tests fail with an error response meaning that it is likely to be allowing email with wrong data and yet it should throw an HttpResponse as expected, I have tried to figure it out why my test is failing and returning 200 http status code but not as expected = 400. Test to raise an exception def test_exception_raised(self): # register the new user response = self.client.post(reverse('register'), self.user, format='text/html') # expected response self.assertEqual(response.status_code, status.HTTP_302_FOUND) # verify the email with wrong data data = {"uid": "wrong-uid", "token": "wrong-token"} response = self.client.post(reverse('resetpassword'), data, format='text/html') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) Error File "../tests/test_passwordreset.py", line 55, in test_exception_raised self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) AssertionError: 200 != 400 Failing code