Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to build API that will return HTML for the site and JSON for other clients
I have started learning DRF just a while ago and had a little question - how can I code one API that will return HTML for the site that I am currently working on and return JSON format for other "clients"(e.g. mobile apps, desktop, etc)? I have tried to search for this information, but didn't found any answering content. The only way I see is to create default Django views for the site and create separated API's for other requests. Can anybody tell me if I am right and need to do so, or there is some code that is solving my problem? -
'parsererror' error In MYSQL Axaj Django upload in chunks
I want to upload a file in chunks, and it works on SQLite but i wont work with MYSQL, and it uploads the file only till 10mb/11mb. Debug false/true gives me the same error JS: $.ajax({ xhr: function () { var xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', function (e) { if (e.lengthComputable) { if (self.file.size < self.max_length) { var percent = Math.round((e.loaded / e.total) * 100); } else { var percent = Math.round((uploadedChunk / self.file.size) * 100); } $('.progress-bar').css('width', percent + '%') $('.progress-bar').text(percent + '%') } }); return xhr; }, url: '/create-post', type: 'POST', dataType: 'json', cache: false, processData: false, contentType: false, data: formData, error: function (xhr) { alert(xhr.statusText); }, success: function (res) { if (nextChunk < self.file.size) { // upload file in chunks existingPath = res.existingPath self.upload_file(nextChunk, existingPath); } else { // upload complete $('.textbox').text(res.data); alert(res.data) } } }); }}; Views: https://imgur.com/a/FThSXAO All of this gives me parsererror Nothing else... -
Django - after sign-in template don't know that user is authenticated
Below code probably works (no errors present): views.pl class SignInView(View): def get(self, request): return render(request, "signin.html") def post(self, request): user = request.POST.get('username', '') pass = request.POST.get('password', '') user = authenticate(username=user, password=pass) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect('/') else: return HttpResponse("Bad user.") else: return HttpResponseRedirect('/') ....but in template: {% user.is_authenticated %} is not True. So I don't see any functionality for authenticated user. What is the problem? -
DjangoRestFramework, how to add optional field not coming from model to serializer
I have a model like this: class Camper(models.Model): location = models.PointField() name = models.CharField(max_length=255) and a viewset like this: class CamperViewSet(viewsets.ModelViewSet): ... def retrieve(self, request, *args, **kwargs): """Retrieve a Camper instance.""" show_weather = request.query_params.get('showWeather', False) instance = self.get_object() if show_weather: lat = instance.location.y lon = instance.location.x instance.weather = getWeatherFromLatLon(lat, lon) serializer = self.get_serializer(instance) return Response(serializer.data) So when I request /api/campers/8?showWeather=true I make another request in my view to get the weather from the current position. How do I add it to my serializer ? It's an optional field so I need to manage this and it's only used in /campers/id so it will not be used in list/create/put/etc My serializer looks like this: class CamperSerializer(serializers.ModelSerializer): camper_id = serializers.IntegerField(source='id') class Meta: model = Camper fields = ('camper_id', 'name', 'location') -
URL for Django filtering get requests
I'm making a filtering function for a database I'm working with. I'm wondering how I can access the request url. Here is the code for the models. from django.db import models class User(models.Model): username = models.CharField(max_length=20, null=True) account_type = models.CharField(max_length=30, null=True) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) email = models.EmailField(max_length=254, null=True) class Interest(models.Model): interest = models.CharField(max_length=200, null=True) listing_account = models.ForeignKey(ListingAccount, related_name='interests', on_delete=models.CASCADE, null=True) def __str__(self): return f"{self.interest}" Below is the filtering function in views.py. How can I find the URL path to this? class AccountFilterViewSet(generics.ListAPIView): queryset = ListingAccount.objects.all() serializer_class = ListingAccountSerializer filter_backends = [filters.SearchFilter] search_fields = ['first_name'] -
How do I properly set up a React app using Vite with my Django backend?
I've built my Django backend, then created a new app called Frontend. In the frontend folder I started a Vite app called "static" which includes my src folder and other files. When I create a build using npm run build a dist folder is created. I am able to run this project on localhost:5173 but when I want to run on Django (http://127.0.0.1:8000/) I get a blank white screen with errors. The errors are linked --> console errors here Has anyone gone through this process? -
Django Annotate Count
Could someone help me to understand why func Count calculates 1 for the actor that does not have any publicated scene?: actors = Actor.objects.filter(state=Actor.State.PUBLISHED)\ .annotate(scenes_cnt=Count('scenes', filter=Q(state=Scene.State.PUBLISHED))) I have one actor who has only one scene with state=Scene.State.PREVIEW but the code above calculates scenes_cnt=1 for this actor. I'm confused. Thanks in advance! I try to calculate publicated scenes for actors. Expect to get scenes_cnt=0 if actor does not have any scene with state=Actor.State.PUBLISHED -
Django: Object of type Decimal is not JSON serializable
I am trying to pass in some more data to the jwt token authentication, i have written a Serialize for this and passed in some other fields like full_name, image, pin etc now i am trying to pass in the wallet field which is a DecimalField in my Model, then i am getting this error. Object of type Decimal is not JSON serializable how do i fix this? token['wallet'] = user.profile.wallet Complete Serializer class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['username'] = user.username token['email'] = user.email token['full_name'] = user.profile.full_name token['bio'] = user.profile.bio token['country'] = user.profile.country token['image'] = user.profile.image.url token['address'] = user.profile.address token['phone'] = user.profile.phone token['website'] = user.profile.website token['pin'] = user.profile.pin token['verified'] = user.profile.verified token['wallet'] = user.profile.wallet # ... return token -
DjangoRestFramwork how to override ModelViewSet get method
I have a model like this : class AccountViewSet(viewsets.ModelViewSet): """ A simple ViewSet for viewing and editing accounts. """ queryset = Account.objects.all() serializer_class = AccountSerializer permission_classes = [IsAccountAdminOrReadOnly] How do I override the get method so when I hit /api/accounts/8 I can add some code before returning the 8th account ? -
Django Admin select_related issue
I'm trying to select_related for a bunch of assets in the Django admin. These assets are tied to a product, which in turn has a separate Company and Category model. I defined the string method like so in the Product class: def __str__(self): if self.company: return f"{self.category.name} | {self.company.name} | {self.name}" return f"{self.category.name} | {self.name}" However, when I check debug toolbar in the Django admin, I see that a bunch of extra queries are made because of this. products\models.py in __str__(53) return f"{self.category.name} | {self.company.name} | {self.name}" I have the following get_queryset method defined in the ModelAdmin: def get_queryset(self, request): qs = super().get_queryset(request).select_related( 'product', 'product__category', 'product__company') if request.user.is_superuser or request.user.is_staff: return qs return qs.filter(user=request.user) Is there a fix for this? Am I doing it wrong? -
How do you store an API key (token) client side without the user being able to see/access it?
I am working on a project that is handling sensitive customer information. Obviously security is a high priority. We have recently created an API that we want to use to be able to access the database to access / modify the data. What is the best way to store an API token client side? We currently are using the meta tag of the html template file to store the csrf token, but we do not want the API token to be visible. Here is the code for the csrf token and it works. //Capture and store the csrf Token useEffect(() => { const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content'); setToken(csrfToken); console.log({sessionToken, csrfToken}); }, []); Here is the tag for the index file we are using as a template <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="csrf-token" content="{{ csrf_token }}"> <meta name="api-token" content="{{ request.session.api_token }}"> </head> This also works, but then the API token is visible if someone inspects the page. We are using a Django / Python backend and a React front end. Would this involve the use of cookies? Or does it get more complicated than that? Any help would be greatly appreciated. Let me know if you need to see … -
Joining a table to itself in django ORM
I am creating a room booking system in Django and need a way to find overlaps in a reservation. I have come up with this raw query: select distinct y.reservation_base_id as id from app_reservation x inner join app_reservation y on x.reservation_base_id != y.reservation_base_id and x.id != y.id and x.start <= y.stop and y.start <= x.stop where x.reservation_base_id = %s; Here 'app_reservation' is an actual reservation that has the info about start and stop of the reservation. A reservation links to a reservation base. A reservation base has meta information about the reservation ie: title, description. This query works, however i would like to translate it to Django orm so i can easily modify it, and make it more flexible. I have looked in to Subquerying and Q-nodes, but i have not found something that join a model to itself. Any help would be greatly appreciated. -
Is it possible to add days to the date in the template?
I have today's date in my template, which is in a loop. I want to add a counter to the cycle so that in the template I don't have today's date, but date + 1 day, date + 2 days, and so on. {% for day_week_list in set_day_week %} <div class="card mb-2"> <div class="card-header"> {{ day_week_list }} {{ day_data|date:'d.m' }} </div> <div class="card-body"> -
How to transfer data from several models to one summary by the smallest size of one of the models?
I have three databases - table models (Django Models ). In which there is a different amount of data - a different number of rows of elements in the database table. One table has 100 rows - the other model table has 150 rows. I'm going to migrate the data from these models to another one - a general summary table model. Sequentially transferring data from each model. How can I do this - to transfer data to the summary table - only by the size (number of rows) of the smallest model table? -
Django manage command run scrapy spider
I have a parser on scrappy that works correctly and returns me a dictionary under the car key yield { 'car': car } it lies in the same directory with the Django project, which has a model in which I can put these dictionaries. my task is to write a django manage command in which I can catch this stream of data from the spider during its operation: class Command(BaseCommand): help = 'run all scrapper scripts' def handle(self, *args, **options): print("Hello its work") Can someone tell me how to get the data from the spider correctly here, I will be very grateful -
How can I launch Dash Pivottable inside Django?
I have made a Django project in which I have a many pages build in Django dash. Recently i have some requirement in which i have to use Dash Pivottable, but it's not working inside Django. Whereas, when I run it seprately (outside django project), then it is working fine. can anyone help me with this? This is the Dash graph code I used (simpleexample.py): from dash import dcc import dash_html_components as html from dash.dependencies import Input, Output, State from django_plotly_dash import DjangoDash import pandas as pd import requests import dash from dash import callback_context from dash import Dash #from dash.dash_table.Format import Group import os import os.path from datetime import datetime import dash import dash_pivottable from datetime import date app = DjangoDash('stock', external_stylesheets=external_stylesheets) app.layout = html.Div( dash_pivottable.PivotTable( data=[ ['Animal', 'Count', 'Location'], ['Zebra', 5, 'SF Zoo'], ['Tiger', 3, 'SF Zoo'], ['Zebra', 2, 'LA Zoo'], ['Tiger', 4, 'LA Zoo'], ], cols=["Animal"], rows=["Location"], vals=["Count"] ) ) if __name__ == '__main__': app.run_server(debug=True) I have also linked it with URL in urls.py: This is views.py This is my html template (stock.html): {% extends 'base.html' %} {% block body %} <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> {% load plotly_dash %} <div class="{% plotly_class name='stock' %}" style="height: 100%; width: 100%"> {% … -
Django admin fails to use unsigned URL for some static files in an AWS bucket
I am serving static files from an AWS bucket for my Django 4.0 powered site. My own apps function perfectly, but the Admin app tries to use unsigned URLs for some of the static files. More specifically, fonts.css and widgets.css under /admin/css/ are requested with unsigned URLs (resulting in 403 Forbidden) whereas all other CSS files are requested with presigned URLs and served just fine. As to images, only icon-addlink.svg is requested with unsigned URL (403 Forbidden) and all other images under /admin/img/are requested and served as expected. The image below (from the browsers Inspect feature) shows how Django tries to fetch some of the files with no querystring at all. What could be causing this? And how to get around it? I have checked that the problematic CSS and image files are properly copied to the static files folder with collectstatic command and they do exist in the AWS bucket. This issue has persisted upgrading to Django 4.0 from 3.X. -
Vs Code browser not working while using Django
I am trying to test the frontend of a Django project and want to use the VS code simple browser to open the local hosted site. In doing so it gives me no output(while it works perfectly on chrome) and the terminal show me this output enter image description here "GET /1?vscodeBrowserReqId=1676305382720 HTTP/1.1" 200 176 I haven't found anything related to this issue on the net and was wondering if it a Django problem or VS code -
Remove loading from postman during celery task
I have implemented celery on a django project and used redis as broker and django_celery_results as backend. Everything is working fine but I want to remove loading from postman. I want to print a message like task processing and when it is done, it shows result on reloading or sending the request again. Code celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "coutoEditor.settings") app = Celery("coutoEditor") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() tasks.py @shared_task() def speed_up_vid_task(input_path, speed_factor, start, end): ''' Method Params: input_path: The video file url or directory path file name speed_factor: The factor for the speed up process start: start of the video part that needs to be sped up (in secs) end: end of the video part that needs to be sped up (in secs) ''' start = convert_to_sec(start) end = convert_to_sec(end) filename = str(uuid.uuid4()) print(filename, "new") temporary_dir = BASE_DIR + '/' + editor_speedUp_temp_dir # editor_temp_dir = media/editor/speed_vid/temp/" output_dir = BASE_DIR + '/' + editor_speedUp_output_dir # editor_speedUp_output_dir = media/editor/speed_vid/ # Check for broken url r = requests.get(input_path, stream=True) if not r.status_code == 200: return Response({ 'message': "media file is corrupted", 'data': "broken url process could not be completed", 'status': False }, status=status.HTTP_400_BAD_REQUEST) if not os.path.exists(output_dir): os.mkdir(output_dir) if not os.path.exists(temporary_dir): os.mkdir(temporary_dir) … -
How to replace classic ImageUploadForm with dropzone.js?
I am totally new to Django, but currently I want to deploy my model. I am working on a Django project where users should be able to upload one image using Dropzone.js. Althoung I don't want to save these files anywhere, just have it for further processing with ML. I want to replace current ImageUploadForm to have dropzone for one image on website, Current views.py: import base64 import io import json import os from PIL import Image from django.shortcuts import render from .forms import ImageUploadForm import matplotlib.pyplot as plt from io import StringIO def index(request): image_uri = None graph = None quantity = 0 if request.method == 'POST': form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data.get('image') #some image processing else: form = ImageUploadForm() context = { 'form': form, 'image_uri': image_uri, 'quantity': quantity, 'graph': graph } return render(request, 'image_classification/index.html', context) Current index.html: <!DOCTYPE html> <html lang="en"> <style> body { width: 100% !important; margin: 0 auto; background-color:DarkGray !important; text-align: center !important; } </style> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script> </head> <body> <br>Uploaded images are not saved.</p> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> … -
How to merge multiple csv files?
I have several csv files that has same first row element in it. For example: csv-1.csv: Value,0 Currency,0 datetime,0 Receiver,0 Beneficiary,0 Flag,0 idx,0 csv-2.csv: Value,0 Currency,1 datetime,0 Receiver,0 Beneficiary,0 Flag,0 idx,0 And with these files (more than 2 files by the way) I want to merge them and create something like that: left csv-1 csv-2 Value 0 0 Currency 0 1 datetime 0 0 How can I create this funtion in python? -
Running a Pytorch model inside Django
I am trying to run a model (that i have saved already) inside my django project and i dont know how this is to be done . I simply searched web for this problem and came across this https://stefanbschneider.github.io/blog/pytorch-django Here, this guy imports a densenet and json but in my case i already have a running model and there are only 2 classes that is ant and bees Can anybody help me with this? what i did try is i cloned the project and replaced with the preloaded model with my model and skipped the json and added my classes but nothing seems to work -
Celery didn't run from pycharm's terminal
I am trying to run celery in pycharm's terminal by using command "celery --app SF_news worker -l INFO". Instead of normal startup i got " "celery" is not an internal or external command, executable program, or batch file." I tried execute that comand through windows cmd and get and it run properly but i really need to run it from pycharm's terminal because I need to send fully workable pycharm project to my teacher. init.py from project folder (near settings.py) celery.py from project folder (also near settings.py) -
customize models in Django RestFramework using AbstractBaseUser, BaseUserManager
i wanna customize models. so i used AbstractBaseUser, BaseUserManager i use **extra_field to add 'point' attribute. i enterd http://127.0.0.1:8000/account/signup/ and write my data but the errors occured enter image description here what's wrong with my code? i'm a beginner, plz help me # serializers.py from .models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): def create(self, validated_data): user = User.objects.create_user( email = validated_data['email'], nickname = validated_data['nickname'], name = validated_data['name'], password = validated_data['password'], point = validated_data['point'] ) return user class Meta: model = User fields = ['name', 'nickname', 'email', 'password'] # models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, nickname, name, password=None, **point): if not email: raise ValueError('must have user email') if not nickname: raise ValueError('must have user nickname') if not name: raise ValueError('must have user name') user = self.model( email = self.normalize_email(email), nickname = nickname, name = name, point = point ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, nickname, name, password=None): user = self.create_user( email, password = password, nickname = nickname, name = name ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): id = models.AutoField(primary_key=True) email = models.EmailField(default='', max_length=100, null=False, blank=False, unique=True) nickname = models.CharField(default='', max_length=100, null=False, blank=False, unique=False) name = … -
connect emulator with backend django
So I have a backend with django and I am using react native for frontend. I added a emulator in android studio. And when I start the backend like: python manage.py runserver I can run also the frontend with expo start. But now I want to fetch the data with react native. So I start the backend with: python manage.py runserver 192.168.1.68:19000 - settings file of django: ALLOWED_HOSTS = ['192.168.1.68', '127.0.0.1', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = [ "http://localhost:8081", "http://localhost:19006", "http://localhost:19002", "http://192.168.1.69:8000", "http://192.168.1.68:19000", ] CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", ] And react native service: export const fetchCategoryData = async () => { try { const response = await fetch("http://192.168.1.68:19000/animal/categories/main_groups/", { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", }, }); if (!response.ok) { throw new Error("Network response was not ok"); } return await response.json(); //setCategoryData(data); } catch (error) { console.error("There was a problem with the fetch operation:", error); throw error; } }; And when I then start the react native app with expo start and I do a r after a. I get this message: warn No apps connected. Sending "reload" to all …