Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display rating star in Django with fontawesome v5.13
I am writing a website with django and in this website, I periodically ask users to rate platform. I store the ratings with models.FloatField() in my database. Now my problem is how to display the stars. If I have something like 3.5 as the rating value, then in my html page, I should have 3 full stars and the fourth star should be half while the fifth (also the last) should be empty star How can I achieve this with fontawesome v5.13 -
Im trying to create a user model with a foreign key but im getting an error
I am making a notes app. When I try to create a foreign key to link the user and its notes, im getting an error. I am very new to foreign keys, I looked at the Django docs, this is how they created a foreign key. here's the code : from django.db import models class User(models.Model): username = models.CharField(max_length=50) email = models.EmailField(max_length=50) class Note(models.Model): body = models.TextField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.body[0:50] here's the error : django.db.utils.IntegrityError: NOT NULL constraint failed: new__api_note.author_id -
django database query OR condition
I am implementing a friend system similar to facebook where one can send friendship requests and accept requests and then see their friends. On the page where one sees the friend requests I am trying to filter out the users who have accepted the friend request and are friend already now. In the code below, 'u' is the current logged in user. Friendship table hold two fields , both foreign keys, please see below: try: already_friends = Friendship.objects.get(Q(from_friend=u) | Q(to_friend=u)) for x in already_friends.iterator(): my_requests = FriendRequest.objects.filter(Q(receiver=request.user) & ~Q(sender=x)) except ObjectDoesNotExist: class FriendRequest(models.Model): sender = models.ForeignKey(User, related_name='the_sender',on_delete=models.CASCADE) receiver = models.ForeignKey(User, related_name='the_receiver', on_delete=models.CASCADE) def __str__(self): return "request sent" class Meta: unique_together = (('sender', 'receiver'),) class Friendship(models.Model): from_friend = models.ForeignKey(User, related_name="from_friend", on_delete=models.CASCADE) to_friend= models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return "Friend request accepted" class Meta: unique_together = (('from_friend', 'to_friend'),) When I use the query I wrote at the top using Q (complex queries) and then use iterator, I get the following error: 'Friendship' object has no attribute 'iterator' How can I achieve what I intend to do using django models/queries? -
Problem uploading images to S3 Bucket from Django App
My problem is that images stored in media folder are not transferring to S3 Bucket. I tested with other file from request and the file did transfer, so I assume settings.py must be OK. From views.py -> This works: if request.method == 'POST': imageFile = request.FILES['images'] upload = Upload(file=imageFile) upload.save() image_url = upload.file.url print(image_url) This does not work: for i in os.listdir(folder): f = os.path.join(conf_settings.MEDIA_ROOT,company, i) upload = Upload(file=f) upload.save() No error but it just does not work. This also does not work: for i in os.listdir(folder): with open(os.path.join(folder, i)) as f: upload = Upload(file=f) upload.save() >The error I am getting is: > >Exception Value: >'_io.TextIOWrapper' object has no attribute '_committed' > >at upload.save() This is my storage_backend.py from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' default_acl = 'public-read' file_overwrite = True This is my model.py class Upload(models.Model): uploaded_at = models.DateTimeField(auto_now_add=True) file = models.FileField() I am uploading a .ZIP file with images. Unzipping it and saving them to media folder, then I want to upload from media folder to S3 Bucket. This operation fails. The file in request.FILES is the Zip file, which I am using to test that all settings.py for AWS should be … -
Value matching query does not exist
I am a beginner in Django. I recently came across a problem: When I am trying to fetch objects, it is saying DoesNotExist: Value matching query does not exist. I searched the web but still I got no clue as to why this is happening. My models.py from django.db import models class Value(models.Model): eq_input = models.CharField(max_length=20, default='x**2 + y**2') color = models.CharField(max_length=20, default='Magma') My forms.py from django import forms from .models import Value class ViewForm(forms.ModelForm): Equation = forms.CharField(max_length=20, label='Equation') Color = forms.CharField(max_length=20,label='Color') class Meta: model = Value fields = { 'Equation', 'Color' } My views.py from django.shortcuts import render from django.http import HttpResponse from .models import Value from .forms import ViewForm def home_view(request): if request.method == "POST": form = ViewForm(request.POST) if form.is_valid(): form.save() else: form = ViewForm() context = { 'form': form } return render(request, "home.html", context) My home.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>3D Graph Plotter</title> </head> <body> <center><h1>This is a 3D plotter</h1></center> <center> <form action="." method="POST">{% csrf_token %} {{ form.as_p }} <input type="submit" name="Save" /> </form> </center> </body> </html> and my urls.py from django.contrib import admin from django.urls import path, include from equation.views import eq, home_view urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name='hv') ] Is there … -
Django admin panel new user registration is not added
OperationalError at /admin/auth/user/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://localhost:8000/admin/auth/user/add/ Django Version: 2.0.3 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 303 Python Executable: C:\Anaconda3\python.exe Python Version: 3.8.8 Python Path: ['C:\Users\sinan\Desktop\blog', 'C:\Anaconda3\python38.zip', 'C:\Anaconda3\DLLs', 'C:\Anaconda3\lib', 'C:\Anaconda3', 'C:\Anaconda3\lib\site-packages', 'C:\Anaconda3\lib\site-packages\locket-0.2.1-py3.8.egg', 'C:\Anaconda3\lib\site-packages\win32', 'C:\Anaconda3\lib\site-packages\win32\lib', 'C:\Anaconda3\lib\site-packages\Pythonwin'] Server time: Cmt, 30 Eki 2021 10:22:25 +0300 -
Django and react login with google authentication
I was trying set up google authentication with react frontend and django rest framework backend. I set up both the frontend and backend using this two part tutorial, PART1 & PART2. When I try to login with google in the frontend I get POST http://127.0.0.1:8000/google-login/ 400 (Bad Request) I think it's because my google api needs an access token and an authorization code to be passed. After debugging the react js, I noticed the response I get from google doesn't have an authorization code. I suspect because responseType is permission(by default), Source:React login props , instead of code. I was wondering how would you change the response type in react? (I'm not even sure if this alone is the issue) Here's my backend code In my views.py file class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter callback_url = "http://localhost:3000" client_class = OAuth2Client in my urls.py path('google-login/', GoogleLogin.as_view(), name='google-login'), for my front end /Components/login.js const googleLogin = async (accesstoken,code) => { console.log(accesstoken) let res = await cacaDB.post( `google-login/`, { access_token: accesstoken, code: code } ); console.log(res); return await res.status; }; const responseGoogle = (response) => { console.log(response.code); googleLogin(response.accessToken, response.code); } return( <div className="App"> <h1>LOGIN WITH GOOGLE</h1> <GoogleLogin clientId="client_id" buttonText="LOGIN WITH GOOGLE" onSuccess={responseGoogle} onFailure={responseGoogle} /> … -
Google PageSpeed Insights not working on pythonanywhere
I had just started a simple application which displays Hello World! This is the index page of games. over here. Also, I wanted to test that website for improvements using PageSpeed Insights using this. When I use PageSpeed Insights, I get this message: Lighthouse returned error: ERRORED_DOCUMENT_REQUEST. Lighthouse was unable to reliably load the page you requested. Make sure you are testing the correct URL and that the server is properly responding to all requests. (Status code: 401) I am using www.pythonanywhere.com using Django for hosting my website. How can I fix that? -
Django-Celery process on Heroku with AWS S3 Access Forbidden
This is a pretty specific issue that I'm running into, but I'm extremely stuck. I've deployed my Django app to Heroku. This app allows the user to upload a pdf which is then stored in AWS S3 bucket storage. The app then redirects the user to a loading page while the pdf is processed in a background process. When the processing is completed, the user is given the option to view and accept changes to their database entries. I'm using celery on a Heroku-redis server for the asynchronous processing. HOWEVER it seems that the Redis server doesn't have the right permissions to read and write to my AWS bucket. Importantly, the main server DOES. I know this because when the user uploads his file, the result is saved in the requisite folder inside the S3 bucket, AND because I very clearly have access to my static files on the site. There's clearly some failure in the credentials handoff from the server to the broker, but I have no idea how to fix this. Code and details below. Here's my celery.py file: from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django … -
Django Doesn't Pass ForeignKey Models to JSON
I've a Comment models that have 2 attributes referenced to Forum models and Profile Models as a foreign key the I try to serialize it to JSON. But when I try with serializers, the JSON object of my foreignkey attrs return Null. I don't know why since it seems normal when I debug the code and print the object before I save to my form. MODELS: class Comment(models.Model): message = models.TextField() forum_creator_username = models.CharField(max_length=200, null=True, blank=True) forum_creator = models.ForeignKey(Forum, on_delete=models.CASCADE, blank = True, null = True) comment_creator = models.ForeignKey(Profile, on_delete=models.CASCADE, blank = True, null = True) created_at = models.CharField(max_length=50,null=True, blank=True) comment_creator_username = models.CharField(max_length=200, null=True, blank=True) creator_image = models.ImageField( blank=True, null=True, default="profiles/default-user_pfzkxt", ) Views: def index(request, id): forums = Forum.objects.all().values() form = CommentForm(request.POST) response={} if request.method == "POST": if (form.is_valid): print(form.is_valid) print(form.is_valid()) add_comment = form.save(commit=False) add_comment.forum = Forum.objects.get(pk=id) add_comment.comment_creator = Profile.objects.get(user = request.user.id) add_comment.forum_creator = Forum.objects.get(pk=id) add_comment.forum_creator_username = add_comment.forum_creator.creator.username add_comment.comment_creator_username = add_comment.comment_creator.username add_comment.creator_image = add_comment.comment_creator.profile_image add_comment.created_at = datetime.now().strftime("%A, %d %B %Y, %I:%M %p") add_comment.save() return HttpResponseRedirect(request.path_info) response['form'] = form Comment.forum_creator = Forum.objects.get(pk = id) test = Comment.forum_creator = Forum.objects.get(pk = id) print("TES FORUM:",test.id) Comment.comment_creator = Profile.objects.get(user = request.user.id) a = Comment.comment_creator print("comment_reator adalah:",a) print("TES", Comment.forum_creator, "comment:",Comment.comment_creator) response['forum'] = Comment.forum_creator return render(request, … -
Return a distinct order based on In Query
I have a queryset where I want to return the respective order based on my values inside the in filter. Below are my given syntax and models Models class Transaction(models.Model): user = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True) comments = models.TextField(null=True, blank=True) class Profile(models.Model): user = models.OneToOneField(User, null=True, blank=True, related_name='profile', on_delete=models.SET_NULL) first_name = models.CharField(max_length=125, null=True, blank=True) middle_name = models.CharField(max_length=125, null=True, blank=True) last_name = models.CharField(max_length=125, null=True, blank=True) nickname = models.CharField(max_length=100, null=True, blank=True) balance = models.DecimalField(default=0.0, max_digits=7, decimal_places=2) is_online = models.BooleanField(default=False) Syntax from trading.models import Transaction ids = [4, 1, 3, 2] tx = Transaction.objects.filter(user_id__in=ids).order_by('user').distinct('user') Where I expect that the returned order of Transaction object is based on the id order of the list of ids -
Requests are sent 3 times to Django
I am trying to send request using axios and React to django API, The request false twice, then true. So I always have trouble checking :( The tokens are JWT and are configured httponly through the server. I just learned Django and I'm a rookie. So the first if statement is always executed. useEffect(() => { if (!isAuthenticated && !userInfo) { history.push('/login') } else { if (!user || !user.username) { dispatch(getUserDetails('profile')) } else { setUsername(user.username) setEmail(user.email) } } }, [dispatch, history, userInfo, user, isAuthenticated]) | Order | Result | -------- | ---------------------------------------- | | First | {user: {…}} | | Second | {isAuthenticated: false, userInfo: null} | | third | {user: {…}} | | Fourth | {isAuthenticated: false, userInfo: null} | | Fifth | {user: {…}} | | Sixth | {isAuthenticated: true, userInfo: null} | | Seventh | {user: {…}, loading: true} | -
Django signal to delete file on aws s3 not working
I have written the pre_save signal in Django to auto-delete the user's old profile_pic if the user updates its profile_pic. This is my code. @receiver(pre_save, sender=User) def delete_file_on_update(sender, instance, **kwargs): """ Delete the user's old profile pic file when user update the profile and return the status True or False i.e where old pic is deleted or not. """ # If instance is saving for first time in database, don't delete profile_pic file. try: old_file = sender.objects.get(pk=instance.pk).profile_pic except sender.DoesNotExist: return False # If user has not updated profile pic, don't delete profile_pic file. new_file = instance.profile_pic if old_file == new_file: return False try: old_file.delete(save=False) return True except Exception: return False This was working fine when storage was local but when I used the AWS s3 storage, It is not deleting the old profile_pic anymore. Also on debugging this signal is get called on each pre_save of user and old_file.delete(save=false) is also executing but the file is not deleting on AWS s3. -
How to convert pdf files into JPEG files and save them in ImageField of Django
I want to convert pdf files into jpeg files and save them as ImageField in Django. In my case, I already have pdf files in MyModel and some of them will be converted into jpeg files and saved as jpeg files as ImageField in AnotherModel. pdf_path = MyModel.object.pdffile.path If I use "convert_from_path" provided by pdf2image, I think it is necessary to prepare the path for a jpeg file in advance. However, I don't know how to prepare it before creating each record of ImageField. -
ProgrammingError at /admin/aws_app/imageframe
django.db.utils.ProgrammingError: column "frame_captype_id" of relation "aws_app_imageframes" does not exist LINE 1: ...ws_app_imageframes" ("time_stamp", "image_frame", "frame_cap... I recently truncated this table ( image frames which is having foreign-key relation with frame_cap, but now it is not allowing me to push any data , and throwing the above error , what's the issue ?, currently both the tables are truncated class ImageFrames(models.Model): time_stamp = models.DateTimeField(auto_now_add=True) image_frame = models.FileField(upload_to = 'camera_frames',null=True,blank=True,max_length=500) flagged_as = models.ManyToManyField(FLag) frame_captype = models.ForeignKey(FrameCapType,on_delete=models.CASCADE,null=True,blank=True) -
Behave Django Testing - Behave testing with selenium only uses dev database instead of test
I am sorry I am very new to the world of Django Behave testing, and cannot find any resources online regarding the question I have: How to properly set up behave django so that it can use selenium to test with a test database loaded with test fixtures? I am trying to write an integration test that will test a simple permission feature, where the user can log in and the response will contain an auth_token that subsequent pages will use to either block or allow depending on the user. The test user is loaded with a test-users.json fixture, but when running behave tests, I get 400 (incorrect credentials) on my dev server and I cannot log in using selenium. I can only log in with a user that is currently present in my dev database. This makes me think that either my fixtures aren't loaded, or that selenium isn't using the test database that was setup by behave? Here are parts of my givens.py, evironment.py setup and my settings.py # tests/acceptance/environment.py from rest_framework.test import APIClient from seleniumrequests import Chrome import os os.environ['DJANGO_SETTINGS_MODULE'] = 'core.settings.settings' def django_ready(context): context.test.client = APIClient() context.browser = Chrome() context.browser.implicitly_wait(1) context.server_url = 'http://localhost:8000' context.fixtures = [ … -
How to avoid having django template display before VueJS render
I have a Django template that I'm trying to render with VueJs using CDN. The problem is when the page is loaded, i see the raw code of django with the delimiters before it get rendered with VueJS. It takes less that a sec. I have an API call (using Fetch) that retrieve some data before displaying them and I put that in mounted() function. The delay is almost 0.6sec and we can see Django render before vuejs render the page. Then I change mounted() to beforeMount(). I now see the django render from time to time but it's much better because often, vue render comes first. My question is, is there a better way to solve this. I'm using CDN and I'm didn't want to get intot server side rendering for this project. Thanks -
Are these HTML files properly configured for user.is_authenticated method in Django
I intend to have extremely sensitive information within my Django website. This being said, I need to restrict access to user accounts only. Is this a proper configuration for securing my HTML files and sensitive data to the rest of the world? Django file structure: I also have my normal HTML files at the templates level. login.html: <html lang="en"> <head> <meta charset="UTF-8"> <title>Login In</title> </head> <body> <form method="POST" style="text-align:center;font-family:verdana;" > {% csrf_token %} {{ form }} <button type="submit">Login</button> </form> </body> </html> base.html <!DOCTYPE html> <html lang="en"> <head> {% load static %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <title>Search</title> <link rel="stylesheet" type="text/css" href="{% static '/css/main.css' %}"> </head> <body> {% if user.is_authenticated %} {% block content %} {% endblock %} {% else %} <h1 style="text-align:center;">Login <a href="/login" style=";text-decoration:underline;">Here</a></h1> {% endif %} </body> </html> example.html <!DOCTYPE html> {% load static %} {% extends "base.html" %} {% if user.is_authenticated %} {% block content %} <html> <head> <title>Example</title> </head> <h1>Example!</h1> <p class='text'>Hello World</p> </html> {% endblock %} {% else %} <p>Login <a href="/login">Here</a></p> {% endif %} -
How to create a subtraction in the inventory when a order is made? [Django] [Python] [E-commerce website]
I’m a python/django begginer. I decided to build a e-commerce website using django for an academic project. I’ve been able to develop enough of the project and build understanding of the subject, but right now I’m having issues finding a way to subtracts the number of items listed in the inventory whenever a order is made. That’s the code for the models, evey product has it's own stock quantity call inventory: class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() description = models.TextField(default='', null=True, blank=True) digital = models.BooleanField(default=False,null=True, blank=True) image = models.ImageField(null=True, blank=True) inventory = models.IntegerField(default=0) def __str__(self): return self.name def has_inventory(self): return self.inventory > 0 This is the code I made to subtract base on quantity of the item ordered, but I can’t make it work, it won’t subtract the number of items from the inventory on the product stock. class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.product) + " x " + str(self.quantity) def inventory(self): product.inventory = self.inventory product.inventory -= int(self.quantity) return inventory What could I do to make it work? -
CORS blocks connection between Flutter and Django API
I want to connect Djnago API with flutter app, but I have lots of problem. I'll show flutter and django code both. Settings.py """ Django settings for crawler project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-)4%#q5&d3^5=0!bauz62wxmc9csk*_c09k!jl2g1a-0rxsa--j' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crawling_data', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'crawler.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'crawler.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': … -
How to paginate a pandas dataframe on django based on columns
I have a cvs with more than 40000 columns and I need to separate it on parts so the user only can see some columns by pages and reduce the load time, I think on pagination but the references only works for rows, How can I use it to separate the columns? It's that posible? I'ts a csv converted on a Dataframe with pandas -
JS file does not work when trying to use it by '<script src='
I've been practicing JavaScript, and I am trying to create a simple notification system using Django. However, when I try to serve my JS file, it does not work. I mean, it does not show up 404 error. Here's my code (client): console.log("called") emitData = { "user_id": current_user_id } console.log("send notification request") socket.emit("requestExistingNotifications", emitData) socket.on("newNotification", (data)=>{ // ... }) socket.on("notificationHistoryFromServer", (data)=>{ // still writing }) Here's my html file: {% load static %} <script src="{% static 'js/notification.js' %}"></script> When I tried to put my code in script tag directly, it works just fine, so I know that my server-side code is fine. However, I want to put the JS code in another file. -
can someone guide me on the use case for serving media files via uploadcare vs amazon S3 vs other solutions?
I am trying to make a django application (with the Rest framework) and I was just researching and came across different ways to serve media files. what is the recommended approach for a project/app that lets you upload pictures so that other users can download them? I came across CDN such as uploadcare, cloudinary and then ofcourse amazon S3 as well. Is there a difference in using these services like uploadcare vs S3 in terms of speed or scaling? thanks in advance, -
Django Webmanifest
I'm building a PWA in Django. The serviceworker is located in pwa->static->pwa->sw.js Everthing gets loaded/cached and the serviceworker is running. If in manifest.json "start_url": "/" or "start_url": "/pwa" is set, i get this serviceworker not found error, from the manifest, so it's not installable, but if I set it to "start_url": "." i can install my App but then I get: Directory indexes are not allowed here. Request Method: GET Request URL: http://127.0.0.1:8000/static/pwa/ At app startup. How can i overwrite or redirect this request to http://127.0.0.1:8000/pwa/ ? -
python3 ModuleNotFoundError: No module named 'celery'
I import celery from python but it through error from celery import Celery line 1, in <module> from celery import Celery