Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to check if file has extension pdf
I have a method of uploading files. But now I want to check if the uploaded file is a pdf file. So I try it like this: def post(self, request): submitted_form = ProfileForm(request.POST, request.FILES) content = '' if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) file_extension = os.path.splitext(uploadfile[1]) if file_extension in {'pdf'}: print('Is pdf') uploadfile.save() with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r') as f: content = f.read() print(content) return render(request, "main/create_profile.html", { 'form': ProfileForm(), "content": content }) return render(request, "main/create_profile.html", { "form": submitted_form, }) But then I get this error: TypeError at / 'UploadFile' object is not subscriptable Question: what I have to change? Thank you -
Unable to store object in Django cache because the model uses a dynamic attribute
I am using the django-stdimage package to auto-resize my images. However, it seems that this particular plugin creates problems when I want to cache certain results. Models: class Page(models.Model): name = models.CharField(max_length=255) image = StdImageField(upload_to="images", variations={"thumbnail": (800, 600), delete_orphans=True) View: page = Page.objects.get(pk=1) cache.set("page", page, None) Result: AttributeError: 'StdImageFieldFile' object has no attribute 'thumbnail' From here: that is because the attribute is being set dynamically and is not properly serialised. So my question is: is there a way to record this object in the cache, even though this specific attribute is being set dynamically? Note that I don't need that specific field to be cached - if there is a way to cache the entire object WITHOUT the image field, I am happy with that too. -
How to make Django create an id but in different sequence
what I mean here is to make my id like that id : 2022001,2022002 not 1,2,3 or something like this random id hdvdfhbf124 and my second question is how to use auto-generated id the default one in my view.py if I didn't defined in models class FAQ(models.Model): questionTitle = models.CharField(max_length=50) questionAnswer = models.TextField(max_length= 300) class Meta: verbose_name_plural = "FAQ" because I can't refere to it in viwes.py like faq.id or something like that even if I import models not working -
I tried installing pip3 using the command prompt in windows but I got these error messages
Hi everyone I am new to Python programming, I tried installing pip3 on my windows computer, I typed (pip3 install pipenv) on the command prompt but I got these error messages (Error message 1: ”could not find a version that satisfies the requirement pipenv (from versions: none”) (Error message 2: no matching distribution found for pipenv) Thank you. -
How I upload image with schema to my dio flutter app
I had this endpoint in my django api django endpoint I need to upload a image with the post details to create one in my app ,i spend days without any sol please help me if you can :( -
Dropdown dynamic in django ajax
I am using django for dynamic dropdown. There are two dropdown when the first dropdown was click and there is a subcategory for it, the second dropdown will show options. I want to disable the second dropdown if there is no subcategory for it. How can I do that? $("#id_general-collision_type").change(function () { const url = $("#form_incidentgeneral").attr("data-acc-url"); // get the url of the `load_cities` view const collisionId = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: url, // set the url of the request (= /persons/ajax/load-cities/ ) data: { 'collision_type_id': collisionId // add the country id to the GET parameters }, success: function (data) { //console.log(data) // `data` is the return of the `load_cities` view function $("#id_general-collision_subcategory").html(data); // replace the contents of the city input with the data that came from the server let html_data = '<option value="">---------</option>'; data.forEach(function (collision_subcategory) { html_data += `<option value="${collision_subcategory.id}">${collision_subcategory.sub_category}</option>` }); console.log(html_data); $("#id_general-collision_subcategory").html(html_data); } }); }); -
My Django App only works on heroku when server is running locally
I have built an app using react and django. After deploying the app on heroku, when I open it the frontend works fine. However when i try to do any action that sends requests to the backend I get errors. The only time the requests work fine is when the django backend is running locally. I hsve been looking allover for solutions and have not been able to find any solutions. In my settings.py The heroku domain name is added to the allowed hosts ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'barkbnb-demo.herokuapp.com'] If anyone can point me in the right direction on where to begin looking for solving the issue that would be greatly appreciated. Thanks!