Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding product with size to shopping bag django
I am developing my hobby ecommerce store website. The products in the store can have different sizes. Wehen we go to product details page I am able to render the product's available sizes. I have also built shopping bag page and can add products to the shopping cart. Product detail page shows product color, product size and quantity. I am rendering the size in a button at the moment. When I click on Add to Bag button I want a function that checks if any size is selected, if not then raise an error message for user but if any size is selected by user then this should be sent to the view so it can be handled accordingly. Here are my models, product detail template and product detail view: if anyone please guide me.... class Product(models.Model): """ Product model to allow creating product records and linking with category """ product_uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True) product_name = models.CharField(max_length=255) sub_category = models.ForeignKey( 'SubCategory', on_delete=models.CASCADE, related_name='products') product_description = models.TextField() has_sizes = models.BooleanField(default=False, null=True, blank=True) is_featured = models.BooleanField(default=False) product_sku = models.CharField(max_length=255, null=True, blank=True) product_price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.product_name class Meta: verbose_name = 'Product' verbose_name_plural = 'Products' ``` ``` class … -
How to write an async for database function?
I have a function that is written as so: @database_sync_to_async def list_values(self): return list( Model.objects.all().select_related("related").order('date')[::-1] ) I'm trying to rewrite to work with an async for loop async for value in self.list_values. However my current attempt async def list_values(self): return ( Model.objects.all().select_related("related").order('date')[::-1] ) Gives me an error 'async for' requires an object with __aiter__ method, got coroutine. I've also played around with adding await and yield, etc. but to no end. Any suggestions and an explanation of how I'm thinking about this wrong? -
eBay HTML CSS description template image gallery loop
Hi I'm currently playing around with updating our stores eBay HTML description template, we use the inkfrog software for listing so I've got to play around with the HTML setup. I'm trying to get the images for each product to be displayed like this in the description: The original HTML for this gallery looks like this: <div class="col-sm-12 col-md-6 col-lg-6 mb-5"> <div class="gallery"> <input type="radio" id="image1" class="image-selector" name="image-selector" checked="checked"> <img src="https://poseidongames.co.uk/wp-content/uploads/2017/11/sub-nautica-below-zero-1.jpg" class="img-fluid main-image animated fadeIn"> <input type="radio" id="image2" class="image-selector" name="image-selector"> <img src="https://poseidongames.co.uk/wp-content/uploads/2017/11/sub-nautica-below-zero-2.jpg" class="img-fluid main-image animated fadeIn"> <input type="radio" id="image3" class="image-selector" name="image-selector"> <img src="https://poseidongames.co.uk/wp-content/uploads/2017/11/sub-nautica-below-zero-3.jpg" class="img-fluid main-image animated fadeIn"> </div> <div class="thumbs"> <ul class="text-center"> <li><label for="image1"><img src="https://poseidongames.co.uk/wp-content/uploads/2017/11/sub-nautica-below-zero-1.jpg" class="thumb"></label></li> <li><label for="image2"><img src="https://poseidongames.co.uk/wp-content/uploads/2017/11/sub-nautica-below-zero-2.jpg" class="thumb"></label></li> <li><label for="image3"><img src="https://poseidongames.co.uk/wp-content/uploads/2017/11/sub-nautica-below-zero-3.jpg" class="thumb"></label></li> </ul> </div> </div> I've managed to get the thumbnail images to cycle through the images array and display: using this code: `<div class="thumbs"> <ul class="text-center"> {% for image in images%} <li><a href="{{ image.url }}"><img src="{{ image | image_size:'600px' }}" class="thumb"></a></li> {% endfor %} </ul> </div>` ``` What I'm struggling with is the large section... I've tried this thinking that it would cycle through the images array and add incremental labels to each image, but this doesn't seem to be working... It's been a while since I've … -
AWS App runner build fail: pkg-config not found when building wheel for pycairo in django project
I am trying to deploy a django project to AWS App runner and it uses xhtml2pdf which needs pycairo in its dependency. It works locally I believe because I am running ubuntu, which is labeled this as "pkg-config" but since AWS App runner is running a different distro where it recognizes "pkgconfig". I tried to change the export path but that did not seem to work. The error is listed below Image of output from AWS app runner I also tried to run the following commonds yum install pkgconfig but it was already installed. I also tried yum install cairo but it also already installed. It seems like the packages are there before running requirements.txt but it cant find it. -
Django allauth Microsoft Graph SSO
I am having trouble using the Microsoft Graph provider using Django allauth, I have configured it according to the documentation and after research online, the app has been registered and has admin consent granted in the Microsoft Entra admin.I used the Django admin panel to register the social application with the following settings: When I click the Sign in with Microsoft button, it redirects me to the consent page: after I click Continue, I am redirected to the sign in page to select the account to sign in, I sign in with an account from my organization and continue, the login does not succeed at this point and I am directed to the following page: I have tried multiple answers to this available online, mainly this question which is already posted here: django-allauth Azure Ad Configurations, but no luck and I am still failing to sign in. The redirect URL is set to : "http://localhost:8000/accounts/microsoft/login/callback/" and the app is set for Single tenant. API permissions: settings.py SOCIALACCOUNT_PROVIDERS = { 'microsoft': { 'TENANT': 'organizations', } } -
How to do a Messaging on Django python?
How to code a Messaging user to user in django python? We already did all the other views. Do you have any idea to create it without ‘forms.py’ and without JavaScript? And also we can not host a server on our own wifi. The server is hosted at the university. CAN you help us? -
Why does text_decoration:none isn't working?
i started work with CSS and HTML about 3-4 days ago. I try to make all code myself but now i need help. idk what to do. my text-decoration in main.css didn't work. I tried to change place of tags and to add this tag an several times but it didn't work too. but it didn't work. !important didn't work. I dunno what to do else. Tysm in advance! CSS code: body { background: #2c2c2c; } aside { float: left; background: #181818; width: 20%; padding: 2.5%; height: 100vh; color: #fff; border-right: 5px solid #4d4d4d; } aside img { width: 80px; float: left; } aside .logo { font-size: 40px; margin-left: 10px; font-weight: bold; position: relative; top: -5px; } aside h3 { margin-top: 50px; font-size: 28px; } aside ul {list-style: none} aside ul li { color: #fff; display: block; margin-top: 20px; transition: transform .6s ease; } li {text-decoration: none !important;} aside ul li:hover, aside ul a:hover { color: #eb5959; transform: scale(1.05); text-decoration: none; } HTML code: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}{%endblock%}</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="{% static 'main/css/main.css' %}"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css"> </head> <body> <aside> <img src="{% … -
Django: count values with annotation from another table without ForeignKey
I have three models/tables: class Stats: obj_type = models.TextField(blank=True, db_index=True) obj_id = models.PositiveIntegerField(blank=True, null=True, db_index=True) views_count = models.IntegerField(blank=True, null=True, default=0) class Movie: title = models.TextField(blank=True) producer = models.TextField(blank=True) class Cartoon: title = models.TextField(blank=True) producer = models.TextField(blank=True) In total, I have around 1,500,000 objects in my Stats table. The obj_type field in it holds strings such as 'Movie' or 'Cartoon' related to the respective tables. What I want to do is to get a list of all the Movie producers from the Movie table with the total count of views pertaining to every producer, e.g.: Walt Disney: 17055 # total views of all Movies with 'Walt Disney' as producer counted based on Statistics table Netflix: 15046 etc. What is the most effective way to achieve this without having a ForeignKey? I.e. something like this if we had the views count inside the same table: views = Movie.objects.values('producer').annotate(count=Sum('views_count')) -
How to force exit Django app when database connection fails
I am trying to have django asgi app exit when the database connection fails. Normal behaviour seems to be that the app and its endpoint happily keep running and are accessible even though the database connection has failed. I want the app to exit. I tried this in asgi.py but the app still persists when I deliberately have the database connection to fail. Any ideas? import os import django import threading from django.core.asgi import get_asgi_application from django.db import connections from django.db.utils import OperationalError os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SAFD.settings") django.setup() # Function to check database connection in a separate thread def check_database_connection(): try: connections['default'].cursor() except OperationalError: exit(1) # raise Exception("Database connection failed") # Synchronously check the database connection db_check_thread = threading.Thread(target=check_database_connection) db_check_thread.start() db_check_thread.join() # Create the ASGI application instance django_asgi_app = get_asgi_application() async def application(scope, receive, send): await django_asgi_app(scope, receive, send) -
Django : Update object in database using UpdateAPIView
I have a Django project with the the following models.py from django.db import models class RawUser(models.Model): id = models.CharField(max_length=256, primary_key=True) field1 = models.IntegerField(null=True) field2 = models.CharField() And the following view.py. The goal of the UserUpdate view is to create or update a user when I get a PUT request. from django.http import JsonResponse from rest_framework import generics from profiling.api.serializers import RawUserSerializer from profiling.models import RawUser class UserUpdate(generics.UpdateAPIView): queryset = RawUser.objects.all() serializer_class = RawUserSerializer def put(self, request, *args, **kwargs): instance = self.get_object() raw_user_serializer: RawUserSerializer = self.get_serializer(instance, data=request.data, partial=False) raw_user_serializer.is_valid(raise_exception=True) # More logic here raw_user = raw_user_serializer.update(instance, raw_user_serializer.validated_data) self.perform_update(raw_user_serializer) return JsonResponse({'user_id':raw_user.id}, status = 201) class UserDetail(generics.RetrieveAPIView): queryset = RawUser.objects.all() serializer_class = RawUserSerializer The issue here is that when I try to PUT a user that exists already, I get the following error on raw_user_serializer.is_valid(raise_exception=True): Bad Request: /api/profiling/users/1/ { "id": [ "This field is required." ] } And when I try to PUT a user that doesn't exist already, I get the following error on instance = self.get_object(): Not Found: /api/profiling/users/25/ { "detail": "Not found." } Here is my urls.py from django.urls import path from . import views app_name = 'app' urlpatterns = [ path('users/<str:pk>/', views.UserUpdate.as_view(), name='user-create'), ] What am I doing wrong … -
when I want to logout in drf api browsable it shows HTTP ERROR 405
I'm new in DRF and now I have an Error in logout in DRF API browsable when I want to logout in API browsable it shows me Error 405 (method not Allowed) this is my setting.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', ), } this is my urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')) ] please tell what can I do to fix this Error as I said I'm new in DRF so I just Wrote this codes nothing else I think this Error its because BasicAuthentication -
How to create a separate user base in Django without extending the user model
So I am trying to build a website in Django where I want two separate user bases like users and agents. An agent can be an agent without being a user. Agents have a separate login url and users have a separate login url. This is where I am stuck. I can't seem to create a different login page for agents. Anyone can apply to be an agent without logging in/registering as a user, then if he/she meets requirements, he/she will be registered as an agent in the admin panel by a superuser. My models.py: from django.contrib.auth.models import User class Agent(models.Model): name = models.CharField(max_length=100) password = models.CharField(max_length=100) image = models.ImageField(upload_to = 'Images/') bio = models.TextField() instagram = models.URLField(max_length=100) twitter = models.URLField(max_length=100) facebook = models.URLField(max_length=100) linkedin = models.URLField(max_length=100) is_featured = models.BooleanField(default = False) slug = models.SlugField(default='') def __str__(self): return f'{self.name} Agent Profile' My forms.py: class AgentSignInForm(AuthenticationForm): username = forms.CharField(max_length=100) password = forms.CharField(max_length=100) def clean(self): cleaned_data = super().clean() username = cleaned_data.get('username') password = cleaned_data.get('password') return cleaned_data My models.py: class AgentLoginView(LoginView): form_class = AgentSignInForm def form_valid(self, form): form.send_email() return super().form_valid(form) -
Insert New Row Into Django-Tables2 Table In For Loop
I am using django-tables2 in Netbox, and am looking to create a new table that is similar to: Get all values that are at site X For each value at site X, run a query and add results into a table I have figured out how to do the queries, but how would I add each new row into the larger table in the for loop without overwriting the entire table in the for loop? -
How to dynamically change database in fastapi?
there are different databases for different users. so after I extract the user from the api token, I want to switch my from my public database to the user database like how THREAD_LOCAL.DB = dbname works in django. I am currently using tortoise orm to manage the database connection. Is there a way to achieve that with tortoise or any other orm? . -
Invalid Syntax on filterset_fields inside Viewset when I try to add necessary paranthesis
class PublicUserViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = User.objects.all() serializer_class = UserSerializer filter_backends = [filters.SearchFilter,DjangoFilterBackend] pagination_class = StandardResultsSetPagination filterset_fields = {'id','username','deliveredtotime': ['gte', 'lte']} When I give it a go with below parameter,it works: filterset_fields = ['id','username','deliveredtotime'] It also works with filterset_fields = {'deliveredtotime': ['gte', 'lte']} But when I try to do as shown below: filterset_fields = {'id','username','deliveredtotime': ['gte', 'lte']} I get this: Error: filterset_fields = {'id','username','deliveredtotime': ['gte', 'lte']} SyntaxError: invalid syntax ':' How can I solve this problem? Note: I know this is NOT a valid dictionary parameter. But I have looked at https://www.django-rest-framework.org/api-guide/filtering/ and didn't see any valid option. Does someone know how to work around it? -
LTE and GTE filters do not work inside Viewset
I defined DjangoFilterBackend inside filter_backends and added (tried to) the correct definitions as shown in filter_fields. It does not give any error in url search but it does not give any result (as filtered) in shown URL: http://127.0.0.1:8000/api/publicusers/?deliveredtotime__lte=50 class User(AbstractUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField(max_length=40, unique=True, default='undefinedusername') deliveredtotime = models.IntegerField(default='0') class PublicUserViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = User.objects.all() serializer_class = UserSerializer filter_backends = [filters.SearchFilter,DjangoFilterBackend] pagination_class = StandardResultsSetPagination filter_fields = { 'deliveredtotime': ['gte', 'lte'] } What am I doing wrong? Edit: filterset_fields = {'username','id', 'deliveredtotime': ['gte', 'lte'],} Error: filterset_fields = {'username','id', 'deliveredtotime': ['gte', 'lte'],} ^ SyntaxError: invalid syntax -
Forbidden (CSRF cookie not set.) : /accounts/register/ , django react
import React, { useState } from "react" import axios from "axios" import CSRFToken from "./CSRFToken" import Cookies from "js-cookie" const Register = () => { const [formData, setFormData] = useState({ email: "", username: "", password: "", re_password: "" }) const config = { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': Cookies.get('csrftoken') } } const handleChange = (e) => { setFormData(() => ({ ...formData, [e.target.name]: e.target.value })) } const submitForm = async (e) => { e.preventDefault() console.log(formData) if (formData.password === formData.re_password) { if (formData.password.length < 8) { alert("Password should minimum of 8 characters") } else { console.log("Data is valid") try { console.log(config) const reg_req = await axios.post("http://localhost:8000/accounts/register/", JSON.stringify(formData), config) console.log(reg_req.data) } catch (error) { console.log(error) } } } else { alert("Passwords don't match") } } return <> <div className="container"> <div className="row"> <div className="col-md-3"></div> <div className="col-md-6 border p-4 rounded mt-4"> <h2 className="my-2 mb-3">Register</h2> <form onSubmit={submitForm}> <CSRFToken /> <div className="form-floating mb-3"> <input type="email" className="form-control" id="email" name="email" placeholder="name@example.com" value={formData.email} onChange={handleChange} /> <label htmlFor="email">Email address</label> </div> <div className="form-floating mb-3"> <input type="text" className="form-control" id="username" name="username" placeholder="username" value={formData.username} onChange={handleChange} /> <label htmlFor="username">Username</label> </div> <div className="form-floating mb-3"> <input type="password" className="form-control" id="password" name="password" placeholder="Password" value={formData.password} onChange={handleChange} /> <label htmlFor="password">Password</label> </div> <div className="form-floating mb-3"> <input type="password" className="form-control" id="re_password" name="re_password" placeholder="Re … -
TypeError: 'Meta.fields' must not contain non-model field names: minimum_price
Here is what I am trying to do: User (business) have multiple article items and I am trying to find and show the minimum priced item inside the User class. Models.py class User(AbstractUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField(max_length=40, unique=True, default='undefinedusername') email = models.CharField(max_length=255, unique=True,null=True,blank=True) @property def minimum_price(self): return self.articles.all().aggregate(Min('price'))['price__min'] class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='articles') caption = models.CharField(max_length=250) timestamp = models.DateTimeField(auto_now_add=True) price = models.FloatField(default='0') Serializers.py class UserSerializer(serializers.ModelSerializer): minimum_price = serializers.ReadOnlyField() class Meta: model = User fields = '__all__' def validate(self, attrs): attrs = super().validate(attrs) if attrs.get('id') == self.context['request'].user.pk: return attrs raise ValidationError('Unauthorized Request') Views.py class PublicUserViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = User.objects.all() serializer_class = UserSerializer filter_backends = [filters.SearchFilter,DjangoFilterBackend] filterset_fields = ['minimum_price'] But here is the error that I get: TypeError: 'Meta.fields' must not contain non-model field names: minimum_price How can I solve this problem? -
351 ERROR: No matching distribution found for distro-info==1.1+ubuntu0.1
i am new to docker, i am using a docker project where i am trying to make a docker compose build and i am receiving an error as 351 ERROR: No matching distribution found for distro-info==1.1+ubuntu0.1 but in my requirements.txt distro-info==1.1+ubuntu0.1 this is defined but previously it was working, but when i put the command pip freeze > requirements.txt and added channels to the file after that i am trying to build it again it is showing me some errors and one of the error is this 351 error -
Django field validation warnings
I am new to Django and confronted with the following problem: Usually I have a form where I have defined my fields and according validation rules. Usually there are fields which have potentially invalid inputs. These are then validated and an error is shown in case. An invalid form leads to the expected behaviour that the data isn't persisted to the database. Now I have a form where I have strict validation rules which should lead (to displaying) an error and data not persisting to the database and besides I have looser validation rules which should lead to displaying of a warning/hint but persisting to the database. Example I have a list where the user could enter how many male, female and diverse participants were in a given course. Later on I ask questions about how many male, female and diverse partcipants would like to do another course from our program. There may be inconsistencies at the moment which I want to warn about but nevertheless accept / save the data as given. Is there any mechanics in Django which allows displaying "warnings", "hints" etc. per field like the error messages? -
Creating django models and setting its default to existing 'Users'
My application already has some existing users. Now, I want to add a 'Follower' feature, so I created a Follower model: class User(AbstractUser): pass class Follower(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower', null=True) following = models.ManyToManyField(User, related_name='following', blank=True) Is there a way I can set the existing Users as its default for the user(follower) column in Follower model?. Upon clicking the follow button, in the backend, I coded it so that if the user (follower) in the Follower model does not exist, it will create the user (follower) and then add the followed user to its 'following'. Otherwise, it will immediately add the followed user to its 'following' in the Follower model. IT WORKS. BUT. I want to know if there is still any other way to do it in the models.py. -
Where to put crucial credentials?
Should I put all API keys etc. inside .env and git ignore it or use the environment variables? As far as I understand .env is just the equivalent of putting passkeys into the environment, but it is easier accessible from the root directory. -
signals not working in my vendor management app django app and i tried to import vendor_app.signals in app.py but error is showing
I have create three models vendor, purchase order and historical performance where historical performance model update from changes and values of purchase order for which i created signal file seprately and added the logic to update fields.I tried to configure signals in my apps.py file in vendor_app directory for which i am getting error"no module fine vendor_app" . I added vendor_app in my vendor_management/settings.installed app. I can't figure out where is problem. models.py code from django.contrib.auth.models import User from rest_framework.authtoken.models import Token from django.dispatch import receiver import datetime from django.db.models.signals import post_save # Creating Model for storing user token @receiver(post_save, sender=User) def create_auth_token(sender, instance, created=False, **kwargs): if created: Token.objects.create(user=instance) # Creating model for vendor class Vendor(models.Model): name = models.CharField(max_length=255) contact_details = models.TextField() address = models.TextField() vendor_code = models.CharField(max_length=50, unique=True) on_time_delivery = models.FloatField(default=0) quality_rating_avg = models.FloatField(default=0) average_response_time = models.FloatField(default=0) fulfillment_rate = models.FloatField(default=0) # Creating model for Purchase Order class PurchaseOrder(models.Model): STATUS_CHOICES = [ ('pending', 'Pending'), ('completed', 'Completed'), ('canceled', 'Canceled'), ] po_number = models.CharField(max_length=50, unique=True) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) order_date = models.DateTimeField(default=datetime) delivery_date = models.DateTimeField(null=True) items = models.JSONField() quantity = models.IntegerField() status = models.CharField(max_length=50, choices=STATUS_CHOICES) quality_rating = models.FloatField(null=True, blank=True) issue_date = models.DateTimeField() acknowledgment_date = models.DateTimeField(null=True, blank=True) class HistoricalPerformance(models.Model): vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) … -
How to create distinct items using FactoryBoy in Django Rest Framework
I have the following code. #factories.py fake: Faker = Faker() class CollectionFactory(factory.django.DjangoModelFactory): class Meta: model = Collection django_get_or_create = ('title', ) title = fake.word(part_of_speech='noun') class ProductFactory(factory.django.DjangoModelFactory): class Meta: model = Product # django_get_or_create = ('title',) title = fake.word(part_of_speech='noun') slug = fake.slug() description = fake.text() unit_price = fake.pydecimal(max_value=1000, min_value=1, right_digits=2) inventory = fake.random_number(digits=4) last_update = fake.date_time_ad(start_datetime=datetime(1998, 1, 1, 1, 1, 1), end_datetime=datetime.now()) # collection = CollectionFactory() collection = factory.SubFactory(CollectionFactory) #test_product.py @pytest.mark.django_db class TestListProduct: def test_product1(self, api_client, product_factory): product_factory: ProductFactory = product_factory product_factory.create_batch(10) prods = Product.objects.all() # Problem: all of these products have the same title cols = Collection.objects.all() assert Product.objects.count() == 1 But the problem is that when I am doing the test all of the products are identical, I need them to at least have different titles. How do I achieve this? -
Problem with Django class-based LogoutView in Django 5.0
I used Django class-based login and logout views by "django.contrib.auth.urls", login feature works correctly, but when logging out via the link "http://127.0.0.1:8000/accounts/logout" it returns an http 405 error page, saying "method not allowed (GET)". I found out this logout feature was available in django 4.0 but in django 5.0 it's removed. Support for logging out via GET requests in the django.contrib.auth.views.LogoutView and django.contrib.auth.views.logout_then_login() is removed. -djangoproject.com How can I fix it? I think I should somehow make it use POST request instead GET request when loging out but don't know how.