Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Websocket Connection Failed on AWS EC2 Ubuntu Instance(Django Channels)
I am trying to deploy my django chammels asgi app in ubuntu aws ec2 instance, my wsgi app is working fine also the asgi on ubuntu is working fine (tested with python websocket library) there is no error in code and daphne is running perfectly I enabled all ports in the security group of EC2 as well There is no error on the codebase and also daphne is running on localhost of EC2 ubuntu Instance perfectly server { listen 80; server_name MY_SERVER_IP; location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /ws/{ proxy_pass http://0.0.0.0:4001; proxy_buffering off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } [Unit] Description=project Daphne Service After=network.target [Service] User=root Type=simple WorkingDirectory=/home/ubuntu/myproject ExecStart=/home/ubuntu/myproject/venv/bin/python /home/ubuntu/myproject/venv/bin/d> [Install] WantedBy=multi-user.target I created this python script to determine if my daphne is working or not, it is providing me the perfect result, no error import asyncio import websockets import json async def hello(): uri = "ws://127.0.0.1:4001/ws/chat/person/?token=<CHAT_TOKEN> async with websockets.connect(uri) as websocket: await websocket.send(json.dumps({"message":"Hey there"})) g = await websocket.recv() print(g) asyncio.get_event_loop().run_until_complete(hello()) This following script returns { "id": 1, "message": "Hey There", "time_stamp": "TIME", "receiver": { "username": "John Doe", "id": … -
How to separate nav bar from the rest of the page
I am new to web development and I am working on Django framework in VSCode. I have been trying to make a user interface for the web application which has a menu on the left side of the screen and a nav bar on top which says "home page" (the image is below). There I need all the texts and photos to be in the rest part of the page, and when I scroll down I want only that part to move, like in a real web application. But I don't know how to do it, do I have to use JavaScript for that or can I just do it within HTML/CSS? As you can see in the picture the paragraph covers the nav bar. Thank you! -
How Should i store Error logs into mysql in Django
For example i want to store errors like this. this is how i want to store all error logs -
Django suddenly gives "No module named "Django""
Been making a blog and I've been busy/ill for 2 weeks, I have came back to it today and go to start my virtual environment, fine so I type python manage.py runserver and just get from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' I tried installing django again but that didn't fix the problem I dont know if it's because my postgres isn't running but when i type psql into my CLI I get psql: error: FATAL: role "toad" does not exist which I can find literally nothing about when I google it At this rate I'll be starting a new project and copy pasting everything across -
Use different view depending on whether slug refers to user or group
I would like to create pages for individual users and groups with vanity URLs following the pattern example.com/<user_or_group_name>. Usernames and group names don't conflict. I set up the following URL pattern: path(route="<str:entity_name>", view=...) I have two distinct views for user pages and group pages. I would like to use either view depending on whether user_or_group_name in the URL is a Group or a User. class GroupPage(DetailView): template_name = "userprofile/group_page.html" model = Group class UserPage(DetailView): template_name = "userprofile/user_page.html" model = User I understand that it is not possible to have to views on the same URL pattern. I could build a unified view and choose object and template depending on whether user_or_group_name is a User or a Group. Yet that feels forced. I thought about routing the URL to a dispatch function (below) but that returns AttributeError: 'function' object has no attribute 'get' raised by the clickjacking middleware. def page_dispatch(request, entity_name): try: User.objects.get(username=entity_name) return UserPage.as_view except User.DoesNotExist: return InstitutionPage.as_view How can I select the view based on whether the URL refers to a user or a group? Thank you for your help. -
Got AttributeError when attempting to get a value for field `gpa` on serializer `SubjectSerializer`
This question seems a kind of repeated one but I am not able to fix it for whole day. Problem is I have following model: class Result(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE) registration_number = models.CharField(null=True,blank=True,max_length=20) gpa = models.CharField(max_length=20) subject = models.CharField(max_length=50) I want to get result of single student so I tried filtering based on user_instance and I want data in this format. [ "user":"daneil", [ {"gpa":"A","subject":"maths"}, {"gpa":"B","subject":"science"} ] ] So I tried this in my serializers.py class ResultSerializer(serializers.ModelSerializer): class Meta: model = Result fields = '__all__' class ListResultSerializer(ResultSerializer): subject = SubjectSerializer(many=True, read_only=True) class Meta(ResultSerializer.Meta): fields = ( 'user', 'subject', ) and at the end the nested serializer for field subject was as below class SubjectSerializer(ResultSerializer): class Meta(ResultSerializer.Meta): fields = ( 'gpa', 'subject', ) I dont know What I did wrong as It gives me error stating: Got AttributeError when attempting to get a value for field `gpa` on serializer `SubjectSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'gpa'. I dont know where I made mistake any help will be helpful. -
Integrate Jaeger open tracing in my django project
In my Django project i would to integrate open tracing tecnique using Jaeger. I installed a Jaeger operator on my kubernetes cluster: So in my django project i install some packages as: django-opentracing jaeger-client opentracing then in my django settings.py i do: MIDDLEWARE = [ 'django_opentracing.OpenTracingMiddleware', ... and at the end of setting i do: import django_opentracing OPENTRACING_TRACE_ALL = True config = Config( config={ # usually read from some yaml config 'sampler': { 'type': 'const', 'param': 1, }, 'local_agent': { 'reporting_host': '10.128.33.41', #My k8s Service Cluster IP endpoint 'reporting_port': '8383', }, 'logging': True, }, service_name='jaeger-operator-metrics', validate=True, ) # this call also sets opentracing.tracer tracer = config.initialize_tracer() OPENTRACING_TRACING = django_opentracing.DjangoTracing(tracer) So i started my application , no errors all seems domìne but the question is: How can i see my jaeger dashboard for look at captured events, logging etc? There is something i have not doing? So many thanks in advance Manuel -
How to create PDF files and open them with django
hey i m working with django to create an OCR app and i m saving the OCR result into a pdf file,however whenever i try to open the file i get we can't open this file and i can't view it unless i m on vscode. if i change to files format to text then i m able to open them, i don't really know the problem exactly so any help ? here i m checking if an image is uploaded to create a file and the create pdf is just a function that runs pytesseract on the image if self.id : File.objects.create( file=(ContentFile(Create_Pdf(self.image),name='file.pdf') )) enter image description here -
Django website hosted on AWS suddenly only shows 'Index of /'
We have a Django app that is hosted on AWS. From one day on another, the website shows 'Index of /' instead of our usual landing page. We haven't changed the source code. Nobody did anything with the source code or AWS and the source code is working in our local test environment. We checked the requirements.txt file, which was suggested in a SO thread with the same issue, but there is nothing wrong with the requirements. On AWS we can see that the DB-instance is running and healthy. The AWS environment is also healthy. The only clue that we have is that there is a message on our AWS 'Personal Health Dashboard' which says that there was a 'RDS operational issue' which has been solved. There is no further info in the message that gives us insight into what might be the issue for us. Does anyone know what might be the issue? -
Updating M2M Model after save
I have two models class Item(models.Model): name = models.CharField(max_length=50) sku = models.CharField(max_length=50) description = models.TextField(max_length=100, blank=True) status = models.IntegerField(choices=TRUE_FALSE_CHOICES, default='1') def __str__(self): return self.name class Location(models.Model): name = models.CharField(max_length=50) description = models.TextField(max_length=100) items = models.ManyToManyField(Item, blank=True) def __str__(self): return self.name so what im trying to achieve is when you save a location all items assigned to that location should change status to 0. Any ideas on how can I do that ? -
Get all defined field choices from Django app
isn't there some util or function, which would iterate through all models in a django app and return something like Model.field: { key->String } values for every choice field defined on a model? Or do I have to write it myself? :) -
KeyError while makeing migrations to the files
C:\Users\SHRIYADAV\Desktop\Django\Roman\Apple\funsite>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\core\management\commands\makemigrations.py", line 149, in handle loader.project_state(), File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\db\migrations\loader.py", line 335, in project_state return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps)) File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\db\migrations\graph.py", line 315, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\db\migrations\migration.py", line 89, in mutate_state operation.state_forwards(self.app_label, new_state) File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\db\migrations\operations\models.py", line 318, in state_forwards renamed_model = state.models[app_label, self.old_name_lower].clone() KeyError: ('apple', 'items') when i started project i didn't got any error after making 80% of my project and than i try to check that my migration file are working properly i execute that line of code python manage.py makemigrations and i have the KeyError -
Saving a PDF File to Django model with a FileField
I am generating a PDF using PDFKit and I am able to successfully save the PDF to my local system and open and view the file. I am then trying to upload that PDF through a POST request to my Django REST API. Problem: When Django receives the request, I am able to receive the file and get the name and size of the file and save it to the media directory. However when I go to open the file that is sent to the server (that I previously opened on my system), it gives me an error saying it can't open the file. I am not sure what is causing this, I have tried looking into any type of encoding, but realized that's not available for a binary file so I know that's not the answer. I've tried wrapping the file in different types like ContentFile but have had no success. I will post my code below. Any help would be greatly appreciated. Models.py class Report(models.Model): asset = models.ForeignKey(Asset, on_delete=models.CASCADE) pdf = models.FileField(upload_to='reports/%Y/%m/%d/', null=True, blank=True) Views.py def post(self, request): report_id = request.query_params.get('report_id') report_pdf = request.data['file'] # Get the report object report = Report.objects.filter(id=report_id).first() # Save the generated pdf to … -
Django error 404 2458 when requesting objects by id
I am following this video trying to learn Django. I have completed this tutorial and I had the same problem even when I followed the code to a T. I am trying to get information about a model object displayed on the web-page when entering the id of the object directly in the url like http://localhost:8000/app/item/1/ or http://localhost:8000/app/item/2/ as the video shows (7:30 into the video). But when I try, I get this error: Original code from video: views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Book def index(request): return HttpResponse('Hello, world!') def book_by_id(request, book_id): book = Book.objects.get(pk=book_id) return HttpResponse(f"Book: {book.title}, published on {book.pub_date}") models.py: from django.db import models class Book(models.Model): title = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') urls.py: from django.utils import path from . import views urlpatterns = [ path('', views.index, name='index'), path('book/<int:book_id>', views.book_by_id, name='book_by_id'), ] My code: views.py: def index(request): return HttpResponse('Hello, world!') def item_by_id(request, item_id): item = Item.objects.get(pk=item_id) return HttpResponse(f"Item: {item.title}, published on {item.datetime_found}") models.py: from django.db import models from django.utils.timezone import now class Item(models.Model): title = models.CharField(max_length=200) # Short description of the item datetime_found = models.DateTimeField(default=now, blank=True) # Date and time of when the item was found urls.py: from django.urls import path … -
Trying to get SearchVector to search multiple words in multiple fields
I am currently using PostgreSQL, Python, and Django for my personal project. The webpage has a search bar which I got working using SearchVector. The problem I'm having is that my search bar function and request.GET method returns a tuple, and search vector searches for that exact phrase in my database. Basically single word searches work fine, but as soon as someone puts in another word or phrase, that exact phrase must be in the database or nothing is returned. For example: I put the word "god" into the search and all entries with "god" show up fine. But I put the phrase "god snake" into the search and nothing comes up even though there are entries with those words in them. Here is my search bar function: def searchbar(request): if request.method == "GET": search = request.GET["search"], print(search) print(search[0]) deity = Deity.objects.annotate(search=SearchVector('name', 'location', 'alt_name', 'culture', 'religion', 'description', 'pop_culture'),).filter(search=SearchQuery(search[0], search_type='phrase')), context = { "user": User.objects.get(id = request.session['user_id']), "deity": deity, "search": search[0], } return render(request, 'search_results.html', context) -
Django form imageupload give empty dic
hi i am trying to create edit profile form ,in which i am trying to data from edit profile form ,i am getting all data in request.POST but i am getting emply {} using request.Files view.py class EditProfile(View): template_name="todo_app/edit_profile.html" def get(self,request,pk): if request.user.is_authenticated: user_id=pk profile=UserProfile.objects.get(user=user_id) content={ 'profile':profile, } return render(request,self.template_name,content) else: return redirect('todo_app:login') def post(self,request,pk): request_data=request.POST first_name=request_data.get('first_name') last_name=request_data.get('last_name') mob_no=request_data.get('mob_no') address_1=request_data.get('address_1') address_2=request_data.get('address_2') gender=request_data.get('gender') age=request_data.get('age') state=request_data.get('state') city=request_data.get('city') country=request_data.get('country') bio=request_data.get('bio') # profile_pic=request.FILES['profile_pic'] print(request_data) print("_"*123) print(request.FILES) return redirect('todo_app:edit_profile',pk) and print result on console is <QueryDict: {'csrfmiddlewaretoken': ['mkfuwR6Uc99svosQvsVpho11JOXOdESSmp2sm1ULDFrFu3UHRrkASTWeSyRwXyzH'], 'first_name': ['upasana'], 'last_name': ['kulshresths'], 'address_1': ['9 Purushottam Nagar'], 'address_2': ['Dayal Bagh'], 'mob_no': ['9087654321'], 'gender': ['Male'], 'age': ['12'], 'state': ['Uttar Pradesh'], 'city': ['Agra'], 'country': ['India'], 'bio': ['Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professo'], 'profile_pic': ['Screenshot from 2021-07-14 16-44-31.png']}> ___________________________________________________________________________________________________________________________ <MultiValueDict: {}> edit_profile.html <form method="POST" action="{% url 'todo_app:edit_profile' profile.user.id %}" enctype="multipart/form-data"> {% csrf_token %} <div class="form-row"> <div class="col-md-6 mb-3"> <label for="first_name">First name</label> <input type="text" class="form-control" id="first_name" value="{{profile.user.first_name}}" name="first_name" required> </div> <div class="col-md-6 mb-3"> <label for="last_name">Last name</label> <input type="text" class="form-control" id="last_name" value="{{profile.user.last_name}}" name="last_name" required> </div> <div class="col-md-6 mb-3"> <label for="address_1">Address line 1</label> … -
Filtering on a foreign key of a many to many field in django?
I have a set of django models that looks something like this: class Profile(models.Model): attributes class Package(AuditBaseModel): name = models.CharField(max_length=128) active = models.BooleanField(default=True) class ProfilePackage(AuditBaseModel): profile = models.ForeignKey(Profile, related_name="profile_packages", on_delete=models.CASCADE) package = models.ForeignKey(Package, related_name="profile_packages", on_delete=models.PROTECT) active = models.BooleanField(default=True) What I need is way to filter on the package name from the profile. I know I can do something like ProfilePackage.objects.filter(active=True, package__name="Professional").select_related("profile") and that will give me a queryset that includes profiles with that package, but I need to combine this with other filters and I would prefer that profiles model be the top level. -
DRF: to_representation() called twice on serializer update()
My site has a Vue frontend with a DRF backend. I have a model with a multi-value field that looks like this: stages = StageSerializer( many=True, read_only=True ) In the to_representation() method, I process the stages data into three different elements to facilitate features for the frontend. def to_representation(self, instance): results = super().to_representation(instance) return render_stages(results) The problem is, when I post (PATCH actually) to an update view, which ends up calling the update() method of the serializer, the to_representation() method seems to be called twice. I could post the code from render_stages(), but I don't see how that could be causing the problem. Suffice to say that it takes this, from the call to super().to_representation(): { . . other fields . "stages": [ { "id": 1, "name": "To Do" }, { "id": 2, "name": "In Progress" }, { "id": 3, "name": "Done" } ] } ...and turns it into this: { "stages": [ "To Do", "In Progress", "Done" ], "stages_order": "1,2,3", "stages_data": [ { "id": 1, "name": "To Do", "order": 1 }, { "id": 2, "name": "In Progress", "order": 2 }, { "id": 3, "name": "Done", "order": 3 } ] } As you can see, the format of the "stages" … -
How to create login in Django?
i can't create login view. I try to login as created superuser, but i can't. I tried create user via admin panel, but i can't login too as that user. login_view function: def login_view(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user = authenticate(request, email=email, password=password) if user is not None: login(request, user) print('successful') else: print('failed') return render(request, 'login.html') login.html: <body> {% if request.user.is_authenticated %} <p>You are logged</p> {% else %} <form class="w-50 mx-auto" method="POST"> {% csrf_token %} <div class="form-group"> <input type="email" class="form-control" placeholder="Enter email" name="email"> </div> <div class="form-group"> <input type="password" class="form-control" placeholder="Enter password" name="password"> </div> <button type="submit" class="btn btn-primary">Log in</button> </form> {% endif %} </body> -
Media Folder Configuration path not found in django
I am using MYSQL for the database. I want to upload my imagefield files in media folder that I have created in my project. I am getting "empty path didn't exist". settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' models.py class Product(models.Model): category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='product_creator') title = models.CharField(max_length=255) author = models.CharField(max_length=255, default='admin') description = models.TextField(blank=True) image = models.ImageField(upload_to='images/') slug = models.SlugField(max_length=255) price = models.DecimalField(max_digits=4, decimal_places=2) in_stock = models.BooleanField(default=True) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Products' ordering = ('-created',) def __str__(self): return self.title urls.py from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have registered the model successfully in admin.py. -
Method Delete Not Allowed - destroy() method Django
I have looked online for all possible solutions to this recurring question, but nothing I have tried works. I have a view set that retrieves and creates certain information. For reference, retrieving and creating that information is specific to each user. If a user has already created an entry, they are not allowed to create another. The two methods for retrieving and creating right now are as follows: class MyViewSet(ModelViewSet): queryset = MyModel.objects.all() serializer_class = MySerializer def get_queryset(self): return self.queryset.filter(user=self.request.user.username) def create(self, request, *args, **kwargs): result = MyModel.objects.filter(user=request.user.username) if (result): return Response(status=405) # Otherwise, create an entry for that user The endpoint to both of these operations don't include an arguments in the URL. In other words, they are GET /my-endpoint/ and POST /my-endpoint/ (since each operation is specific to a user) Right now, I am trying to add a DELETE operation using destroy(). I understand that a destroy() sometimes requires a pk, but from what I've seen online, you can bypass that by specifying pk=None as I've done below. As I mentioned before, my-endpoint/ does not require any arguments or parameters in the URL so deleting an entry for a given user can be done by calling DELETE my-endpoint/. … -
Simple background task that runs after the response was sent
My Django project needs a simple background task library that doesn't require tons of services behind (e.g. celery, rabbitmq, redis etc). I'm looking for library that executes the task once the HTTP response was sent (similar to Starlette's BackgroundTask idea.) I tried to utilise the Signals in Django using this sample code: import time import django.dispatch from django.dispatch import receiver pizza_done = django.dispatch.Signal() @receiver(pizza_done) def on_pizza_done(sender, toppings, **kwargs): time.sleep(10) print(toppings) However the view that sends this signal hangs for the 10 seconds as per the on_pizza_done pseudo-logic. Does anyone know a Python/Django library for the above requirement? I would compromise if the backend for tasks is Postgres database (as that's what we use). I looked on django packages but everything seems to be around queues/heavy dependencies. I'm on Django 3.2.x and Python 3.9 so I can benefit from the asynchronous support that was added in Django 3.1. -
taking all specific folders and take all files with specific extentions inside them on windows
I have all my django apps in one common project_apps dir. Inside it I had for example -app_1 -fixture -test test1.json models.py serializers..py urls.py views.py -app_2 -fixtures -test test2.json models.py serializers.py urls.py views.py ... etc. when I run this script on ubuntu python manage.py loaddata ./project_apps/*/fixtures/test/*.json it works fine. It takes all fixtures folders in project_apps and then takes all files in fixtures folder with extension .josn and loads the data. All good, but when I run this script on Windows, i got this error No fixture named '*' found. How can I make it work on Windows? -
Celery worker not starting: "Module 'proj' has no attribute 'celery'"
I'm using Django, Celery, and RabbitMQ. When I run celery -A FlakeFinder worker -l INFO, I get the error: Usage: celery [OPTIONS] COMMAND [ARGS]... Error: Invalid value for '-A' / '--app': Unable to load celery application. Module 'flakefinder' has no attribute 'celery' If I instead run celery -A FlakeFinder.celeryApp worker -l INFO, I get this error in purple text: ModuleNotFoundError: No module named 'celery.backends.amqp' I'm not really sure where to go from here. How can I get the celery worker running? My folder structure looks like this: . (FlakeFinder) ├── FlakeFinder │ ├── __init__.py │ ├── asgi.py │ ├── celeryApp.py │ ├── secrets.py │ ├── settings.py │ ├── tasks.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── license.txt ├── manage.py ├── scraping │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ ├── models.py │ ├── scraper.py │ ├── tests.py │ └── views.py celeryApp.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab # scheduler # default django settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'FlakeFinder.settings') app = Celery('FlakeFinder') app.conf.timezone = 'UTC' app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() app.conf.beat_schedule = { # executes every 1 minute 'scraping-task-three-hr': { 'task': 'scraping.tasks', 'schedule': crontab() } } tasks.py from scraping.scraper import … -
How to enable partial searches for all fields?
Imagine I ahve the following filters.py: class ActionFilter(django_filters.FilterSet): class Meta: model = Action fields = "__all__" Now, I want to enable partial searches for Charfield fields in my model. How can this be enabled?