Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF SearchFilter Datetimefield Unsupported lookup 'gte'
I have a field timestamp which is a DateTime field when I'm filtering by this field in the shell it works fine with '__gte' or '__lte' $ python manage.py shell >>> from inventory.models import Order >>> Order.objects.filter(timestamp__date__gte=('2022-06-06')) >>> <QuerySet [<Order: ID: 22>, <Order_id: 27>, ....] but when I use SearchFilter it raises an error django.core.exceptions.FieldError: Unsupported lookup 'gte' for DateField or join on the field not permitted, perhaps you meant gte or gt or lte? models.py class Order(models.Model): timestamp = models.DateTimeField(auto_now_add=True) views.py from rest_framework.generics import ListAPIView from rest_framework import filters class Invoices(ListAPIView): serializer_class = InvoicesSerializer permission_classes = [IsAuthenticated, CustomModelPermissions] queryset = serializer_class.Meta.model.objects.all() filter_backends = [filters.SearchFilter] search_fields = ['timestamp__date__gte'] -
Django in python
**i want to making a site with django but i recive this error :excepted 'endblock', did you forget to register or load this tag? ** **Invalid block: ** -
How to return a string expression for order_by args in django queryset?
Let say i want to do this in the views of a Django project order_by_query = request.query_params.get("order_by", "") order_by_expression = compile_ob(order_by_query) qs = SomeModel.objects.all().order_by(order_by_expression) I expect the order_by_query to be a string like field1,-field2 so I will write a function like def compile_ob(expression: str) -> ??: my questions are: what should i write inside the compile_ob function? what should i return as type? Thank you -
why do i need to restart my docker container to see changes in django views.py file on windows
Why do I have to restart my docker container every time I make a change in my Django python files? I'm running a Django app via Docker and it seems any changes I make in my Views(and possibly elsewhere) are not reflected until I restart my container. For example, if I log an output to the terminal or make changes, then refresh, there's no change. If I restart my container and then refresh, I get the result I would expect. -
Should I use CSRF when setting JWT token using cookie in Django?
I am developing an API back end with Django, that uses JWT tokens for authentication. After reading numerous articles on JWT authentication and security, I concluded that it is best to store the JWT refresh token using an HttpOnly cookie. I also read that when using setting cookies with the Django Rest Framework, you should use CSRF protection. So... 1. Should I set a CSRF cookie when setting the JWT refresh token? I implemented my own methods for setting the refresh_token cookie upon successful requests to the LoginView and RefreshView. If I do need to set the CSRF cookie, should I also set it on those same views and then validate it when the refresh token is used, for example, when refreshing and logging out? Also... 2. How should I store the JWT access token? I have a React front end and, at the moment, I am storing the access tokens in localStorage. Would it be better if I were to store the token in a global state, for example using Redux? Forgive me if I don't know what I am talking about - my front-end knowledge is very limited. -
DRF Response isn't working with class based views in Django
I am converting my function-based views to class-based views. Following the official documentation, I was getting errors using the Response imported from rest_framework. When using HttpResponse it's working fine. The error I am getting with Response is: .accepted_renderer not set on Response This is my view: def get(self, request): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data) What could be the reason for this? -
Docker selenium not redirecting on another page in django test
I have some issue with docker selenium. For example, I have tried it on local selenium using operadriver, so redirecting to another page, after submit form, was working.I want to see this result also in django selenium test, but I've just get selenium.common.exceptions.TimeoutException: Message: in waiting when url will change. This is my test code import os import socket import shutil # from pyvirtualdisplay import Display from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options from django.test import LiveServerTestCase from django.conf import settings # Create your tests here. class LandFormTest(LiveServerTestCase): host = socket.gethostbyname(socket.gethostname()) def setUp(cls): selenium_url = 'http://selenium:4444/wd/hub' options = Options() options.add_argument('--no-sandbox') options.add_argument('--headless') options.add_argument("--disable-dev-shm-usage") options.add_argument("--ignore-certificate-errors") # options.add_argument("My user agent") options.add_argument(f"window-size=1920,1080") cls.driver = webdriver.Remote( command_executor=selenium_url, desired_capabilities=DesiredCapabilities.CHROME, options=options ) def test_form(self): try: driver = self.driver domain = self.live_server_url.split('//')[1].split(':')[0] if not settings.BASE_DIR.joinpath(f'templates/lands/{domain}').is_dir(): src = f'templates/lands/quantum.localhost' dest = f'templates/lands/{domain}' shutil.copytree(src, dest) driver.get(f'{self.live_server_url}/api/v1/test/?ai=2&gi=5') user_firstname = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.NAME, "firstname")) ) current_url = driver.current_url user_firstname = driver.find_element(By.NAME, 'firstname') user_lastname = driver.find_element(By.NAME, 'lastname') user_email = driver.find_element(By.NAME, 'email') user_phone = driver.find_element(By.NAME, 'phone') user_firstname.send_keys('test') user_lastname.send_keys('test') user_email.send_keys('test@gmail.com') user_phone.send_keys('+(846)411-36-00') user_phone.submit() WebDriverWait(driver, 10).until(EC.url_changes(current_url)) print(driver.current_url) print(driver.page_source) assert 'Hello World' in driver.page_source except … -
Permission based media server
I wanna build web based file/media(can be any type such as .mp4, .something) server using Django and JWT will handle the authorization. As normally, all media files are publicly accessible if we copy paste absolute path. How can setup in a way when only authorised user can access that specific file/media? -
How to Deploy Django Serving React App on AWS Elastic Beanstalk?
After quite a bit of debugging, I finally managed to successfully deploy the Django portion of my full-stack app on AWS Elastic Beanstalk. Here is the .config file in .ebextensions that I'm using: option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "waifu_database.settings" PYTHONPATH: "/opt/python/current/app/waifu_database:$PYTHONPATH" aws:elasticbeanstalk:container:python: WSGIPath: waifu_database.wsgi:application However, I still have the React portion to deploy. I know that it would probably be easier to separate the two, but is there a way I can install all the packages using npm and deploy it with the Django backend? I've already tried this but it just gave me a "Failed to deploy application" error. Here is my file directory: waifu_database |- .ebextensions |- .elasticbeanstalk |- api |- frontend |- node_modules/ |- src/ |- static/ |- templates/ |- package.json |- waifu_database |- asgi.py |- settings.py |- urls.py |- wsgi.py |- manage.py |- requirements.txt Here is my package.json file: { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack --mode production --watch", "build": "webpack --mode production" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.19.3", "@babel/preset-env": "^7.19.3", "@babel/preset-react": "^7.18.6", "babel-loader": "^8.2.5", "react": "^18.2.0", "react-dom": "^18.2.0", "webpack": "^5.74.0", "webpack-cli": "^4.10.0" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.18.6", … -
What is the proper way to set third party urls in settings?
I am calling some third party apis from my django view. What will be the best configuration for setting the third party api credentials ? With this current config i am only setting server on the env. What would be the best approach get all the key and url from env only or below like this ? settings.py server = os.getenv("server", "staging") if server == "production" third_party_api_key = "some key" url = "some_url" elif server == "staging": third_party_api_key = "some key" url = "some_url" else: third_party_api_key = "some key" url = "some_url" -
social network developer's image compression
I am basically developing a social network to share images using Django and one of my issues is how to compress images all for the same size of 470x470 -
Django: Loop / iterate nested list with multiple sublevels
Here are my snippets: models.py class Item(models.Model): name = models.CharField('Name', max_length=50, unique=True) toplevel = models.BooleanField('Top level item', default=False) order = models.IntegerField('Order number', blank=True, null=True) #only if top level is true, determines the top level order class Hierarchy(models.Model): mainitem = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='mainitem') subitem = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='subitem') order = models.IntegerField('Order number', default=0) #determines the order of the subitems under the mainitem views.py def items_view(request, *args, **kwargs): items = Item.objects.all() toplevelitems = Item.objects.filter(toplevel=True) sublevelitems = Item.objects.filter(toplevel=False) context = { 'items':items, 'toplevelitems':toplevelitems, 'sublevelitems':sublevelitems, } return render(request, "itemlist.html", context) itemlist.html {% if items %} <ul class="list-group list-group-flush"> {% for toplevelitem in toplevelitems %} <li class="list-group-item">{{ toplevelitem.order }} {{ toplevelitem.name }}</li> {% for sublevelitem in sublevelitems %} <ul class="list-group list-group-flush"> <li class="list-group-item">{{ sublevelitem.name }}</li> </ul> {% endfor %} {% endfor %} </ul> {% else %} <p>No created items</p> {% endif %} So what I am trying to built with these is a hierarchy of items that will be itereted for the client in a nested list. What I cannot figure out is how to loop through all the levels of the hierarchy and place them under the right upper level. Here is what I am going for: Item 1 (top level item) Item 1.1 … -
dango app, images don't show up after heroku restart even my images are on cloudinary
I am uploading my images to cloudinary. This is a test project. After 24 hours The images don't show on django-website. Host is heroku. #settings .py changes STATIC_ROOT = BASE_DIR / 'staticfiles' CLOUDINARY_STORAGE = { 'CLOUD_NAME': 'here is my cl name', 'API_KEY': 'here is my api key', 'API_SECRET': 'here is my api secret', } DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' # models.py changes image = models.ImageField(upload_to='test_project_cloudinary/', null=True) #views.py if request.method == "POST": form = ImageForm(request.POST, request.FILES) if form.is_valid(): print("form validated") form.save() return redirect("home") else: print("form not validating") -
Conditionally bulk_create or bulk_update model instance fields based on the conditional equality of two foreign key related fields in Django
I'm trying to bulk_create or bulk_update instances of a model Matchup, where two of its fields are dependent on the equality or lack thereof of two of its related fields' reverse relationships. The Matchup has both a home_team and away_team, both of which are ForeignKey fields. There's are also is_divisional and is_conference fields to denote whether the matchup is between teams in the same division or conference. class Matchup(models.Model): home_team = models.ForeignKey( "teams.Team", on_delete=models.CASCADE, related_name="home_matchups", ) away_team = models.ForeignKey( "teams.Team", on_delete=models.CASCADE, related_name="away_matchups", ) is_divisional = models.BooleanField(default=False) is_conference = models.BooleanField(default=False) The Team model also has two ForeignKey fields, conference and division. class Team(models.Model): conference = models.ForeignKey( "leagues.Conference", on_delete=models.CASCADE, related_name="teams", ) division = models.ForeignKey( "leagues.Division", on_delete=models.CASCADE, related_name="teams", ) So the goal here is to check whether the Matchup.home_team and Matchup.away_team belong to the same conference or division. If so, is_conference/is_divisional respectively should be True. Here's what I initially had. It works, but leads to hundreds of duplicate queries. I perform this bulk_update after all the objects are created in bulk. for matchup in matchup_objs: if matchup.home_team.division == matchup.away_team.division: matchup.is_divisional = True if matchup.home_team.conference == matchup.away_team.conference: matchup.is_conference = True Matchup.objects.bulk_update(matchup_objs, ["is_divisional", "is_conference"]) In an attempt to reduce the duplicate queries, I tried using … -
Calculate the total amount of the cart in django rest framework
I'm new in django,I need calculate cart summa and I have these models: class Customer(Base): name = models.CharField(max_length=100) phone_number = models.CharField(max_length=100, blank=True, null=True) comments = models.CharField(max_length=255, blank=True, null=True) class Cart(Base): user = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="cart") cart_number = models.CharField(max_length=500, default=increment_cart_number, null=True, blank=True) total_summa = models.FloatField() is_saved = models.BooleanField(default=False) class Item(Base): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product') product_price = models.FloatField() quantity = models.IntegerField(default=1) I used generics view, Can i calculate cart summa like this Bread 3x6000 = 18000 Milk 2x500 = 10000 Total_Summa = 28000 Could you help me please? -
Not able to longin to django admin panel after creating custom super user
Hey guys I tried my best but I am not able to log in to the django admin panel with my custom made user model. I did do all the things I can, I also did the authentication for the email and the rest but I still am not able to log into the django admin panel it keeps saying this "Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive." I tried and checked my password probably a hundred times now but still I won't let me log in. Can someone please help me with this, it would be the biggest help ever. I have been stuck here for like a month now I have pasted all the code that I did below:- models.py:- from django.db import models import uuid from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.utils.translation import gettext_lazy as _ class CustomAccountManager(BaseUserManager): def create_user(self, first_name, last_name, phone_number, email, password, **other_fields): if not email: raise ValueError(_('You must provie an email address')) if not first_name: raise ValueError(_('You must provide a first name')) if not last_name: raise ValueError(_('You must provide a last name')) email = self.normalize_email(email) user = … -
installing postgres in aws ubuntu
**i have an app i want to deploy to aws.i have cloned the app from my github to the server.i have also downloaded all the dependancies and slo installed postgres but it keeps giving me errors. kindly help out! below is the error code!!** i am stuck at this now. i have trying to run the server on aws ubuntu but to no avail. i have tried to change the password,donr all the research i could online but i cant come up with the answer. please some should help me out. i am stuck at this now. i have trying to run the server on aws ubuntu but to no avail. i have tried to change the password,donr all the research i could online but i cant come up with the answer. please some should help me out. i am stuck at this now. i have trying to run the server on aws ubuntu but to no avail. i have tried to change the password,donr all the research i could online but i cant come up with the answer. please some should help me out. i am stuck at this now. i have trying to run the server on aws … -
Unable to login using Django
This is my login view def login_request(request): if request.method == 'POST': username = request.POST.get['username'] password = request.POST.get['password'] user = authenticate(username = username, password = password) if user is not None: form = login(request, user) messages.success(request, f' welcome {username} !!') return redirect('index') else: messages.info(request, f'Unable to Login now') form = AuthenticationForm() context = {'form':form} return render(request, "BizzyCardApp/log-in.html", context) and this is the log-in.html file {% extends "BizzyCardApp/base.html" %} {% block content %} {% load crispy_forms_tags %} <br> <br> <br> <br> <br> <div class="container center oswald" id="grad" style="border-radius: 10%; width: 300px;"> <br> <form> <table class="table table-borderless table-responsive container"> <tbody> <tr> <div class="mb-3 mt-3"> <form method="POST"> {% csrf_token %} {% for field in form %} <div> <p>{{ field.label }}: <br> {{ field }}</p> {% for error in field.errors %} <small style="color: red">{{ error }}</small> {% endfor %} </div> {% endfor %} </form> </div> </tr> <tr> <div class="d-flex justify-content-center"> <button type="submit" class="btn btn-light center text-center">Submit</button> </div> </tr> </tbody> </table> </form> <div class="text-center"> <a href="/sign-up/" class="link-dark"> Don't have an account? Sign Up </a> </div> </div> {% endblock %} Once I hit the Submit button, it's supposed to redirect me to the index page but all that happens is that the GET request is done but … -
MultiValueDictKeyError en un formulario
Me sale este error "MultiValueDictKeyError in Django" en views.py esta esto from django.shortcuts import render from django.http import HttpResponse Create your views here. def busqueda_productos(request): return render(request, "busqueda_productos.html") def buscar(request): mensaje="Articulo buscado: %r" %request.GET["prd"] return HttpResponse(mensaje) en Busqueda_productos.html <title>Busqueda de Productos</title> </head> <body> <form action="/buscar/" method="GET"> <input type="text" name ="prd"> <input type="submit" value= "Buscar"> </form> </body> en la pagina de Django http://127.0.0.1:8000/ me sale esto. MultiValueDictKeyError at /Buscar/ 'prd' Request Method: GET Request URL: http://127.0.0.1:8000/Buscar/ Django Version: 4.1.1 Exception Type: MultiValueDictKeyError Exception Value: 'prd' Exception Location: C:\Users\ASUS\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\datastructures.py, line 86, in getitem Raised during: gestionPedidos.views.buscar Python Executable: C:\Users\ASUS\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.7 Python Path: ['C:\Users\ASUS\Desktop\ProyectosDjango\TiendaOnline', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python310', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python310\lib\site-packages'] Agradezco su colaboracion -
why my index page does not load in django?
I started a django project and the index template doesn't work it just load django's main page in fact I have opened the tutorial and copied word for word and it still doesn't work views.py def index(request): return render(request, 'students/index.html') settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'students', ] my main urls.py file from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('students.urls')), ] urls.py file for my app called students from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] my index.html file(I tried putting the body outside the head tag but it also didn't work so i copied what was done in the tutorial <!DOCTYPE html> <html lang="en"> <head> <title>Student management </title> <body> <h1>Hello world!</h1> </body> </head> </html> -
Get method not changing to post in django forms
and I have studied Django for 3 months but still I couldn't find the solution down below. I am building resume maker online website. But when I run function in views.py, I get method 'GET' every time, but I expected it should be POST, I think there is a problem with frontend. I have an awesome app called Nicepage which generates beautiful html codes for me without coding. I downloaded its source code and used it as a frontend for my website. I don't know why but, still I couldn't solve the problem. Can you please help me to solve this? here is my frontend: <section class="u-clearfix u-section-1" id="sec-800b"> <div class="u-clearfix u-sheet u-valign-top u-sheet-1"> <div class="u-container-style u-expanded-width u-group u-image u-image-default u-image-1" data-image-width="360" data-image-height="360"> <div class="u-container-layout u-container-layout-1"> <h2 class="u-text u-text-default u-text-1">Let's start with&nbsp;<br>personal information </h2> <div class="u-expanded-width-sm u-expanded-width-xs u-form u-form-1"> <form enctype="multipart/form-data" method="POST" class="u-clearfix u-form-spacing-10 u-form-vertical u-inner-form" style="padding: 10px;"> {% csrf_token %} <div class="u-form-group u-form-name"> {{ form.as_p }} <!-- <label for="name-86ce" class="u-label">Fullname</label>--> <!-- <input type="text" placeholder="Enter your fullname carefully..." id="name-86ce" name="name"--> <!-- class="u-border-1 u-border-grey-30 u-input u-input-rectangle u-white" required>--> </div> <div class="u-form-email u-form-group"> <label for="email-86ce" class="u-label">Email</label> <input type="email" placeholder="Enter a valid email address" id="email-86ce" name="email" class="u-border-1 u-border-grey-30 u-input u-input-rectangle u-white" required=""> </div> … -
Accessing a query of a Foreign Key
I have the following model: class Exercise(models.Model): name = models.CharField(max_length = 30, blank=True, null=True) class Breakdown(models.Model): exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, related_name='breakdowns',blank=True, null=True) My question In the views how can I forloop the breakdowns inside exercise. Here is what I have tried: class page_details(DetailView): model = Workout template_name = 'app/page.html' context_object_name = 'workout' def get_context_data(self, **kwargs): exercises = Exercise.objects.filter(workout_id=self.object) for e in exercises.Breakdown: print(e) I keep getting AttributeError: 'QuerySet' object has no attribute 'Breakdown' My question how do I get access to this data. -
Insert selected data to one table from another table with condition in django and python
I have 2 tables in my phpMyAdmin database, which is connected to Django project. I need to check all the rows in table 1 with the check column which has values 'yes' or 'no'. if the check is no, then selected data from that row has to copy to table 2 and other values are hardcoded with if condition. Below is the situation, Table 1 has data of dealers, with columns of name, item, date, quantity, place, check. Table 2 has to be data with item, date, quantity, entry_no, reason. i need to check all data in table 1 for the 'check' value is 'yes' or 'no'. if 'no', only item, date, quantity should be copy to table 2 as new data with entry_no and reason values are specific to item. after the data entered to table 2 as new record, then check value in table 1 has to change to 'yes'. every time i have to check all data in table 1. there are 2 option to insert data, one is save data to table 2 from the code, second is, i have developed a script to fill the html form automatically with the help of selenium library with … -
Is there any way to bookmark a Django "current" documentation page, without version numbers?
Let's take an example. I search for Django STATICFILES_DIR: https://www.google.com/search?q=django+STATICFILES_DIRS Pretty quickly I get exactly what I want: https://docs.djangoproject.com/en/4.1/ref/contrib/staticfiles/ which has a STATICFILES_DIR configuration entry. But, notice from the url, this is for Django 4.1. And it says so on the page too. But maybe there are a current version? Let's look. There isn't. Contrast with Python, which points to a very generic, 3 version. Not to Python 3.10 or 3.11. https://docs.python.org/3/tutorial/datastructures.html#dictionaries Or postgres (looking for create table): https://www.postgresql.org/docs/14/sql-createtable.html OK, yes, I have a version 14, but... I can click on that current and that will NOT pin me to a particular version. https://www.postgresql.org/docs/current/sql-createtable.html Often searching gets you to ancient postgressql versions like 9.2, but you can always find a current link. Am I looking in the wrong places for a permanent link for Django docs? Yes, there is dev link on the Django versions, but that's living a bit dangerously. -
Setting up group permissions in Django Rest Framework
I've a problem with Django Rest Framework. I wish to set a group-specific permissions with the following code, which I set in admin.py: from django.contrib import admin from django.contrib.auth.models import Group, Permission # Creating staff group and handling group permissions staff_group, created = Group.objects.get_or_create(name='Staff') def staff_has_crud_permissions(obj): add_obj = Permission.objects.get(codename=f'add_{obj}') change_obj = Permission.objects.get(codename=f'change_{obj}') delete_obj = Permission.objects.get(codename=f'delete_{obj}') view_obj = Permission.objects.get(codename=f'view_{obj}') staff_group.permissions.add(add_obj) staff_group.permissions.add(change_obj) staff_group.permissions.add(delete_obj) staff_group.permissions.add(view_obj) print(staff_group.permissions) staff_has_crud_permissions('bar') Yet, when the line print(staff_group.permissionsruns, I get auth.Permission.None. Why doesn't it succeed?