Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the alternative of Amazon's Simple Storage System (S3)
I'm trying to deploy my django projct into heroku so I need to server my static files in another service so I don't want to server it in Amazon's Simple Storage System (S3) can anybody help me ? -
Updating database object in Django
I am making a Django project where the user uploads their picture, and it gets saved in the database. And if the user uploads the same picture multiple times on the same day, it uploads the existing field, rather than creating a new one. My error is that while it updates the existing field, it also creates a new one. How do I fix this? Here is my code: if img == None: messages.error(request, "Please submit an image.") return render(request, 'page.html') elif Image.objects.filter(user=user, date=today).exists(): image_file_like = ContentFile(base64.b64decode(img)) a=str(uuid.uuid4()) image = Image(user=user) image.img.save(f"{a}.png", image_file_like, save=True) path = f"media/{a}.png" toUpdate = Image.objects.filter(user=user, date=today) toUpdate.update(img = path) print('works2') return render(request, 'page.html') else: image_file_like = ContentFile(base64.b64decode(img)) a=str(uuid.uuid4()) image = Image(user=user) print('works3') image.img.save(f"{a}.png", image_file_like, save=True) image.save() return render(request, 'page.html') Thanks -
Django ORM: I want to convert raw query to Django ORM [NEED HELP]
Depending on User's type, I want to join related table. if user type is 'pi' prefetch_related('content_object__stores) else prefetch_related('content_object__store_set), but combine both query together. Any idea converting the raw query to Django ORM?? SELECT * FROM user AS u LEFT JOIN provisioning_company AS c ON u.company_id = c.id AND u.type != 'pi' LEFT JOIN provisioning_picker AS p ON u.company_id = p.id AND u.type = 'pi'; class User(AbstractUser): content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, default=None, null=True) related_id = models.IntegerField(default=None, null=True) content_object = GenericForeignKey('content_type', 'company_id') type = models.CharField(max_length=2, choices=user_type_choices) class Picker(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=128) email = models.EmailField(max_length=256) mobile = models.CharField(max_length=16, unique=True) stores = models.ManyToManyField( Store, verbose_name='stores', blank=True, help_text="stores", related_name="picker_set", related_query_name="picker_set", db_table="provisioning_picker_store", ) class Store(CommonModel): companies = models.ManyToManyField( Company, verbose_name='companies', blank=True, help_text="companies", related_name="store_set", related_query_name="store_set", db_table="provisioning_company_store_relation", ) tried something like User.objects.prefetch_related( Prefetch("content_object__store_set", queryset=User.objects.exclude("pi")) ).prefetch_related(Prefetch("stores", queryset=User.objects.filter("pi"))) but it does not work like the raw query. Any help would be appreciated. -
Not able to upload image in CRUD using serializers
I am doing CRUD using serializers as I am tasked. In this context I am new to images and studied it,I have made files called 'media' to store images but I am getting an error like this I have been trying to solve this error but didnt have much success below is the insert function def insert(request): data = {} if request.method == "POST": print('POST',id) data['categories'] = request.POST.get('categories') data['sub_categories'] = request.POST.get('sub_categories') data['color'] = request.POST.get('color') data['size'] = request.POST.get('size') data['title'] = request.POST.get('title') data['price'] = request.POST.get('price') data['sku_number'] = request.POST.get('sku_number') data['product_details'] = request.POST.get('product_details') data['quantity'] = request.POST.get('quantity') data['image'] = request.FILES['images'] form = POLLSerializer(data=data) print(form) if form.is_valid(): print('form after valid:',form) print("error of form:",form.errors) form.save() messages.success(request, "Record Updated Successfully...!:)") return redirect("polls:show") else: print('form not valid') print(form.errors) if request.method == "GET": print('POST',id) category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict, many=True) sub_category_dict = SUBCategories.objects.filter(isactive=True) sub_category = SUBCategoriesSerializer(sub_category_dict,many=True) color_dict = Colors.objects.filter(isactive=True) color = ColorsSerializer(color_dict,many=True) size_dict = Size.objects.filter(isactive=True) size = SizeSerializer(size_dict,many=True) hm = {"context": category.data,"sub_context":sub_category.data,"color_context":color.data,"size_context":size.data} return render(request, "polls/product_insert.html", hm) models class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) def filepath(request,filename): old_filename = filename … -
Cpanel python detecting wrong version
Im trying to deploy django application on cpanel But as I setup python3.7.12 but it detecting python2.6.6 Im tried please help me -
Pass values from django views to django forms
I am trying to pass a value from views.py to forms.py in django views.py: def pods(request): clusterName = request.GET.get('data') ----> this is the value I want to pass to forms return render(request,'pods.html',{"nodeForm":forms.getPodsOnNodes()}) forms.py: class getPodsOnNodes(forms.Form): nodeName = forms.ChoiceField(label='Node Name',choices=functions.choiceMaker(functions.nodesList(**this is where I want to use clusterName from views**))) Would you please let me know how I can do this? -
Sending data with post method via Fetch API to Django backend doesn't work
I'm writing a shopping cart in Django which uses sessions. I want to send the ID of the selected item to the server via Javascript's fetch API. When I use HTML's native form with method=post, my server app works correctly but when I use fetch API I get errors. Here is my button code: <button class="btn btn-primary addtocart" id=2 onClick="GFG_click(this.id)">Add to Cart</button> Here is the JavaScript: <script> function GFG_click(clicked) { fetch('cart/add/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id : '1' }), }) .then((res) => JSON.stringify(res.json())) .then((data) => { // Do some stuff ... }) .catch((err) => console.log(err)); } </script> Here is the Django's URL pattern: path('cart/add/', views.cart_add, name='cart_add') Here is the cart_add view: def cart_add(request): if request.method == 'POST': cart = Cart(request) id = request.POST.get('id') product = Product.objects.get(id=id) cart.add(product=product) return JsonResponse("success") And this is the error I get: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 DoesNotExist at /playground/cart/add/ Product matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:8000/playground/cart/add/ Django Version: 4.0.5 Exception Type: DoesNotExist Exception Value: Product matching query does not exist. In this line: product = Product.objects.get(id=id) -
How can I make a request to profile API? User was redirected to the profile page after login and i want to make a get request to the user profile API
I want to make a get request to get details of the user from profile API that I have created. The profile API gives details of their user(username, email) But when I make the request in react, I keep getting errors. I am highly confused. The code for Login page and profile page are shown below. As well as error from the console of the browser. import { useRef, useState, useEffect, useContext } from 'react'; import AuthContext from "./context/AuthProvider"; import axios from './api/axios'; import { useHistory } from "react-router-dom"; const LOGIN_URL = '/login/'; const Login = () => { const { setAuth } = useContext(AuthContext); const userRef = useRef(); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); useEffect(() => { userRef.current.focus(); }, []) const history = useHistory() const handleSubmit = async (e) => { e.preventDefault(); const response = await axios.post(LOGIN_URL, JSON.stringify({ email, password }), { headers: { 'Content-Type': 'application/json' }, withCredentials: true } ); if (response.status === 200) { history.push("/profile"); console.log('Successfully Login'); } console.log(response.status) console.log(response.data) //console.log(JSON.stringify(response?.data)); //console.log(JSON.stringify(response)); const accessToken = response.data.accessToken; const roles = response?.data?.roles; setAuth({ email, password, roles, accessToken }); setEmail(''); setPassword(''); } return ( <> <section> <h1>Sign In</h1> <form onSubmit={handleSubmit}> <label htmlFor="email">Email</label> <input type="text" id="email" ref={userRef} … -
Pip found no matching distribution found for distributions that exist AWS Elastic Beanstalk
I am running a Django app on AWS elastic beanstalk, and to install dependencies on the virtual environment, I just need to add them to the requirements.txt file. However, I recently added the flair ai package to my project with all its dependencies, and now Elastic beanstalk is unable to download/find multiple packages. I keep getting errors like these, where there are no versions, or only earlier versions of the package. I am not sure what the issue here could be? I am now unable to deploy my app and the environment is degraded because of these issues. ERROR: Could not find a version that satisfies the requirement pywin32==304 (from versions: none) ERROR: No matching distribution found for pywin32==304 WARNING: You are using pip version 22.0.4; however, version 22.1.2 is available. -
Trying to complete the DJANGO intro tutorial as seen on the w3schools website - https://www.w3schools.com/django/django_intro.php
Following along the tutorial as seen on https://www.w3schools.com/django/django_intro.php Basically I have: Created virtual environment Started Django project - myworld Created a members app and edited the views exactly as mentioned Added to urls.py in the project and members directory Still get this error that empty path didn't match any of these A screenshot of the error message I am seeing instead of Hello world! and welcome to Django A screenshot of my urls.py file Is this an issue with me being in a wrong path, or do I need to specify more in path('blog', ) section? -
RSA encryption private key among a group of people
I am currently trying to implement the RSA encryption algorithm with my Django application. So the way I want it to be Is that the users enter some data through like quiz or surveys and then that data is encrypted using a public key of the users. Then I have a group of admins who only can see what the user enters in their own portal (not the Django admin), like maybe a group of admins at a school or something . How can I implement this ? Because a thing that struck me is that I can't decrypt the data with multiple private keys since 1 user's data can be shown to multiple admins for analysis purposes. So I want that a user's data should be decrypted and shown in the admin portal of multiple admins. -
How to overwrite form.valid with a funcion base view
So, i just want to tell my view, to use the request.user as the author of the company im creating. I can find how to do that with class base views, overwriting the form.valid, but i cant find how to do that with a funcion base view enter image description here -
Convert raw query to django ORM (prefetch_related, left join with mutiple conditions)
I want to convert the raw query to Django ORM, but I got no idea. SELECT * FROM user AS u LEFT JOIN animal AS a ON u.related_id = a.id AND u.type != 'animal' LEFT JOIN human AS h ON u.related_id = h.id AND u.type = 'animal'; tried something like User.objects.prefetch_related(Prefetch('name1', queryset=User.objects.exclude('animal'))).prefetch_related(Prefetch('name2', queryset=User.objects.finter('animal')) but it does not work like the raw query. Any help would be appreciated. -
How to fix CORS error while using Models.Pointfield function of GeoDjango Framework?
User is required to click on the location in map using Pointfield. This is my code for models class Marker(models.Model): """A marker with name and location.""" Market_Place_Name = models.CharField(max_length=255) GPS_Location = models.PointField() Http_Location = models.CharField(max_length=255) def __str__(self): """Return string representation.""" return self.name I get error message saying the following and map doesn't load either as shown below: I've tried adding these following codes on setting.py of geodjango project, but nothing seems to work INSTALLED_APPS = ['corsheaders'] MIDDLEWARE = ["corsheaders.middleware.CorsMiddleware",'django.middleware.security.SecurityMiddleware'] CORS_ALLOWED_ORIGINS = [ "http://localhost:8000", "http://127.0.0.1:8000"] -
How to get value from HTML select form inside the views?
1.In HTML template i created a select form passing into it player names from Player Model. 2.I want to delete the player selected in this form. 3.Inside my views, i am trying to get the selected value as a string but i can't. for me it would be Player.objects.get(name="what is selected inside the form"). Can you please help? What should i do in order to get this value inside my views? <div> <form method="POST" action = "" enctype="multipart/form-data"> {% csrf_token %} <select name="to_delete" > {% for pl in players %} <option value="1">{{pl.name}}</option> {% endfor %} </select> <input type="submit" value="Delete"/> </form> </div> def deletePlayer(request,pk,sk): room = Room.objects.get(number=pk) player = Player.objects.get(number=sk) players = Player.objects.filter(room=room) if request.method == "POST": result = reguest.get('1') to_delete = Player.objects.get(name=result) to_delete.delete() context = {'room': room, 'players':players,'player':player} return render(request, 'base/delete_player.html', context) -
@classmethod or @staticmethod In python(Django)
I have used spring framework for developing server application, and now I start to learn Django. I got one question when I use Django. "Is there no issue about memory when using @classmethod or @staticmethod? in python" In spring(java), there is issue about abusing static and spring also support controlling object(IoC container). But when I use Django, there is no decorator or setting about object. Just I use @classmethod, and use it with class name (ex. AccountService.join() ) -
Do I need to buy an SSL certificate for my new domain?
I was hosting my app on Heroku and it said it was "secure" in the domain bar with no problem. I have the following setting on: SECURE_SSL_REDIRECT = True Now I added my own domain and reconfigured my app to point to the domain. Did I lose some sort of SSL by doing this? Sometimes now I get an error when I try to load the webpage that says ERR_SSL_UNRECOGNIZED_NAME_ALERT -
Django funcion views, creating a company with user associated
So, i have this problem when im trying to create my "company", when i didnt have user authentication the view worked just fine. Now i've added django allauth, and this screen appears to me: enter image description here So i will leave here my model and my view to create the company Im just a begginner so sry for my bad explanation enter image description here enter image description here -
Is my payment processing secure (TLS) on Django/Heroku using Stripe
I'm using Stripe payment elements on my Django app hosted on Heroku. I have the following setting on: SECURE_SSL_REDIRECT = True What else do I need to do to make my website meet TLS? Do I need a TLS certificate from a site like Let’s Encrypt? -
Django Form Classes sometimes they don't appear?
This is the form below. Sometimes my form-control doesn't appear? I've used JQuery hasclass to check and add it if it fails. I just want to know why as my other forms are the same and work fine? Can't seem to figure out what the issue is. If anyone knows please let me know :) class holder_password_update_form(PasswordChangeForm): def __init__(self, user, *args, **kwargs): self.user = user super().__init__(user, *args, **kwargs) self.base_fields['old_password'].widget.attrs['class'] = 'form-control' self.base_fields['new_password1'].widget.attrs['class'] = 'form-control' self.base_fields['new_password1'].help_text = mark_safe('<p class="text-start" style="padding-left: 10px"> Your password can\'t be too similar to your other personal information, can\'t be a commonly used password, must contain at least 8 characters, 1 uppercase letter, 1 lowercase letter, 1 digit(s), 1 special character. </p>') self.base_fields['new_password2'].widget.attrs['class'] = 'form-control' self.base_fields['new_password2'].help_text = mark_safe('<p class="text-start" style="padding-left: 10px">Enter the same password as before, for verification.</p>') def save(self, commit=True): password = self.cleaned_data["new_password1"] self.user.set_password(password) if commit: self.user.save() return self.user -
Can you make a Django form dropdown box accept a model as its choices?
I have a real estate site where I am trying to be able to upload multiple photos to one 'property' without going through the django admin panel (so I can multi select photos.) Current view for custom built form I am able to choose multiple files, upload them to my 'uploads' folder and able to see them in the admin panel for databases. The issue is that the property name from the form I built doesn't connect the Property object to the Property Photos objects. Its just a null value. When I click on a Property Photo object only then does it assign the Property object to it. Property Photo objects BEFORE Property Photo object Once I click on it and push save Property Photo object After How do I get to be able to select (using a dropdown) a Property object from all my Property objects as a list and assign those photos uploaded to that Property object? Below are my: html form, models.py, views.py, and forms.py photo_upload.html <body> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="fs-1">Photo Upload</div> {{ image_form }} <button>Upload</button> </form> </body> models.py class Property(models.Model): class Meta: verbose_name_plural = 'Properties' address = models.CharField(max_length=150) slug = models.SlugField(unique=True, … -
Is it possible to have an input from a form in a html template be added to the url in a django project?
In the sidebar of my homepage, there is a search box where a user is meant to be able to type in the name of an entry and be taken to that page. So for example, if they type in css they would be taken to http://127.0.0.1:8000/wiki/css where the value inputted is appended to the url. (The home page url is http://127.0.0.1:8000/wiki/.) When I use the get method in the form it ends up searching up /wiki/?q=css instead of just having /css at the end of the url. However, when I use the post method in my form the url remains at http://127.0.0.1:8000/wiki/ with no additional url at the end. How do I append an input to the end of a url? HTML: <h2>Wiki</h2> <form action="/wiki/" method="post"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> urls.py: from tokenize import Name from unicodedata import name from django.urls import path from django.http import HttpResponse from . import views urlpatterns = [ path("", views.index, name="index"), path('hello/', views.hello, name='hello'), path('<str:name>', views.entry, name='entry'), path('new/', views.new, name='new'), path('random/', views.randomEntry, name='random') ] views.py: from django.shortcuts import render from django.http import HttpResponse from django import forms import random from . import util def index(request): return render(request, … -
how to check if a date is expired or not django?
I have a model that contains informations about trips and one field is a DateTimeField() like this: class Voyage(models.Model): voyid = models.CharField(max_length=20, primary_key= True) depart = models.CharField(max_length=30) destination = models.CharField(max_length=30) datedep = models.DateTimeField() #the datedep is the time and date of the trip departure And the result is a list of trips so i want to output only the trips that are not expired: (datedep > now), how do i do that? -
django.urls.exceptions.NoReverseMatch: Reverse for 'xyz' not found. 'xyz' is not a valid view function or pattern name
i have problem bcz i get: Powershell: django.urls.exceptions.NoReverseMatch: Reverse for 'register' not found. 'register' is not a valid view function or pattern name. Project Schematic: https://ibb.co/g39qB9k Error during template rendering: https://ibb.co/k5k82V4 html: <a class="navbar-brand" href="{% url 'turbineweb:home_page' %}"> Turbine Power Web</a> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ms-auto"> {% if user.is_authenticated %} <li class="nav-item"><a class="nav-link" href="{% url 'accounts:logout' %}">Logout</a></li> <li class="nav-item"><a class="nav-link" href="{% url 'accounts:password_change' %}">Change Password</a></li> {% else %} <li class="nav-item"><a class="nav-link" href="{% url 'accounts:login' %}">Login</a></li> **<li class="nav-item"><a class="nav-link" href="{% url 'accounts:register' %}">Register</a></li>** {% endif %} <li class="nav-item"><a class="nav-link" href="">Turbine Models</a></li> <li class="nav-item"><a class="nav-link" href="">Author</a></li> {% if user.is_company %} <li class="nav-item"><a class="nav-link" href="">My Models</a></li> {% endif %} <li class="nav-item"> Hello, {{ user.username|default:'Guest' }} </li> </ul> </div> views: def home_page(request): return render(request, 'turbineweb/home_page.html') project urls: urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls', namespace='accounts')), path('', include('turbineweb.urls', namespace='turbineweb')), ] accounts urls: app_name = 'accounts' urlpatterns = [ path('login/', CustomLoginView.as_view(redirect_authenticated_user=True, template_name='accounts/login.html', authentication_form=LoginForm), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name='logout'), path('registration/', RegisterView.as_view(), name='users-registration'), path('password-change/', ChangePasswordView.as_view(), name='password_change'), path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] turbineweb urls: app_name = 'turbineweb' urlpatterns = [ path('home/', views.home_page, name='home_page'), ] -
Django, return a value to the HTML file from a view when using a form
My index.html file contains three forms, each connect to my views.py file and perform some function, everything is working fine but I am not understanding how to get a returned value back to my html page to display it. index.html: <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Index</title> </head> <body> <form action="{% url 'start_or_end_fast' %}" method="POST"> {% csrf_token %} <button type="submit" name='start_fast' value='start_fast'>Add Fast</button> </form> <form action="{% url 'start_or_end_fast' %}" method="POST"> {% csrf_token %} <button type="submit" name='end_fast' value='end_fast'>End Fast</button> </form> <form action="{% url 'start_or_end_fast' %}" method="POST"> {% csrf_token %} <button type="submit" name='duration' value='duration'>Fast Duration</button> </form> <!-- DISPLAY FAST DURATION ON THE PAGE --> {% if duration %} <p>Fasting for {{duration}} </p> {% endif %} </body> </html> The third form is a button, when I press it the duration prints in the terminal. views.py code to do that: #If pressing Fast Duration button, show the duration difference between the current fast start_date_time and the current time elif request.method == 'POST' and 'duration' in request.POST: time_difference() return render(request,'startandstoptimes/index.html') else: return render(request,'startandstoptimes/index.html') def time_difference(): #Get the current date and time current_time = datetime.now().strftime(("%Y-%m-%d %H:%M:%S")) time_now = datetime.strptime(current_time, "%Y-%m-%d %H:%M:%S") #find the current fast that has not finished yet …