Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Arrays in django rest framework
Can anyone help me represent this in django rest framework? I need to recreate this json data in the DRF, but I don't know how to create an array inside the views, taking the data from another model. { "name": "Fabiano Felipe", "email": "fabiano.webdev@gmail.com", "phone": "55(81)98121-3241", "products": [ { "product_type": "Hotel", "product_description": "Recife Palace", "start_date": "12/10/2025", "end_date": "15/10/2025", "from_location": "", "to_location": "New York" }, { "product_type": "Transfer", "product_description": "Passeio X", "start_date": "12/10/2025", "start_time": "12:00", "end_time": "15:00", "end_date": "12/10/2025", "from_location": "Miami", "to_location": "New York" } ] } The first four fields will be created within the model, however, the array, I need to bring from another model so that the user can fill it. -
Django: How to sort by presence of M2M (Pizza Example)
Say I have the common pizza example: class Topping(models.Model): order = models.IntegerField() name = models.CharField(max_length=250) class Pizza(models.Model): toppings = models.ManyToManyField(Topping) With the following toppings: Topping.objects.create(order=1, name="tomato") Topping.objects.create(order=2, name="cheese") Topping.objects.create(order=3, name="olives") Topping.objects.create(order=4, name="salami") Topping.objects.create(order=5, name="onion") Topping.objects.create(order=6, name="rocket") Now say I had a pizza with tomato, cheese and salami I wish to get an order list of all the toppings of the pizza according to the topping__order, along with a list of all the toppings it does not have, also ordered by topping__order So its sort by first where the pizza has the topping, and secondly by the topping__order field. The result would be something that has the same info as this (probably in a queryset though): { { "id": 1, "name": "tomato", "has_topping": True}, { "id": 2, "name": "cheese", "has_topping": True}, { "id": 3, "name": "salami", "has_topping": True}, { "id": 2, "name": "olives", "has_topping": False}, { "id": 5, "name": "onion" , "has_topping": False}, { "id": 6, "name": "rocket", "has_topping": False}, } Is this possible via a database query? (I can do it manually in python via two querries) -
Do I need to write triggers and functions directly to DB server while using a programming framework like django?
I am new to DB based programming and was trying to build trigger functions to update one table on INSERT/UPDATE on another table. I plan to use django for backend and PostgreSQL or SQLite for DB. Would like to know whether I should write all DB functions within django or should write some SQL functions directly in the DB server. I know django can handle SQL queries etc. But considering separate DB servers in big projects, I wonder how this is done. -
Django, CSP: How to activate Nonce in scripts for Admin pages
At my page scripts are only executed, when the nonce tag is included (because of CSP settings). That causes at the admin pages, that scripts are not working. Therefore I am overwriting now all the admin templates, for example from: <script src="{% static 'admin/js/nav_sidebar.js' %}" defer></script> to <script src="{% static 'admin/js/nav_sidebar.js' %}" nonce="{{request.csp_nonce}}" defer></script> Is there an easier way to do this? Deactivate CSP on the admin pages or somehow tell Django to add Nonce to all scripts? Thanks -
ImageField Test In View
I'm trying to post an Image on 'accounts/profile_edit' url in one of my tests. I have a Profile model which resizes images bigger than (225, 255) and this is the functionality I want to test. I read how to unit test file upload in django but I can't get client.post to work with image. What is the problem? class TestProfileEditView(TestCase): # other tests... def test_profile_picture_resize(self): self.client.force_login(user=self.user) image = Image.new('RGB', (500, 500), (255, 255, 255)) image_location = f'{settings.MEDIA_ROOT}/TestProfilePictureResize.png' image.save(image_location) with open(image_location ,'rb') as f: response = self.client.post(reverse('profile-edit-view'), {'picture': f}) profile = Profile.objects.get(user=self.user.id) picture_path = profile.picture # falsely returns default picture location self.assertEqual(picture_path, /media/profile_pictures/TestProfilePictureResize.png) self.assertTemplateUsed(response, 'user/profile.html') # returns False views.py : @login_required def profile_edit(request): if request.method == 'POST': user_form = UserEditForm(request.POST, instance=request.user) profile_form = ProfileEditForm( request.POST, request.FILES, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, f'Profile Edited Successfully.') return redirect(reverse('profile-view'), request.user) else: user_form = UserEditForm(instance=request.user) profile_form = ProfileEditForm(instance=request.user.profile) context = { 'user_form': user_form, 'profile_form': profile_form } return render(request, 'user/profile_edit.html', context) models.py : class User(AbstractUser): email = models.EmailField(unique=True, blank=False, null=False) first_name = models.CharField(max_length=50, blank=False, null=False) last_name = models.CharField(max_length=50, blank=False, null=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] def __str__(self): return f"{self.first_name} {self.last_name}" class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) picture = models.ImageField( default=f"default_profile_picture.png", upload_to="profile_pictures" … -
User has no attribute session
After looking online I cannot come up with the solution. I am building my own authentication app: I can register the user, send activation account email, activate the account, login, and correctly change password. However, when it comes to logging out, I get the error 'User' object has no attribute 'session'. I try to print the user and it shows correctly the email and username associated to it. Checking inside the cookies there seem to be a valid csrf token and a valid session id. I would love if you can double check my login, logout and settings to see if I am messing something up. settings.py REST_FRAMEWORK = { 78 'DEFAULT_AUTHENTICATION_CLASSES': ( 79 'rest_framework.authentication.SessionAuthentication', 80 'rest_framework.authentication.BasicAuthentication', 81 ), 82 'DEFAULT_PERMISSION_CLASSES': ( 83 'rest_framework.permissions.IsAuthenticated', 84 'rest_framework.permissions.IsAdminUser', 85 ), 86 } loginView class LoginView(APIView): 23 authentication_classes = [SessionAuthentication, BasicAuthentication] : list[Unknown] 24 permission_classes = [AllowAny] : list[Type[AllowAny]] 25 26 def post(self, request): -> Response 27 serializer = LoginSerializer(data=request.data) : LoginSerializer 28 if serializer.is_valid(): 29 try: 30 user = authenticate(request, : Unknown | None 31 email_or_username=request.data["email_or_username"], 32 password=request.data["password"]) 33 34 except ValueError as e: 35 return Response({"errors": f"{e}"}, status=status.HTTP_400_BAD_REQUEST) 36 37 login(request, user) 38 return Response({"success":"user successfully logged in"}, 39 status=status.HTTP_200_OK) 40 … -
Django not setting cookies after deployment
I have created a vue and DRF application, which is working fine locally, it sets access, refresh and csrf token in cookies on login and so all of the isAuthenticated routes work fine. But i handed it over to the person who's meant to deploy this on vps and now it doesn't set cookie on login. I'm able to login, but since no cookie is set, refreshing it logs me out and all routes give 401 error. These are my django settings, removing secret_key here: import os from pathlib import Path from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_api_key', 'rest_framework_simplejwt.token_blacklist', 'corsheaders', 'django_filters', 'api' ] AUTH_USER_MODEL = 'api.User' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.AllowAllUsersModelBackend', ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", "fxbNh4", ] # CORS_ALLOWED_ORIGINS = [ # "http://localhost:8080" # … -
int() argument must be a string, a bytes-like object or a number, not 'list
def request_id_generator(script_id): script_id = str(script_id) mnf_reference = MNFScriptDatabase_2.objects.get(script_id=script_id) service_no = int(mnf_reference.script_used_by_services) + 1 mnf_reference.script_used_by_services = int(service_no) mnf_reference.save() request_id = str(script_id) + "_" + str(service_no) return request_id -
Anyone can you help about CSP in ckeditor in djang
enter image description here Help me about this CSP -
in django data base stored image not display in application and i have no error while running the code
I have no error while run the code the images will stored database but it will not display in webpage ,I post my source code here my application page code {% extends 'shop/layouts/main.html' %} {% block title %} registration | onlineshopping {% endblock title %} {% block content %} <section class="py-5 text-center container" style="margin-top: 70px;"> <div class="row py-lg-5"> <div class="col-lg-6 col-md-8 mx-auto"> <h1 class="fw-light">Bestsellers</h1> <p class="lead text-muted">Our most popular products based on sales.updated honourly</p> <p> <a href="#" class="btn btn-primary my-2">Already User</a> <a href="#" class="btn btn-secondary my-2">Register</a> </p> </div> </div> </section> <section class="bg-light py-4 my-5"> <div class="container"> <div class="row"> <div class="col-12"> <h4 class="mb-3">Categories</h4> <hr style="border-color:#b8bfc2"> </div> {% for item in category %} <div class="col-md-4 col-lg-3"> <div class="card my-3"> <img src="{{item.image.url}}" class="card-image-top" alt="Categories"> <div class="card-body"> <h5 class="card-title text-primary">{{item.name}}</h5> <p class="card-text">{{ item.description }}</p> <a href="" class="btn btn-primary btn-sm">View Details</a> </div> </div> </div> {% endfor %} </div> </div> </section> {% endblock content %} models.pycode from django.db import models import datetime import os def getFileName(request,filename): now_time=datetime.datetime.now().strftime("%Y%m%d%H:%M:%S") new_filename="%s%s"%(now_time,filename) return os.path.join('uploads/',new_filename) # Create your models here. class Catagory(models.Model): name=models.CharField(max_length=150,null=False,blank=False) image=models.ImageField(upload_to=getFileName,null=True,blank=True) description=models.TextField(max_length=500,null=False,blank=False) status=models.BooleanField(default=False,help_text="0-show,1-Hidden") created_at=models.DateTimeField(auto_now_add=True) def __str__(self) : return self.name class Product(models.Model): catagory=models.ForeignKey(Catagory,on_delete=models.CASCADE) name=models.CharField(max_length=150,null=False,blank=False) vendor=models.CharField(max_length=150,null=False,blank=False) product_image=models.ImageField(upload_to=getFileName,null=True,blank=True) quantity=models.IntegerField(null=False,blank=False) original_price=models.FloatField(null=False,blank=False) selling_price=models.FloatField(null=False,blank=False) description=models.TextField(max_length=500,null=False,blank=False) status=models.BooleanField(default=False,help_text="0-show,1-Hidden") trending=models.BooleanField(default=False,help_text="0-default,1-Trending") created_at=models.DateTimeField(auto_now_add=True) def __str__(self) : return self.name setting.py … -
How to Filter Children Model In Django RestFramework
I have been trying to build an api to filter out country_name. How can i filter multiple data from multiple model connected to each other through Foreign key. when I query url https://www.localhost:8000/api/country/?country_name={}. It give me exact country that i want. { "count": 1, "next": null, "previous": null, "results": [ { "id": "7f0cf3bd-0a67-4c57-b192-5cf6cba8b203", "country_name": "Usa", "state": [ { "id": "6a070973-11bd-4f9e-9bbf-652f171b028b", "state_name": "Alaska" }, { "id": "6ed508ce-5ea0-441b-a02e-22cc9b70e6ae", "state_name": "Texsas" } ] } ] } I want same for state_name inside country_name if there are multiple states. How can I do it. Models.py from django.db import models import uuid # create your models here # Forename Model class COUNTRY(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) country_name = models.CharField(max_length=100, default=None) def __str__(self): return self.country_name class STATE(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) state_name = models.CharField(max_length=100, default=None) # PARENT_COUNTRY parent_country = models.ForeignKey(COUNTRY, on_delete=models.PROTECT, related_name='state') def __str__(self): return self.state_name Serializer.py from rest_framework import serializers from .models import COUNTRY, STATE # Name Serializer class STATE_Serializer(serializers.ModelSerializer): class Meta: model = STATE fields = ["id", "state_name"] class COUNTRY_Serializer(serializers.ModelSerializer): state = STATE_Serializer(many=True, required=True) class Meta: model = COUNTRY fields = ["id", "country_name", "state"] Views.py from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response from django_filters.rest_framework import DjangoFilterBackend from .serializers import COUNTRY_Serializer, from … -
How to test api with session in django
I am currently building an auth app that provides register, login, logout ... functionalities. Everything seems to work fine, however when I log the user in, I cannot logout, I get an Anonymous user error instead. After searching on the internet I came to the conclusion that it is not the best to build an api with sessions and instead to use tokens(JWT). With sessions I cannot test my API with tools like POSTMAN because that requires cookies (technically you can use cookies in POSTMAN though). Having said that, sessions seem to be more stable and secure so how would I go about testing my API using the sessions stored in the cookie? Thanks. -
Developing a web application with python
I would like to learn to write a web application using python. The application will write information into and retrieve data from a PostgreSQL database I will be hosting on a personal web URL. I would like to securely log into the application and select (or create a new) item/file to work on. The file will have a structure like an indented bill of material a user can dig down into if the data exists or can build if it does not. I am expecting to build the structure with Python classes, but I don't know where to start with building the GUI for the web browser. I would like to have a slick interface with a tree structure on the left of the screen I can expand and dig down or add items, and a form containing information on the right (or blank properties if the item is being added). Eventually I would like to show analysis and various other views of the data contained in the database including graphs and summary tabs. Would Django be the right tool to use to build the web app or Flask or is there something better I should spend my time learning. … -
How to order by queryset by Saturday to Sunday in django?
i want to order an attendance queryset by Saturday to Friday. how can i achieve it? class ReportsTogether(models.Model): user = models.ForeignKey(User,on_delete=CASCADE,verbose_name=_("Report For User")) user_log = models.ManyToManyField(UserTimeInOut,verbose_name=_("User Attendance")) user_break = models.ManyToManyField(UserBreak,verbose_name=_("User Break")) user_lunch = models.ManyToManyField(UserLunchBreak,verbose_name=_("User Lunch Break")) time = models.DateField(verbose_name=_("Date"),null=True) -
Django interal server error 500 while creating home page
Currently trying to set up a sign-up page, as well as the start of a project I am going to try to accomplish. But after adding in bootstrap (it seemed like might not have been) that I couldn't load the page, I had also added in a urls to my main/site directory as well. Let me know if I should include the html as well. App/ App\__init__.py analysis_app\asgi.py analysis_app\settings.py ... Main/ main\migrations main\templates main\__init__.py main\admin.py main\urls.py main\views.py .... Traceback: Internal Server Error: / Traceback (most recent call last): File "C:\Users\Blue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Blue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\deprecation.py", line 136, in __call__ response = self.process_response(request, response) File "C:\Users\Blue\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\middleware\clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'tuple' object has no attribute 'get' [11/Sep/2022 00:43:07] "GET / HTTP/1.1" 500 63663 App\urls.py: from django.contrib import admin from django.urls import path, include from main import views urlpatterns = [ path('admin/', admin.site.urls), #path('', views.home, name=""), path('', include('main.urls')), path('', include('django.contrib.auth.urls')), ] Some of the App/settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'crispy_bootstrap5', 'main.apps.MainConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'analysis_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['analysis_app/main/templates'], 'APP_DIRS': True, … -
Why for loop is not running in django template?
for loop is not running in django template. For loop is working in terminal but showing nothing in the template.. -
ugettext_lazy not working in model validator
I'm using ugettext_lazy in a model validator to return the proper message to the frontend with the right language but it is not working. from django.utils.translation import ugettext_lazy as _ class User(AbstractUser, BaseModel): mobile_number = models.CharField( 'Mobile Number', validators=[ RegexValidator( regex=r'^A Validator regex', message=_('Mobile Number is not Valid'), code='invalid_mobile', ) ], max_length=32, blank=True, ) I am using Django Rest Framework and some of the errors are handled in the serizliers and the ugettext_lazy is working properly in the serializer errors but when it comes to the model messages, the translation is not working and it returns the English version of the error. -
How to create API by Django Rest Framework for minio bucket creation?
I Can't understand how to create minio bucket for authenticate user. this API will be create by Django rest Framework . -
CurrentUserDefault doesn't work with AnonymousUser
I'm trying to use CurrentUserDefault with a field that can be null: # model class Package(models.Model): # User can be empty because we allow anonymous donations owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, ) # serializer class PackageSerializer(serializers.ModelSerializer): owner = serializers.HiddenField(default=serializers.CurrentUserDefault()) Everything works fine when a user is logged in. However, if a user is not authenticated I get this: ValueError at /api/organizations/village/packages/ Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7fc97ad6d940>": "Package.owner" must be a "User" instance. Is there a reason why CurrentUserDefault doesn't work with anonymous users? P.S. I know I can use this instead of CurrentUserDefault and it will work: class AuthorizedUserOrNone: requires_context = True def __call__(self, serializer_field): user = serializer_field.context["request"].user if user.is_authenticated: return user return None def __repr__(self): return "%s()" % self.__class__.__name__ -
Is it possible to display the HTML provided by the admin panel app on-site?
I've built a site where I can create new posts (essays) by the admin panel. The output is visible to users. But when I place some HTML as content in the form it doesn't render itself on the page. example: Output on the page (with marked unrendered HTML): I would like to know how to fix it and also, how to name the topic I want to know ( I couldn't find anything related to my problem, probably because I don't know how to express it). -
Python - Django MySql raw sum returns single value
Beginning in Django, I try to query data from MySQL and running with an issue while I try to use raw. I return, I correct values, grouped, but not summed (only return last value for that group I guess). My query works good when I run it on MySQL directly, just not with objects.raw. Any idea why that is / How to work with that? My code is as below. yesterday = date.today() - timedelta(days=1) list_parts = PqList.objects.raw('SELECT id, SUM(quantity), equipment_id, so_number FROM pq_list WHERE date > %s group by equipment_id, so_number', [yesterday]) context['list_parts'] = list_parts -
Django message framework doesn't show messages
I have a flow where one page adds a message to Django's message store (CookieStore) and another page displays that message (by rendering it onto a template). All works nicely in most environments. However I have one environment where the message doesn't show. I can see the cookie being set, but it is not getting removed in the "other" page load. My question is - are there any env variables that may be preventing the messages from being cleared from store and rendered onto a page, or any other settings to look out for? This environment is not easy to debug, so I can't set any breakpoints and searching the code didn't reveal anything obvious. -
How to create view and serializer to add to many to many field in DRF
I implemented two models, Card and Dish. I used many-to-many relationship because Dish can be in many cards. Furthermore, I have been struggling and could not get answer anywhere how to update created card with dish. Or create a card with dishes in it. Should I try to create a middle filed with IDs of card and dish or there is some other way to do it in DRF? I have been struggling with this for some time and would greatly appreciate some tip please. Here is the code: class Dish(models.Model): name = models.CharField(max_length=255, unique=True) description = models.TextField(max_length=1000) price = models.DecimalField(max_digits=5, decimal_places=2) preparation_time = models.IntegerField() date_added = models.DateField(auto_now_add=True) update_date = models.DateField(auto_now=True) vegan = models.BooleanField(default=False) def __str__(self): return self.name class Card(models.Model): name = models.CharField(max_length=255, unique=True) description = models.TextField(max_length=1000) date_added = models.DateField(auto_now_add=True) update_date = models.DateField(auto_now=True) dishes = models.ManyToManyField(Dish, blank=True) def __str__(self): return self.name class DishSerializer(serializers.ModelSerializer): class Meta: model = Dish fields = ['id', 'name', 'description', 'price', 'how_long_to_prepare', 'date_added', 'update_date', 'vegan'] read_only_fields = ['id'] class CardSerializer(serializers.ModelSerializer): class Meta: model = Card fields = ['id', 'name', 'description', 'date_added', 'update_date', 'dishes'] read_only_fields = ['id'] class CreateCardView(generics.CreateAPIView): """Create a new user in the system.""" serializer_class = serializers.CardSerializer class AddToCardView(generics.CreateAPIView): serializer_class = serializers.CustomUserSerializer -
Optimal way to fetch related model and through model together in ManyToManyField
Given schema: class Investor(models.Model): name = models.CharField(max_length=30) advisors = models.ManyToManyField("Advisor", related_name="investors", through="Connection") class Advisor(models.Model): name = models.CharField(max_length=30) class Connection(models.Model): investor = models.ForeignKey("Investor", related_name="connections", on_delete=models.CASCADE) advisor = models.ForeignKey("Advisor", related_name="connections", on_delete=models.CASCADE) blocked = models.BooleanField(default=False) And given an Advisor "a", what is the optimal to fetch a list of all Investors and their Connection to "a" when it exists? The best I've figured out so far is: from django.db.models import Prefetch for investor in Investor.objects.prefetch_related( Prefetch( 'connections', queryset=Connection.objects.filter(advisor=a), to_attr='connection', ) ): name = investor.name blocked = None if investor.connection: blocked = investor.connection[0].blocked print(f"{name} (blocked={blocked})") -
REACT: using a functional component in a class-defined class modal
I have a problem which I cannot solve: I started a ReactJS project and used the class definition for all components. Now I would like to add the following tool to my webapp: DragandDropApp. This tools uses the functional definition and now I need help on how to implement this / add this componenent to a modal, which was defined as a class. Is it in general possible to do that? If yes, could you help me on how to return/ render the component, so that I can add it to my app? Thank you very much in advance! Best, Simon