Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is the full_name field not being populated when customer submits payment form in Django and Stripe integration?
I'm having trouble retrieving the customer's name when they submit a payment form in my Django application. I'm using Django for the backend and Stripe for payment processing. The customer's name is not being saved in the database when the form is submitted. I have a 'add' view that handles the form submission and creates an order. Here's the relevant code: views.py: `from django.http.response import JsonResponse from django.shortcuts import render from basket.basket import Basket from .models import Order, OrderItem def add(request): basket = Basket(request) if request.POST.get('action') == 'post': order_key = request.POST.get('order_key') cust_name = request.POST.get('custName') # Get the custName value user_id = request.user.id baskettotal = basket.get_total_price() if Order.objects.filter(order_key=order_key).exists(): pass else: order = Order.objects.create(user_id=user_id, full_name=cust_name, address1='add1', address2='add2', total_paid=baskettotal, order_key=order_key) order_id = order.pk for item in basket: OrderItem.objects.create(order_id=order_id, product=item['product'], price=item['price'], quantity=item['qty']) response = JsonResponse({'success': 'Return something'}) return response ` The form submission is handled by the following JavaScript code: script.js: var stripe = Stripe(''); var elem = document.getElementById('submit'); clientsecret = elem.getAttribute('data-secret'); var elements = stripe.elements(); var style = { base: { color: "#000", lineHeight: '2.4', fontSize: '16px' } }; var card = elements.create("card", { style: style }); card.mount("#card-element"); card.on('change', function(event) { var displayError = document.getElementById('card-errors') if (event.error) { displayError.textContent = event.error.message; $('#card-errors').addClass('alert alert-info'); … -
Not able to manage Bootstrap components by extending base.html in Django
Difficulty in managing Bootstrap components in Django. I wanted to make two different bootstrap components side by side but its not working if I am extending base.html file ` {% extends 'base.html' %} {% block title %}services{% endblock title %} {% block body %} <div class="container"> <div class="row"> <div class="col-xs-6"> Hello </div> <div class="col-xs-6"> Dev </div> </div> </div> {% endblock body %} ` I was expecting Hello Dev instead I got Hello Dev -
Unable to start DJango server in codesandbox online editor
Unable to start DJango server in codesandbox online editor Error is Environment: Request Method: GET Request URL: http://jhkvsl-8000.csb.app/ Django Version: 4.2.1 Python Version: 3.11.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'apis'] Installed 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'] Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/utils/deprecation.py", line 136, in __call__ response = self.process_response(request, response) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/middleware/clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: ^^^^^^^^^^^^ Exception Type: AttributeError at / Exception Value: 'str' object has no attribute 'get' Code Written inside the project setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'apis', ] apis/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.apis, name="home"), ] apis/views.py from django.shortcuts import render # Create your views here. def apis(request): return "Working fine" complete project link -> https://codesandbox.io/p/sandbox/django-project-api-jhkvsl I am just trying to know weather it is possible to code django application in codesandbox or not. complete project link -> https://codesandbox.io/p/sandbox/django-project-api-jhkvsl I am just trying to know weather it is possible to code django application in codesandbox or not. -
How to import a service for testing locally in Django using the shell?
I'm trying to debug a service in Django using the shell. I ran the following in make shell: from domains.coffee.services import CoffeeService However, I got Apps aren't loaded yet. Can someone please help me to import a service to test its functionalities locally? I tried running make shell, and importing the service into the shell, but was unable to. -
Django DRF Serializer Not Saving Nested Model: What Am I Missing?
django drf nested serializer saving issue i'm not able to save my model due to some nested serializer id issue, i will share my model class Duration(models.Model): start_time = models.PositiveIntegerField(blank=True,null=True) end_time = models.PositiveIntegerField(blank=True,null=True) def __str__(self): self.end_time class VideoMaker(models.Model): CHOICE_SELECT = [ ('vo','voice over'), ('bg_music','backgournd music'), ('video_music','vidio music'), ] typee = models.CharField(max_length=15,choices=CHOICE_SELECT) high_volume = models.PositiveIntegerField() low_volume = models.PositiveIntegerField() video_component_id = models.CharField(max_length=300,null=True,blank=True) url = models.URLField(blank=True,null=True) duration = models.ForeignKey(Duration, on_delete=models.CASCADE) def __str__(self): return self.id My Serializer: class DuratinSeriaizer(serializers.ModelSerializer): class Meta: model = Duration fields = [ 'id', 'start_time', 'end_time', ] class VideoMakerSerializer(serializers.ModelSerializer): duration = DuratinSeriaizer() class Meta: model = VideoMaker fields = [ 'id', 'typee', 'high_volume', 'low_volume', 'video_component_id', 'url', 'duration', ] def create(self, validated_data): datas = validated_data.pop('duration') duration_data = VideoMaker.objects.create(**validated_data) for datas in datas: Duration.objects.create(duration=duration_data,**datas) Duration.save() return duration_data my views: class AudioCreateApiView(generics.ListCreateAPIView): queryset = VideoMaker.objects.all() serializer_class = VideoMakerSerializer if i'm wrong please help me out! The error i'm getting ''' NOT NULL constraint failed: VideoMaker_videomaker.duration_id ''' im not able to save, i'm helpless i'm Expecting : { "id": 6, "typee": "vo", "high_volume": 65, "low_volume": 123, "video_component_id": "wertyuio", "url": "", "duration": { "id": 9, "start_time": 21, "end_time": 98 } } -
Django email redirect
I have to send an email via app. Which I can already! The problem is, in the email I send, there is a hyperlink, I need that hyper link to redirect me when I click to "http:127.0.0.1:8000/view/". The ID is always unique to each "pedido" ! fragment of pedido_list2.html, html that lists pedidos and is where we click at "Pedir opinião": <form action="{% url 'main:index' %}" method="POST" class="options-form"> {% csrf_token %} <button type="submit">Pedir Opinião</button> </form> index.html: <!DOCTYPE html> <html> <head> <title>Obter Informação do PCP sobre o Pedido</title> <style> .submit-button { padding: 10px 20px; background-color: green; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; } </style> </head> <body> <h1>Obter Informação do PCP sobre o Pedido Selecionado</h1> <form action="{% url 'main:index' %}" method="post"> {% csrf_token %} <input type="hidden" name="pedido_id" value="{{ pedido.idpedido }}"> <label for="content">Contexto:</label><br> <textarea id="content" name="content" rows="30" cols="160"></textarea> <button class="submit-button" type="submit" onclick="return confirm('Tem certeza que deseja enviar este mail ao PCP?');">Enviar</button> </form> </body> </html> contactform.html, html that contains the format of the email sent!: <!DOCTYPE html> <html> <body> <h1>Conteúdo do Email</h1> <p><b>Assunto: </b>{{ content }}</p> <a href="http://127.0.0.1:8000/view/{{pedido_id}}">Clique aqui para visualizar o pedido em questão</a> </form> </body> </html> views.py: def index(request): pedido = Pedido2.objects.first() if request.method == 'POST': form = … -
How can I successfully integrate Yahoo sign-in into my Django website using Yahoo API?
I want to integrate Yahoo sign-in into my website, but I have been unsuccessful so far despite registering an app on Yahoo. Can someone guide me on how to achieve this integration? How can I successfully integrate Yahoo login into my website after registering an app on Yahoo? Need guidance on integrating Yahoo login into my Django Rest Framework website. Registered Yahoo app but facing issues. Seeking help in achieving successful integration. -
User unauthorized while making ajax call - Django
I want to get user data through ajax call but request.user.is_authenticated gives False hence unauthorized. Few points to notice: User is logged in successfully. csrf token is also passed in ajax request. Am I doing something wrong here? I have used below code to get it: Ajax function getUserData(user_id) { console.log(getCookie("csrftoken")); $.ajax({ url: new URL(`http://localhost:8000/user/${user_id}`), method: "GET", headers: { "Content-Type": "application/json", "X-CSRFToken": getCookie("csrftoken") }, success: function (result) { let data = result; } }) } views.py def getUserData(request, user_id): if request.method == "GET": print("check User", user_id) print("IS auth: ", request.user) if user_id and request.user.is_authenticated: # request.user.is_authenticated = False table_data = [] return JsonResponse(table_data ) else: return HttpResponse('Unauthorized', status=401) urls.py path('user/<int:user_id>',views.getUserData,name="getUserData" ), -
Fail to show date array in chart.js labels/x-axis in Django
I have a django project where a model called EmployeeDayOutput is created with 2 columns output_date (datetime or date field both work) and output_hours (float). In a html page I use chart.js to display the return recordsets from EmployeeDayOutput, where I use the output_date as labels and output_hours as datasets. For example they are respectively ['2023-5-1', '2023-5-2', '2023-5-3'] and [10, 20, 30]. The chart.js formats the html webpage well but it just shows me the wrong dates as [2017, 2016, 2015] instead of the date format. According to the chart.js examples, the date labels shall take the form as newDateString below. export function newDateString(days) { return DateTime.now().plus({days}).toISO(); } However, the output_date is generated from the server side as defined in the views.py as below: `def empOutputChart(request, employee_id): emp_day_outputs = EmpDayOutput.objects.filter(employee_id=employee_id) # output_dates = [datetime.datetime.strftime(emp_day_output.output_date, "%Y-%m-%d") for emp_day_output in emp_day_outputs] # new_dates = [date.replace("'", "\'") for date in output_dates] output_dates = [emp_day_output.output_date for emp_day_output in emp_day_outputs] output_hours = [emp_day_output.output_hours for emp_day_output in emp_day_outputs] # Pass the data to the template. context = { 'emp_day_outputs': emp_day_outputs, 'output_dates': output_dates, 'output_hours': output_hours, } return render(request, 'vismanager/employee_day_output_chart.html', context)` As you can see, I try to format the output_dates as string instead of date array or … -
Wagtail. ValueError: Cannot create form field for 'site' yet, because its related model 'wagtailcore.Site' has not been loaded yet
I have wagtail project with two apps. Doing makemigrations raise an error: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/oleh/Documents/us_website/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/oleh/Documents/us_website/venv/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "/home/oleh/Documents/us_website/venv/lib/python3.10/site-packages/django/core/management/base.py", line 487, in check all_issues = checks.run_checks( File "/home/oleh/Documents/us_website/venv/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/oleh/Documents/us_website/venv/lib/python3.10/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/home/oleh/Documents/us_website/venv/lib/python3.10/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() File "/home/oleh/Documents/us_website/venv/lib/python3.10/site-packages/django/urls/resolvers.py", line 480, in check for pattern in self.url_patterns: File "/home/oleh/Documents/us_website/venv/lib/python3.10/site-packages/django/utils/functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/oleh/Documents/us_website/venv/lib/python3.10/site-packages/django/urls/resolvers.py", line 696, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/oleh/Documents/us_website/venv/lib/python3.10/site-packages/django/utils/functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/oleh/Documents/us_website/venv/lib/python3.10/site-packages/django/urls/resolvers.py", line 689, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/oleh/Documents/us_website/us_website/app/urls.py", … -
How to solve 'TemplateDoesNotExist' error in Django 4.2 while running the server?
TemplateDoesNotExist at / home.html Request Method: GET Request URL: http://127.0.0.1:5555/ Django Version: 4.2.1 Exception Type: TemplateDoesNotExist Exception Value: home.html Exception Location: C:\Users\soumy\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\template\loader.py, line 19, in get_template Raised during: geekshows.views.home Python Executable: C:\Users\soumy\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.3 Python Path: ['F:\Django\geekshows', 'C:\Users\soumy\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\soumy\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\soumy\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\soumy\AppData\Local\Programs\Python\Python311', 'C:\Users\soumy\AppData\Roaming\Python\Python311\site-packages', 'C:\Users\soumy\AppData\Local\Programs\Python\Python311\Lib\site-packages'] Server time: Mon, 22 May 2023 13:56:05 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: F:\Django\geekshows\templates\home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\soumy\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\admin\templates\home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\soumy\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\templates\home.html (Source does not exist) django.template.loaders.app_directories.Loader: F:\Django\geekshows\course\templates\home.html (Source does not exist) django.template.loaders.app_directories.Loader: F:\Django\geekshows\fees\templates\home.html (Source does not exist) When I am running server this error is comming. I am using Django 4.2 so how to over come. -
Automatically login to Django app using Microsoft account after logging in to Outlook 365
I have a DJango application called "tools". Then I have a second application called "users" which is for user management. When logging in, you can start both with the username and password, as well as with Microsoft. I have done this with "django-allauth". Works correctly. I want to implement SSO. That is, if I am logged in to "outlook365", when I enter my web page I want to automatically log in without me having to go to the login page. How can I do it taking into account that I already logged in correctly with the microsoft account? I WANT THE USER TO NOT HAVE TO HIT THE "login" BUTTON BUT AUTOMATICALLY WHEN I ENTER "/" THE ACCOUNT IS CONNECTED I understand that it has to be done through cookies, that's why in my view I have this: def home(request): if request.user.is_authenticated: return redirect('main_page') if request.COOKIES.get('OutlookSession'): print ("COOKIES") session_cookie_value = request.COOKIES['OutlookSession'] user = authenticate(request, auth_entry='microsoft', your_cookie_parameter=session_cookie_value) if user is not None: login(request, user) return redirect('main_page') print("No") return render(request, 'home.html') To the console it just prints "No", so it doesn't go into the condition. But if I look in the inspection part -> applications -> cookies I get this: dev-tools.mondragonlingua.com / … -
Calling PostgreSQL stored procedure from Django returns 'invalid input syntax for integer' error - how to solve?
I have this procedure that generates a pdf file with reports from a database. The procedure itself works well. The issue is, when I try to call it from my django application, it doesn't work. cursor.callproc("fun_servidores_folha", (self.storage.entidade.id, self.storage.folha.id, self.request['agrupamento'], 'completo', self.filtros.get('vinculo__in', []), self.filtros.get('lotacao__in', []), self.filtros.get('und_trab_1__in', []), self.filtros.get('und_trab_2__in', []), self.filtros.get('cargo__in', []), self.filtros.get('funcao__in', []), self.filtros.get('marca__in', []), self.filtros.get('cargo__marca__in', []), self.filtros.get('und_trab_1__marca__in', []), self.filtros.get('lotacao__marca__in', []), self.filtros.get('id__in', []))) I get the error: psycopg2.errors.InvalidTextRepresentation: invalid input syntax for integer: "" CONTEXT: função PL/pgSQL fun_servidores_folha(integer,integer,text,text,text[],text[],text[],text[],text[],text[],text[],text[],text[],text[],text[]) linha 621 em RETURN QUERY When debugging, for example, I can try (1, 1, 'lotacao', 'completo', [], [], [], [], [], [], [], [], [], [], []) but it returns the error I mentioned above. Here is the beginning of the procedure file: CREATE OR REPLACE FUNCTION public.fun_servidores_folha( entidade_id integer, folha_id integer, agrupamento text, relatorio text, vinculo__in text[], lotacao__in text[], und_trab_1__in text[], und_trab_2__in text[], cargo__in text[], funcao__in text[], marca__in text[], cargo__marca__in text[], und_trab_1__marca__in text[], lotacao__marca__in text[], id__in text[]) So I'm stuck with this. -
How to annotate Django ORM queryset to calculate date difference excluding weekends?
I have a model 'Order' with two datetime fields 'received_at' and 'delivered_at'. now I need to annotate the queryset to add a field 'delivery_duration' that will hold dates count between received_at and delivered_at, excluding weekends (saturday and sunday). so, if received_at monday and delivered_at same day (monday), the delivery_duration count will be 0. if received_at monday and delivered_at next wednesday, the delivery_duration count will be 2. if received_at friday and delivered_at monday, count will be 1. if received_at friday and delivered_at sunday, count will be 0. if received_at saturday and delivered_at sunday, count will be 0. I could achieve dates count with this code: orders = Order.objects.all().annotate( delivery_duration = ExpressionWrapper( Func(TruncDate('delivered_at') - TruncDate('received_at'), function='EXTRACT', template='%(function)s(DAY FROM %(expressions)s)'), output_field=IntegerField()))) this returns the date counts between 'delivered_at' and 'recieved_at' but including weekends. I need to exlude the weekends (staturday, sunday) from count if that is between the range. -
Is it correct to create uncommitted instances in a Django model manager?
I have two models Element and Group with Element having a FK to Group My instanciation of Element instances is quite complex and so I've created a custom manager. class ElementManager(models.Manager.from_queryset(ElementQuerySet)): def create_element(self, group, **kwargs): # Some logic ... # Create the instance with computed params return super.create(**params) I now want a way to "build" an uncommitted instance to bulk_create multiple Element instances and I wonder where this logic should be located. I could put it in the Manager: class ElementManager(models.Manager.from_queryset(ElementQuerySet)): def build_element(self, group, **kwargs): # Some logic ... # Create the instance with computed params return super.model(**params) def create_link(self, group, **kwargs): self.build_element(group, **kwargs).save() However I feel that is not correct for a Manager to create uncommitted instances since the doc specifies that: "A Manager is the interface through which database query operations are provided to Django models" and .build_element() does not provid "database query operations". Could someone explain to me where this piece of code should be located to respect the Django logic ? -
I am trying to make an app like instagram but when I upload my photos, it shows that the photos are available but the images are not visible
I am trying to make an app like instagram but when I upload my photos, it shows that the photos are available but the images are not visible please help me please help me, I have used livereload but still its not working -
How to put gmail link using gg.gmail icon beside it?
How to add a gmail link beside gg.mail icon i got from https://css.gg/mail and having them be on one class so its dynamic, meaning i can move both the icon and the gmail link at the same time? I tried putting the link tag inside the <span> tag of the icon but it just resulted on the gmail link being inside the icon instead of being beside it. this is what it looks like with the link inside it -
Using Custom Managers in Django Views
Using custom managers in Django Rest Framework I observed I can't use a custom model manager for both ListCreateAPIView and RetrieveUpdateDestroyAPIView at the same time, expect if I used a default manager for one and a custom manager for the other. Please could anyone explain why this happens? Below are my views: class OrderList(generics.ListCreateAPIView): permission_classes = [IsAdmin] queryset = Post.objects.all() serializer_class = PostSerializer class OrderDetail(generics.RetrieveUpdateDestroyAPIView, PostUserWritePermission): permission_classes = [IsAdmin] queryset = Post.customobjects.all() serializer_class = PostSerializer Below is my custom manager: class Orders(models.Model): class CustomObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(status = 'fulfilled') customobjects = CustomObjects() I keep getting the error below whenever I tried to use the custom manager for both views: TypeError: BaseManager.all() missing 1 required positional argument: 'self' -
How can I fix the 'This Edge Function has crashed' error in Next.js 13.4.2 due to middleware.ts file?
This Edge Function has crashed 500 INTERNAL_SERVER_ERROR" in next 13.4.2 app directory I have deployed a next.js 13.4.2 project that has a middleware.ts file in it and all protected routes aren't working due the "This Edge Function has crashed error." TypeError: Invalid URL string. at (vc/edge/function:121:5785) at (vc/edge/function:120:13723) If I remove the middleware.ts file the protected routes work as expected. This is the simple middleware.ts file import { tokenVerifyEndpoint } from "./config" import { NextResponse, NextRequest, NextFetchEvent } from "next/server" export async function middleware(request: NextRequest, event: NextFetchEvent) { const access = request.cookies.get("access")?.value const loginURL = new URL("/auth/login/", request.nextUrl) const dashboardURL = new URL("/dashboard/", request.nextUrl) const authenticated = access === undefined ? false : true event.waitUntil( fetch(`papaya-django.vercel.app/api/token/verify`, { method: "POST", headers: { "Accept": "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ token: access }) }) .then(async (data) => { const response = await data if(response.status === 200){ return authenticated = true } else if (response.status !== 200) { return authenticated = false } }) .catch((error) => { console.error("Error occurred during token verification:", error) authenticated = false }) ) if (!authenticated && !request.nextUrl.pathname.startsWith("/auth")) { return NextResponse.redirect(loginURL) } else if (authenticated && request.nextUrl.pathname.startsWith("/auth")) { return NextResponse.redirect(dashboardURL) } return NextResponse.next() } export const config = { … -
How to resolve 'Method GET not allowed' error when using Django to build REST API for delete file?
I wrote a rest api using Django language, but in the delete part, I got the error "detail": "Method "GET" not allowed."and 405 . I meet please guide me class deletedata(APIView): def delete(self,request,pk): query=database.objects.get(pk=pk) query.delete() return Response(status=status.HTTP_204_NO_CONTENT) and section url urlpatterns = [ path('get-data',getdata.as_view()), path('post-data',postdata.as_view()), path('update-data/<int:pk>/',updatedta.as_view()), path('delete-data/<int:pk>/',deletedata.as_view()), ] -
Django only() and values() are not working with prefetch_related()
I want to filter the fields retrieved in a query and get the reverse foreign key using the related_name in a child model using prefetch_related() for the sake of performance optimization when reaching a huge number of database records. I have the following "Seller" Model: class SellerQuerySet(models.QuerySet): def annotate_seller_salary(self): return self.annotate(seller_salary=F('points')*100) class SellerManager(models.Manager): use_for_related_fields = True def annotate_seller_salary(self): return self.get_queryset().annotate_seller_salary() def get_queryset(self): return SellerReviewQuerySet(model=self.model, using=self._db) class Seller(models.Model): name= models.CharField(max_length=50) points= models.IntegerField(default=0) address= models.TextField(max_length=100) And "Product" Model: class Product(models.Model): name= models.CharField(max_length=50) quantity= models.IntegerField(default=0) seller= models.ForeignKey(Seller, on_delete=models.CASCADE, related_name="seller_products") I'm trying to get all the products grouped by the seller. But the issue is that If I retrieved the products first and then tried to group it by the seller, I will not be able to retrieve the annotation function for the "Seller" model along with it. So, I would need to start by retrieving the "Seller" object with its annotations and then use prefetch_related() and Prefetch() to get the Products using the related_name for the seller foreign key. BUT! The problem is, I don't want to get all the "Seller" model fields. I ONLY need the points field and the annotation attribute seller_salary along with the "Product" objects that are associated with … -
Django's on_commit difference in behavior when triggered via Django admin
I am trying to send api call via transaction.on_commit and it is kind of working but I am seeing a different behavior when I edit the model via Django admin vs when this code is triggered by some other means. I have UserRoles model where I am calling post_save.connect(sync_user_roles, sender=UserRole) then in the sync_user_roles(self, **kwargs) I am calling transaction.on_commit( lambda: self._proc_user_role_sync( kwargs["instance"], pre_edit_users=[u.username for u in kwargs["instance"].users.all()], user_role=user_role, library_id=library_id, ) ) And I am just trying to print new users in the _proc_user_role_sync def _proc_user_role_sync( self, instance: "models.UserRole", pre_edit_users: List[str], user_role: str, library_id: str, ): print(f"new users: {[u.username for u in instance.users.all()]}") Whenever I edit user_roles via Django admin, I see the new state of db in the _proc_user_roles_sync, meaning the newly added user is showing up in the print statement. But whenever I trigger this code by making API call to backend, new user is not showing in the print statement, even though I can see it being stored in the db. What exactly is causing this difference and how can I make sure that the newly added user shows up in the _proc_user_role_sync every time the code is triggered? -
Django registration form not hashing password
I'm building a student management system, but there's a problem. When I register a new user, i enter it's username, first name, last name, etc... and password of course. But when I save the form and insert the user in the database, the password is stored as plain text and not hashed. On the other hand, when I create user thru django admin panel the user password i hashed normally and login works... Here is my code: views.py def addUser(request): if request.method == 'GET': form = AddNewUserForm() return render(request, 'addNewUser.html', {'form': form}) if request.method == 'POST': form = AddNewUserForm(request.POST) if form.is_valid(): password = make_password(form.cleaned_data['password']) form.password = password form.save(make_password(form.cleaned_data['password'])) print("New user added!") return render(request, 'addNewUser.html', {'form': form}) return redirect('/users/') .html <!DOCTYPE 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>Document</title> </head> <body> <form method="POST"> {{form}} {% csrf_token %} <input type="submit" value="Add new user"> </form> </body> </html> -
I could not understand a function for the ManyToMany field listing in Django
Non of the similar questions auto listed answer my question: I have the models.py as follows: ```from django.db import models class Location(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=300) def __str__(self): return f'{self.name} ({self.address})' class Participant(models.Model): email = models.EmailField(unique=True) def __str__(self): return self.email class Meetup(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) description = models.TextField() image = models.ImageField(upload_to='images') location = models.ForeignKey(Location, on_delete=models.CASCADE) participants = models.ManyToManyField(Participant) def __str__(self): return f'{self.title} - {self.slug} - {self.description}'``` In order to be able to list the two emails I entered via the Admin panel I had the following Admin.py ```from django.contrib import admin from .models import Meetup, Location, Participant # Register your models here. class MeetupAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'description', 'location', 'get_emails') def get_emails(self, obj): return "\n".join([p.email for p in obj.participants.all()]) list_filter = ('title', 'description') prepopulated_fields = {'slug': ('title', )} search_fields = ('title', ) admin.site.register(Meetup, MeetupAdmin) admin.site.register(Location) admin.site.register(Participant)``` Without using the function return "\n".join([p.email for p in obj.participants.all()])``` I would not have been able to list the two emails represented by the ManyToMany relation My question here is: I would like to understand what does the p and obj here. I would be so grateful if someone could explain how this work. -
Django signals error with Foreign Keys - post_delete on related objects gets called before pre_delete on the ForeignKey
I have 2 model classes: class Company: name = models.... pending_delete = BooleanField class User: company = ForeignKey(Company, CASCADE) On the pre_delete of Company, I try to set pending_delete to True, so that I can access it when the post_delete signal of User is called because of CASCADE. However, for some reason the pre_delete signal (of Company) runs after the post_delete signal of User. This might be intended but I'm not sure that I understand why.