Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't retrieve token from angular side, but it works fine in postman - JWT not shown in 'application' browser tab - Django - Angular
I trying to make login page and home page with django and angular, it logged in well, but once i try to retrieve the logged in user from angular it shows me 403 (Forbidden) but it works fine in postman, it'll retrieve the logged in information I tried this below code, i expected to show me the logged in user, but it shows 403 error message. and it doesnt show the jwt on my web browser developer tool Application, it looks like it has not been stored. it logged in successfully from frontend and will show the token(JWT) with console.log , but when i try to use the jwt for another page it shows me 403 error. my server side - django: this what im trying to retrieve, but shows the error class UserView(APIView): def get(self,request): token = request.COOKIES.get('jwt') print(token) # this will retrieve null when i send request from angular, but retrieve the token when i send the request with postman if not token: raise AuthenticationFailed('UnAuthorized user!') try: payload = jwt.decode(token,'secret',algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Expired Session') user = User.objects.get(id=payload['id']) serializer = UserSerializer(user) return Response(serializer.data) my urls.py urlpatterns = [ path('api/login/',LoginView.as_view(),name='login'), path('api/users/',UserView.as_view(),name='user'), ] and my settings.py INSTALLED_APPS = [ 'django.contrib.admin', … -
AttributeError: module 'django.conf.global_settings' has no attribute 'ROOT_URLCONF' no solutions found worked
I know this is a known issue, but no solutions on other threads have helped me. No matter what I do, I get this error in Azure Stream logs, everything works fine when I run the project locally. my wsgi.py file: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mojspecjalista.settings') application = get_wsgi_application() My project url file: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('App.api.urls')), path('admin/', admin.site.urls), ] manage.py: def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mojspecjalista.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() and lastly my settings: ROOT_URLCONF = 'mojspecjalista.urls' -
python bug - django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable
enter image description hereI am trying to run my python server and I got this error File "/Users/solnsnday/Documents/Workspace/authors-haven/src/venv/lib/python3.12/site-packages/django/core/management/commands/runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: ^^^^^^^^^^^^^^ File "/Users/solnsnday/Documents/Workspace/authors-haven/src/venv/lib/python3.12/site-packages/django/conf/__init__.py", line 92, in __getattr__ self._setup(name) File "/Users/solnsnday/Documents/Workspace/authors-haven/src/venv/lib/python3.12/site-packages/django/conf/__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/solnsnday/Documents/Workspace/authors-haven/src/venv/lib/python3.12/site-packages/django/conf/__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 994, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "/Users/solnsnday/Documents/Workspace/authors-haven/src/authors_api/settings/local.py", line 1, in <module> from .base import * #noqa ^^^^^^^^^^^^^^^^^^^ File "/Users/solnsnday/Documents/Workspace/authors-haven/src/authors_api/settings/base.py", line 85, in <module> DATABASES = {"default": env.db("DATABASE_URL")} ^^^^^^^^^^^^^^^^^^^^^^ File "/Users/solnsnday/Documents/Workspace/authors-haven/src/venv/lib/python3.12/site-packages/environ/environ.py", line 295, in db_url self.get_value(var, default=default), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/solnsnday/Documents/Workspace/authors-haven/src/venv/lib/python3.12/site-packages/environ/environ.py", line 391, in get_value raise ImproperlyConfigured(error_msg) from exc django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable (venv) solnsnday@Solomons-MBP src % This is my local.py[setting.py] from datetime import timedelta from pathlib import Path import environ env = environ.Env() # Build paths inside the project like this: BASE_DIR / 'subdir'. ROOT_DIR = Path(__file__).resolve().parent.parent.parent APP_DIR = ROOT_DIR / "core_apps" DEBUG = env.bool("DJANGO_DEBUG", … -
Organize Checkboxes into Columns using Django Admin ModelForm
I am building an admin interface using Django 3.0 on top of a codebase I cannot change or overwrite any of the static files within. I have one select field, "states_incl", that uses the CheckboxSelectMultiple widget. I have the code working successfully with updating and saving to the model, but I am wanting to organize these 50 checkboxes into 5x10 columns to limit the whitespace. Is it possible to achieve this inside of the Python code available for the admin.py? My snippets are below. STATE_CHOICES = [('AK', 'AK'), ('AL', 'AL'), ('AR', 'AR'), ('AZ', 'AZ'), ('CA', 'CA'), ('CO', 'CO'), ('CT', 'CT'), ('DE', 'DE'), ('FL', 'FL'), ('GA', 'GA'), ('HI', 'HI'), ('IA', 'IA'), ('ID', 'ID'), ('IL', 'IL'), ('IN', 'IN'), ('KS', 'KS'), ('KY', 'KY'), ('LA', 'LA'), ('MA', 'MA'), ('MD', 'MD'), ('ME', 'ME'), ('MI', 'MI'), ('MN', 'MN'), ('MO', 'MO'), ('MS', 'MS'), ('MT', 'MT'), ('NC', 'NC'), ('ND', 'ND'), ('NE', 'NE'), ('NH', 'NH'), ('NJ', 'NJ'), ('NM', 'NM'), ('NV', 'NV'), ('NY', 'NY'), ('OH', 'OH'), ('OK', 'OK'), ('OR', 'OR'), ('PA', 'PA'), ('RI', 'RI'), ('SC', 'SC'), ('SD', 'SD'), ('TN', 'TN'), ('TX', 'TX'), ('UT', 'UT'), ('VA', 'VA'), ('VT', 'VT'), ('WA', 'WA'), ('WI', 'WI'), ('WV', 'WV'), ('WY', 'WY')] class StateModelForm(forms.ModelForm): class Meta: model = States fields = '__all__' def __init__(self, *args, **kwargs): … -
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.