Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Firefox refresh doesn't update web page after input fileds changed in the form without submit
I just noticed that my django web application doesn't update the input fields changed just in the form (page) after referesh in Firefox. So every press of F5- or refresh-button invokes http GET that returns the contents of the database. But if I have changed some input fields in my web page (wihout submit) in Firefox they won't become updated with the values in database. If I repeat this in Chrome the fields become updated correctly. What can be causing this? And how can I confirm that after every refresh my page would show exactly what has been stored in the database ? -
Django Elastic Beanstalk hosted application server not found
I have a Django application that I'm hosting with Elastic Beanstalk. I have setup a hosted zone & configured it with a new domain name. The site is accessible from the domain I setup & works fine, but for some reason at random times I will run into "We can’t connect to the server at www.***.com" for no apparent reason. The health of my environment says 'Ok' & I can't see any reason that it shouldn't be finding the server. I'm all out of ideas as to why I'm running into this error on occasion. (Note: It's not an internet issue, I have tried on many different devices & connections and the issues still arises after a few refreshes or route changes.) -
set the default selected item as the same for a value get from DB in Django
I have a web app using Django as the backend. In the frontend, there's a selection box. The default selection should be the same as a value get from DB. {% with query_results_book_discard_reason=query_results_book_discard_reason|index:forloop.parentloop.counter0 %} <select style="display: none" name="discard_reason" class="MySelect"> <option value="">--Select--</option> <option value="Change edition">Change edition</option> <option value="Change to eTextbook">Change to eTextbook</option> <option value="Change title">Change title</option> <option value="No material required">No material required</option> </select> {% endwith %} {{ query_results_book_discard_reason.discard_reason }} is the value from DB that would match the selection box. If {{ query_results_book_discard_reason.discard_reason }} is equal to "Change edition", the default selected item should be "Change edition" in the selection box. If {{ query_results_book_discard_reason.discard_reason }} is equal to "Change to eTextbook", the default selected item should be "Change to eTextbook" in the selection box. ... If {{ query_results_book_discard_reason.discard_reason }} is equal to None, the selection box should be original. How could managed to do that? -
Django - Raw query to ORM
models.py class Employees(models.Model): emp_no = models.IntegerField(primary_key=True) birth_date = models.DateField() first_name = models.CharField(max_length=14) last_name = models.CharField(max_length=16) gender = models.CharField(max_length=1) hire_date = models.DateField() class Meta: managed = False db_table = 'employees' class Salaries(models.Model): emp_no = models.ForeignKey(Employees, models.DO_NOTHING, db_column='emp_no',related_name='salaries', primary_key=True) salary = models.IntegerField() from_date = models.DateField() to_date = models.DateField() class Meta: managed = False db_table = 'salaries' unique_together = (('emp_no', 'from_date'),) Mysql raw query: SELECT `employees`.`emp_no`, `employees`.`birth_date`, `employees`.`first_name`, `employees`.`last_name`, `employees`.`gender`, `employees`.`hire_date`, ( SELECT JSON_ARRAYAGG( JSON_OBJECT( 'salary', `salaries`.`salary`, 'from_date', `salaries`.`from_date`, 'to_date', `salaries`.`to_date` ) ) FROM `salaries` WHERE (`employees`.`emp_no` = `salaries`.`emp_no`) ) as salaries FROM `employees` INNER JOIN `salaries` root_salaries ON `root_salaries`.`salary` > 60000 WHERE `employees`.`emp_no` = `root_salaries`.`emp_no` LIMIT 100 OFFSET 100 My question is how to generate the above raw query using Django ORM. Thanks. -
How do i let user know their active login sessions like the one we get in telegram?
I want to add a feature where user can see from how many devices they are logged in. All devices like operating system, the time they logged in , last time they were active from that device etc. -
how to submit order form and get redirect to the user's page to see all others made by the user
i am developing an app where customers can make orders and get redirected to a page to see all the orders requested but i am getting error here. below is the error message.All i want is for a user who's registered to make order and get redirected to a page where all his orders will be displayed . i will appreciate if someone could help me out here . i am developing an app where customers can make orders and get redirected to a page to see all the orders requested but i am getting error here. below is the error message.All i want is for a user who's registered to make order and get redirected to a page where all his orders will be displayed . i will appreciate if someone could help me out here . here is the error message: IntegrityError at /clients/add_item/ null value in column "location_id" of relation "clients_clientjob" violates not-null constraint DETAIL: Failing row contains (2, , null, , , , 2021-07-14 12:10:05.555719+00, Pending, 2, null). Request Method: POST Request URL: https://canwork.herokuapp.com/clients/add_item/ Django Version: 3.1 Exception Type: IntegrityError Exception Value: null value in column "location_id" of relation "clients_clientjob" violates not-null constraint DETAIL: Failing row … -
Django template variable default value not working
I am using Django 3.2 I am passing a boolean flag to a Javascript function in my base template. However, when the variable is set, it seems the default value is still being used in my template logic. Here is my code snippet: /path/to/urls.py urlpatterns = [ # ... path('foo', TemplateView.as_view(template_name="foo.html", extra_context={'show_subscription_popup':0}), name='blog'), path('admin/', admin.site.urls), ] /path/to/foo.html {% block content %} <span>{{ show_subscription_popup}}</span> {% endblock content %} {% block body_js %} <script type="text/js"> $().ready(function() { let popDisplayed = '0'; if ({{ show_subscription_popup|default:1 }}){ popDisplayed = getCookie('popDisplayed'); } /* remaining logic ... */ }); </script> When I render the page, I see that the variable show_subscription_popup has the correct value of 0, which it is passed to the TemplateView, however, in the javascript, the code reads like this: if (1){ /* do something */ } Why is the default value overwriting the value I passed to the template, and how do I resolve this issue? -
account activation email in django giving error
i got the issue with sending email for account activation in django. all email was sending including activation when the project was on development, since i took the project to the server running on nginx the activation email, after user account registration is not sending and giving this error SMTPDataError at /users/register/ (550, b'5.7.1 Reject for policy reason') i thought is the email settings but all other sending emails from the project are working , expect the one in registration. -
I setup multiple category product like ecommerce but my view showing per category just 1 item. I want to view per category 10 iteams
This is my view.py code This is my index.html code -
How do we define Django Rest Framework project apps & folder structure
Currently, I'm building an Affiliate system API using DRF. This project has 2 API directions: Internal API for front-end External API for tracking affiliate links And that's how I define my Django APP: Internal_API namely api External_API namely api_external However, Internal_API app needs to access External_API models, and each of the apps has a very massive list of models, serializers, and views. The main entities are: Affiliate (Player) Enterprise (Campaign creator) Campaign (Where affiliate plays) Order (if someone buys through link) Traffic (tracks affiliate link) and mapping tables. This is the current project structure (simplified): backend ├── api │ ├── admin.py │ ├── apps.py │ ├── models │ │ ├── affiliate.py │ │ ├── affiliateEnterprise.py │ │ ├── campaign.py │ │ ├── enterprise.py │ ├── send_emails.py │ ├── serializers │ │ ├── affiliate.py │ │ ├── affiliateEnterprise.py │ │ ├── campaign.py │ │ ├── campaignAffiliate.py │ │ ├── enterprise.py │ │ ├── order.py │ │ ├── traffic.py │ ├── urls.py │ └── views │ ├── affiliate.py │ ├── affiliateEnterprise.py │ ├── campaign.py │ ├── campaignAffiliate.py │ ├── enterprise.py │ ├── order.py │ ├── traffic.py ├── api_external │ ├── admin.py │ ├── apps.py │ ├── models │ │ ├── order.py │ … -
How to integrate the tradingview charting_library in the django app?
I have customized the tradeview chart and want to use it in my django app both locally and in production. The chart is running on its own server localhost:5000 while the django app is running on localhost:8000. How can I integrate the chart in the django app. Even if I try to serve the library files using Django server, Django is unable to find some of the HTML files in the library. -
Why Cannot call web site Django with sub domain name
I got the trouble for deployment Django app on IIS SErver, it is about the host IP /subdomain for the Django web application on the intranet. This IP has been created record in the DNS server on the intranet already. but this website can’t be requested by subdomain name, Yet I can call web site by IP successfully. IP and domain name mapping is 17x.xxx.xx.48 = es-xxx.xxx.com This is an error, you can see The error on the left-hand side of this screenshot below. ** dial tcp: lookup es-xxx.xxxx.com on 127.0.0.11:53: no such host** I used to develop ASP.NET and deploy on IIS Server, there is no problem with this issue. This is my configuration both in settings.py and IIS server. I already attempted to use nslookup and it is fine as the figure below.