Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I create a get function that returns data using only the id in Django?
Here we have the views.py file for the favorites model. The favorite model consists of two foreignkeys. One which links the favorites to the user's account, and the other that links it to the property the user favorited. I am trying to write a new get function that returns all of the properties that are favorited by a user using the parameter of the user's account id. The function should return all of the properties that are favorited with that account id. from .models import Favorites from .serializers import FavoritesSerializer from rest_framework import viewsets from rest_framework.views import APIView from rest_framework.response import Response class FavoritesViewSet(viewsets.ModelViewSet): queryset = Favorites.objects.all() serializer_class = FavoritesSerializer class FavoritesGetView(APIView): def get(self, request, id): snippet = Favorites.objects.get(id=id) serializer = FavoritesSerializer(snippet, many=False) return Response(serializer.data) class FavoritesPropertyGet(APIView): def get(): So far, I have tried rewriting the get function under FavoritesGetView but realized that that get function is still required. So now I am trying to write a new get function under FavoritesPropertyGet. -
Ask Django - Nginx Invalid HTTP_HOST header: 'attacker.web'. You may need to add 'attacker.web' to ALLOWED_HOSTS
recently i had this error message in my sentry Invalid HTTP_HOST header: 'attacker.web'. You may need to add 'attacker.web' to ALLOWED_HOSTS. and i saw the request like this curl \ -H "Accept: */*" \ -H "Content-Length: " \ -H "Content-Type: " \ -H "Forwarded: for=\"attacker.web:8888\";by=\"attacker.web:9999\"" \ -H "Host: attacker.web" \ -H "User-Agent: Report Runner" \ -H "X-Forwarded-For: " \ -H "X-Forwarded-Host: mysite.com" \ -H "X-Forwarded-Proto: https" \ -H "X-Real-Ip: " \ "https://attacker.web/subpage/" how do i prevent this kind of request ? and what's the name of the attack ? i've been config my nginx to drop curl request return 444 when the host name doesn't the same with server_name how to deal with this kind of request ? -
How to find subtotal price of all products in shopping cart in django
Cart Model has product,user,quantity and def total_price(self): return self.quantity * self.product.price My Cart html page has cart.product.name, cart.product.price, cart.quantity, cart.total_price How to find the subtotal of all products in cart -
How to use both simple jwt token authentication and BasicAuthentication?
I have an DRF api and I have implemented the simplejwt authentication system. It works well. It is usefull when I want to connect my api from external script (I don't need to store credential and just use the token). However I also want to be able to use the DRF interface login when i reach my api from browser so I have implemented also the Basic and SessionAuthentication. Is it the good way to do that ? in my settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ] } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=1), } in my api views.py from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.decorators import permission_classes, authentication_classes # Create your views here. @api_view(['GET']) #@authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def get_all(request): # as a token is used, the user with this token is know in the requets user = request.user # show only mesures of user having the token provided mesures = Mesure.objects.filter(user_id=user.id) serializer = MesureSerializer(mesures, many=True) return Response(serializer.data) In my urls.py from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView urlpatterns = [ path('mesures/', views.get_all), path('mesure-add/', views.add_mesure), path('token/', TokenObtainPairView.as_view(), name='obtain_tokens'), path('token/refresh/', TokenRefreshView.as_view(), name='refresh_token'), path('api-auth/', include('rest_framework.urls')) ] As you can see I had to comment the @authentication_classes decorator to … -
Move my Django application + Apache to Docker
I am trying to migrate my test app to Docker, but I am always getting the same error, despite of trying many approaches. This is my Dockerfile: FROM python:3.10-slim-buster RUN apt-get update && apt-get install -y apache2 libapache2-mod-wsgi-py3 WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY morabusa /app/ COPY app.conf /etc/apache2/sites-available/app.conf RUN a2dissite 000-default.conf && a2ensite app.conf CMD ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"] This is the app.conf for Apache vHost, which I have simplified a lot, in order to try to find the issue: <VirtualHost *:80> ServerName morabusa.com ErrorLog /app/morabusaprj/logs/error.log CustomLog /app/morabusaprj/logs/access.log combine <Directory /app> Require all granted </Directory> WSGIScriptAlias / /app/morabusaprj/wsgi.py </VirtualHost> This is my wsgi.py file configuration (I have added the import sys, but it still fails): import os import sys sys.path.append('/app') sys.path.append('/app/morabusaprj') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'morabusaprj.settings') application = get_wsgi_application() Traceback: [Wed Feb 08 17:57:56.488523 2023] [wsgi:error] [pid 9:tid 140315142702848] [client 192.168.1.33:60062] mod_wsgi (pid=9): Failed to exec Python script file '/app/morabusaprj/wsgi.py'. [Wed Feb 08 17:57:56.488574 2023] [wsgi:error] [pid 9:tid 140315142702848] [client 192.168.1.33:60062] mod_wsgi (pid=9): Exception occurred processing WSGI script '/app/morabusaprj/wsgi.py'. [Wed Feb 08 17:57:56.488622 2023] [wsgi:error] [pid 9:tid 140315142702848] [client 192.168.1.33:60062] Traceback (most recent call last): [Wed Feb 08 17:57:56.488633 2023] [wsgi:error] [pid 9:tid 140315142702848] … -
TheCurrentPath...DidntMatch Django
"I am encountering the error 'The current path, say/welcome/, didn’t match any of these' while trying to access a certain URL in my Django application. I have checked my URL patterns in my app's urls.py file, and there doesn't seem to be a typographical error in the URL. [[enter image description here](https://i.stack.imgur.com/gazLZ.png)](https://i.stack.imgur.com/4bPSK.png) I am not sure what is causing this error, and I would like to resolve it so that I can access the desired URL. Can anyone help me figure out what's causing this error and provide a solution? -
How can i make models in django with form input
I Want to make a backend service website, for that I am working in django and want to make django models but with form input, if a user create a table in my frontend I want to create a table or model in data base how can i do it? Hello stackies , I Want to make a backend service website, for that I am working in django and want to make django models but with form input, if a user create a table in my frontend I want to create a table or model in data base how can i do it? -
Running Django in IIS
I have a Python application that's that has been working correctly as backend for my website, up to now I have been running it using "python manage.py runserver IP:8000" in CMD. However I would like it to start using HTTPS, but when I try to access through my browser on https://IP:PORT I get the following error: You're accessing the development server over HTTPS, but it only supports HTTP. The server I am running all of this is a Windows Center 2019 DataCenter, normally on a linux environment I would just use NGINX+GUNICORN. I was browsing possible solutions and stumbled upon this, however I already am using IIS to host a website (My frontend), so I needed to figure out how to host several websites for the same IP, I have now found this. Long story short, I configured the new IIS website for it to access my django, I then changed the hostname since both frontend and the new backend will using the same ip and ports (80, 443). But now I have hit a spot where I'm confused due to my lack of experience in IIS and networking. I can't seem to understand how the request will go through … -
How create task with celery in django ? POO issue?
I'm trying to set up a task with Django and Celery. The Celery and Django configuration is okay, nothing to report on that side. However, I have a problem, I think with the writing, of my code in OOP. I can't locate where the problem is. It's an argument problem, 4 arguments are expected by delay(), but my method only expects 3. Here are the files and what I tried to do, as well as the error trace. My files helpers.py i want create a task for run_test_optimization method class MachineLearniaXHelpers(MagicModels): def __init__(self, data_dict, target_name, type_model, test_size = 0.33, random_state = 42, **kwargs) -> None: super().__init__() self.test_size = test_size self.random_state = random_state self.process = DataProcessor( data=data_dict, target_name=target_name ) self.metrics = MetricsScorer(type_model=type_model) self.model = self.several_algorythme(type_model, **kwargs) @staticmethod def split_data(data_dict): return train_test_split(*data_dict) @staticmethod def train_model(model, X, y): model.fit(X, y) def run_test_optimization(self): dict_result = [] for model in self.model: feature_model, values = self.process.transform_dict_to_array_structure() x_train, x_test, y_train, y_test = self.split_data(values) self.train_model(model, x_train, y_train) dict_metrics_train = self.metrics.choice_metrics_by_type_model(y_train, model.predict(x_train)) dict_metrics_test = self.metrics.choice_metrics_by_type_model(y_test, model.predict(x_test)) dict_result.append({ "name_model" : model.__class__.__name__, "features_model" : feature_model, "train_performances" : dict_metrics_train, "test_performances" : dict_metrics_test }) return dict_result tasks.py create my task task_run_test_optimization from celery import shared_task from .helpers import MachineLearniaXHelpers @shared_task def task_run_test_optimization(data_dict, target_name, … -
How to connect Python Django to Informix DB on a remote Windows Server
I need to connect my Django app to the Informix db I have an Informix db installed on a VM Windows server 2019 Datacenter I can access the db through dbvisualiser on my laptop I installed the Informix client SDK on my laptop in the Programs Files directory I tried this settings https://pypi.org/project/django-informixdb/ **In my settings.py ** DATABASES = { 'default': { 'ENGINE': 'django_informixdb', 'NAME': 'testdb', 'SERVER': "ol_test", 'HOST': '172.20.10.3', 'PORT': '9092', 'USER': 'informix', 'PASSWORD': 'test@12345', 'OPTIONS': { 'DRIVER': "C:\\Program Files\\IBM Informix Client-SDK\\bin\\iclit09b.dll", # Or iclit09b.dylib on macOS 'Setup': "C:\\Program Files\\IBM Informix Client-SDK\\bin\\iclit09b.dll", 'CPTIMEOUT': 120, 'CONN_TIMEOUT': 120, 'ISOLATION_LEVEL': 'READ_UNCOMMITTED', 'LOCK_MODE_WAIT': 0, 'VALIDATE_CONNECTION': True, }, 'CONNECTION_RETRY': { 'MAX_ATTEMPTS': 10, }, 'TEST': { 'NAME': 'testdb', 'CREATE_DB': False } } } I got this error C:\Users\test\PycharmProjects\bdm_reporting_app\bdm_reporting_app\settings.py changed, reloading. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\test\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\bas e.py", line 282, in ensure_connection self.connect() File "C:\Users\test\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", l ine 26, in inner return func(*args, **kwargs) File "C:\Users\test\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\bas e.py", line 263, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\test\AppData\Local\Programs\Python\Python310\lib\site-packages\django_informixdb\base.py", line 251, in get_new_connection self.connection = self._get_connection_with_retries(connection_string, conn_params) File "C:\Users\test\AppData\Local\Programs\Python\Python310\lib\site-packages\django_informixdb\base.py", line 299, in _get_connection_with_retries conn = pyodbc.connect(connection_string, autocommit=conn_params["AUTOCOMMIT"], pyodbc.InterfaceError: ('IM002', … -
Unable to Pass Django Context Data to HTML View
Can anybody please tell me how I can pass context data to view. I get nothing in HTML page. views.py def cart(request): if request.method == 'POST': return redirect('index') else: if request.method == 'GET': # Recieve local storage product in post_id varibale post_id = request.GET.get('get_cart') cat_product = Product.objects.filter(id=.11) if post_id is not None: # Fomrat and remove { } and " from post_id string post_id = post_id.replace('{','') post_id = post_id.replace('}','') post_id = post_id.replace('"','') print("The Id is", post_id ) # Find ':' in string and get the value of id in cart_prod_index index =0 while index < len(post_id): index = post_id.find(':', index) if index == -1: break local_storage_prod_id = post_id[index-1] # '|' operator is used to append the queryset result cat_product = cat_product | Product.objects.filter(id=local_storage_prod_id) index+=2 print(cat_product) return render(request, "cart.html" ,{"x":cat_product,}) In cart.html {% for search in x %} {{search.name}} {% endfor %} Please tell How I can get my query set in HTML page -
I wanted to craete a 5 star rating system in django but it keeps getting this error:
i check with django document and But my problem was not solved [08/Feb/2023 15:57:18] "POST /courses/2/learning-django HTTP/1.1" 403 2506 error: Forbidden (CSRF token missing.): /courses/2/learning-django this is my models class Review(models.Model): course = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='reviews') first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) rating = models.IntegerField(null=True, validators=[MinValueValidator(1), MaxValueValidator(5)]) comment = models.TextField() created = models.DateField(auto_now_add=True) active = models.BooleanField(default=False) def __str__(self): return f'{self.first_name} {self.last_name} my views: def productDetailView(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) new_comment = None if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.course = product new_comment.rating = request.POST['rating'] new_comment.save() else: form = ReviewForm() return render(request, 'shop/product_detail.html', {'product': product, 'form': form}) js function: $(document).ready(function(){ $('.rate .rate-item').on('click', function(){ var value = $(this).data('value'); $.ajax({ url: '{{ product.get_absolute_url }}', type: 'POST', data: {'rating': value}, success: function(response){ alert('Rating saved successfully!'); } }); }); }); my template <form method="post"> <div class="row"> <div class="col-md-6"> <div class="form-singel"> {{ form.first_name|attr:" placeholder:Fast name" }} </div> </div> <div class="col-md-6"> <div class="form-singel"> {{ form.first_name|attr:" placeholder:Last Name"}} </div> </div> <div class="col-lg-12"> <div class="form-singel"> <div class="rate-wrapper"> <div class="rate-label">Your Rating:</div> <div class="rate"> <div data-value="1" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="2" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="3" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="4" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="5" class="rate-item"><i … -
How to get identityToken from apple account?
I want to create "Sign in with apple" function and using for this drf-social-oauth2. Does anyone knows how to get identityToken from apple account for testing, for example google has OAuth2 playground? Should I create apple developer account? -
Unable to proxy Shiny using Django and Nginx (HHTP Response Code 101)
I am trying to use Nginx and Django to help me serve Shiny applications within my company's internal servers. I am testing everything locally first to make sure all is working properly. I am following two tutorials: https://pawamoy.github.io/posts/django-auth-server-for-shiny/#proxying-shiny-requests-to-the-shiny-app https://testdriven.io/dockerizing-django-with-postgres-gunicorn-and-nginx I started with the testdrive.io post to setup Django and Nginx and then combined the ideas with pawamoy's blogpost to setup the Shiny part. The final setup: Django app is listening on 8000 Shiny on 8100 Nginx is 1337 (as per testdriven.io tutorial). My final nginx conf file looks like this: upstream django_app { server web:8000; } upstream shinyapp_server { server shiny:8100; } map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; server_name localhost; client_max_body_size 100M; location / { proxy_pass http://django_app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; # proxy_pass http://django_app; if (!-f $request_filename) { proxy_pass http://django_app; break; } } location /static/ { alias /home/app/web/staticfiles/; } location /media/ { alias /home/app/web/mediafiles/; } location ~ /shiny/.+ { # auth_request /auth; rewrite ^/shiny/(.*)$ /$1 break; proxy_pass http://shinyapp_server; proxy_redirect http://shinyapp_server/ $scheme://$host/shiny/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_read_timeout 20d; proxy_buffering off; } # location = /auth { # internal; # proxy_pass http://django_app/shiny_auth/; # proxy_pass_request_body off; # proxy_set_header … -
HOW CAN I VIEW PDF FILES FROM AN API WITH VUE JS
Hello friends I need your support.. I am currently developing an app with django rest framework in the backend and vue js in the frontend.. the app consists of saving pdf files, which I can list in a table.. but the problem is that it only I can see by table the path where they are saved and I have not been able to view the files. Can someone tell me how I can place a button to view these files? I have tried functions to download the files but I have not achieved a solution -
Authentication with Microsoft Azure AD in a multi-tenant app
Following the documentation, registered an application with Accounts in any organizational directory. The Tenant where the application resides is in "Default Directory" and has only one user, tiagomartinsperes@gmail.com. Also, the app has user assignment (as pointed out here) set to No After, created another Tenant (different directory) and invited the external user me@tiagoperes.eu. That's the user I'm getting troubles logging into the previously created app. Then, enable the OAuth2 support using social_core.backends.azuread.AzureADOAuth2 (from here). As I try to authenticate now, it works well with tiagomartinsperes@gmail.com but with me@tiagoperes.eu gives the following error Selected user account does not exist in tenant 'Default Directory' and cannot access the application 'a9a22676-8a1c-4297-95d3-8cd89553220e' in that tenant. The account needs to be added as an external user in the tenant first. Please use a different account. -
How do I affect a single looped element in Django html?
I'm building an app in Django, using Bulma for styling. I have a Polishes model that has a favorites field, which references the User (users can save polishes to their list of favorites): models.py: class Polish(models.Model): name = models.CharField(max_length=100) image = models.CharField(max_length=400, default="https://www.dictionary.com/e/wp-content/uploads/2018/02/nail-polish-light-skin-tone.png") brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name='polishes') favorites = models.ManyToManyField(User, related_name='favorite', default=None, blank=True) def __str__(self): return self.name The add_favorites function checks to see if the polish has been added to the user's favorites already, and if it has, it removes the polish from the list. If it hasn't, it adds it: views.py: @ login_required def add_favorite(request, id): polish = get_object_or_404(Polish, id=id) if polish.favorites.filter(id=request.user.id).exists(): polish.favorites.remove(request.user.pk) else: polish.favorites.add(request.user.pk) return redirect('favorites_list') When I render the list of polishes, I'm using Bulma cards, displaying one polish per card. In the footer of the card, I want it to say 'Save to Favorites' if the polish is not in the user's list of favoties and 'Remove from Favorites' if it is. I'm struggling to get this piece to work. It will currently show either Save to Favorites or Remove from Favorites on all of the cards. Does anyone have any insight on how to render a different message only on those that are already … -
Django: TemplateSyntaxError - Could not parse the remainder
Exception Value: Could not parse the remainder: '['image/jpeg',' from '['image/jpeg',' Why am I getting this TemplateSyntaxError for the code below? {% for file in resource.files.all %} {% if file.file.content_type|lower in ['image/jpeg', 'image/png', 'image/gif'] %} <a class="resource-image" title="{{ file.id }}" href="{{ file.file.url }}"> <img width="100%" src="{{ file.file.url }}" alt="{{ file.id }} Image"/> </a> {% elif file.file.content_type|lower in ['video/mp4', 'video/wmv', 'video/mkv', 'video/x-flv', 'video/webm', 'video/mpeg'] %} <video width="100%" controls> <source src="{{ file.file.url }}"> </video> {% elif file.file.content_type|lower in ['audio/mp4', 'audio/m4a', 'audio/wav', 'audio/x-wav', 'audio/ogg'] %} <audio width="100%" controls> <source src="{{ file.file.url }}"> </audio> {% elif file.file.content_type|lower in ['application/pdf'] %} <!-- <embed src="{{ file.file.url }}" width="800px" height="2100px" /> --> {% endif %} <p class="small text-muted">{{ file.id }}</p> {% endfor %} I've checked the entire template file, and all the brackets are balanced. I can't find any syntax errors. -
Button function works randomly
so basically I am working on a flask app and everything is going well except one thing. I don't know why but my delete button works very randomly, sometimes on the second click, sometimes on the third click. Also I am very new to this website so I don't really know how to put a snippet but here's my code My html <section id="reponses" class="saisirReponse"> {% for i in range(2) %} <div class="elementReponse" id="{{'elementReponse'+((i+1)|string)}}"> <input type ="checkbox" name="{{'checkbox'+((i+1)|string)}}"/><span class="checkmark"></span> <textarea area-required="true" name = "{{'rep'+((i+1)|string)}}"></textarea> <button class = "bouttonSUPP" name="{{'btn'+((i+1)|string)}}" type="button" id="{{'btn'+((i+1)|string)}}" onclick="supp();">SUPP</button> </div> {% endfor%} </section> <input id="nb_quest" type="text" name="nb_quest" value="2"> <button class="bouttonLong" id="addDiv" type="button">Nouvelle réponse</button> Here's my function to add a response input (with seems to work well) (function (d) { "use strict"; d.querySelector("#addDiv").addEventListener("click", addDiv); function addDiv() { var p = d.createElement("div"); var x = d.createElement("INPUT"); var z = d.createElement("TEXTAREA"); var btn = document.createElement("BUTTON"); var t = document.createTextNode("SUPP"); var y =parseInt(document.getElementById("nb_quest").value)+1; x.setAttribute("type", "checkbox"); z.setAttribute("type", "text"); btn.appendChild(t); btn.name = "btn"+ y; btn.id = "btn"+ y; btn.setAttribute("class", "bouttonSUPP") p.setAttribute("class", "elementReponse"); btn.type = "button"; btn.setAttribute("onclick","supp();"); x.name = "checkbox" + y; x.id = "checkbox" + y; p.id = "elementReponse" + y; z.name = "rep" + y; z.id = "rep" + y; z.required = … -
Change color of a field in a table depending on how much time is left for the user to pay with Django
I am trying to change the color of a field in a table depending on how much time is left for the user to pay, if there are 7 days to pay it should change to yellow and if it is already the date of payment or already had to have paid it should change to red, the one that changes to red I got it, but I can't get it to change to yellow when there are 7 days to pay. This is my model and the def class payments (models.Model): client = models.OneToOneField(HealthQuests, on_delete=models.CASCADE, null=True, blank=True, verbose_name= 'Cliente') date = models.DateField(default=datetime.date.today, verbose_name= 'Fecha de facturación') payment_date = models.DateField(default=datetime.date.today, verbose_name= 'Fecha de pago') amount = models.FloatField(verbose_name='Monto de pago', default=0) def payment_yellow (self): return date.today() - payments.payment_date def payment_red (self): return date.today() And my html and the if <tbody> {% for obj in object_list %} <tr> <td><a href="update_payments/{{ obj.id }}" class="btn">{{ obj.client }}</a></td> <td>{{ obj.date }}</td> <td> {% if obj.payment_date <= obj.payment_red %} <div class="p-3 mb-2 bg-danger text-white">{{ obj.payment_date }}</div> {% elif obj.payment_yellow >= 7 %} <div class="p-3 mb-2 bg-warning text-white">{{ obj.payment_date }}</div> {% else %} {{ obj.payment_date }} {% endif %} </td> <td>{{ obj.amount }}</td> </tr> {% endfor %} … -
Django model foreign key cascade will not trigger delete
there two basic ways to do something when an instance gets deleted: Overwrite Model.delete Signal I used to reckon both of them serve the same purpose, just provides different ways of writing, but works exactly. However, in this occasion, I realise I was wrong: class Human(models.Model): name = models.CharField(max_length=20) class Pet(models.Model): name = models.CharField(max_length=20) owner = models.ForeignKey(Human, related_name="pet", on_delete=models.CASCADE) def delete(self, *args, **kwargs): print('------- Pet.delete is called') return super().delete(*args, **kwargs) h = Human(name='jason') h.save() p = Pet(name="dog", owner=h) p.save() h.delete() # nothing is shown Why Pet.delete Is not firing at Human.delete By the foreign cascade? Does I have to apply a signal on this? If so, would it cost more performance? I am building something very heavy, comment system, filter decent records and delete when the commented target get deleted, the comment model has many null-able foreign key fields, with models.CASCADE Set, only one of them is assigned with value. But in product delete view, I call product.delete Then triggers cascade, but comment.delete Is not firing. -
django template -TemplateSyntaxError
I am a beginner in Django world. When I try render my login.html template I'm facing this problem even there is a closing block. TemplateSyntaxError at /login/ Invalid block tag on line 12: 'else', expected 'endblock'. Did you forget to register or load this tag?` Here is my template {% extends 'base.html' %} {% block content %} {% if not request.user.is_authenticated %} <div style="margin-top: 30px"> <form method="POST"> {% csrf_token %} {% if error %} <p style="color: red">{{error}}</p> {% endif %} <div> <input type="text" name="username" placeholder="username" /> </div> <div> <input type="password" name="password" placeholder="password" /> </div> <button type="submit">Login</button> </form> </div> {% else %} <p> You're already logged in. Would you like to <a href="/logout/"> logout?</a> </p> {% endif %} {% endblock content%} -
Error instaling mysql : "metadata-generation-failed"
I am trying to install mysql on my virtual enviroment for DJango. I already have installled the conector: pip install mysql_connector Requirement already satisfied: mysql_connector in /home/djangoProject/my_env/lib/python3.8/site-packages (2.2.9) But, when I try to install mysql, I get an error: pip install mysql Collecting mysql Using cached mysql-0.0.3-py3-none-any.whl (1.2 kB) Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-1calve35/mysqlclient_8e8e5f7eb5c3471ab86bc7c3c2a339d7/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-1calve35/mysqlclient_8e8e5f7eb5c3471ab86bc7c3c2a339d7/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-1calve35/mysqlclient_8e8e5f7eb5c3471ab86bc7c3c2a339d7/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. … -
Django-select2 not loading css maybe or just form looks bad
I downloaded and configured django-select2 and for some reason it looks disgusting not like it should be I check all settings and everything should be all right I guess its just some css files are not loading but in terminal everything`s good forms.py class WorkLogForm(forms.ModelForm): worklog_date = forms.DateField(label='Дата', widget=forms.DateInput( attrs={'type': 'date', 'class': 'form-control', 'placeholder': 'Введите дату'})) description = forms.CharField(label='Описание', widget=forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Описание'})) contractor_counter = forms.ModelChoiceField( queryset=CounterParty.objects.all(), empty_label='', widget=ModelSelect2Widget( model=CounterParty, search_fields=['name__icontains'], ) ) contractor_object = forms.ModelChoiceField( queryset=ObjectList.objects.all(), widget=ModelSelect2Widget( model=ObjectList, search_fields=['name__icontains'], ) ) contractor_section = forms.ModelMultipleChoiceField( queryset=SectionList.objects.all(), widget=ModelSelect2Widget( model=SectionList, search_fields=['name__icontains'], ) ) class Meta: model = WorkLog fields = ( 'worklog_date', ) template.html {{ form.media.css }} <style> input, select { width: 100% } </style> <div class="container"> <form action="{% url 'home' %}" method="post"> {% csrf_token %} <div class="container mt-5"> {{ form.as_p }} </div> <button type="submit">Создать</button> </form> </div> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> {{ form.media.js }} -
ViewSet class variable
Now I have the following logic implemented for a GET request in Django Rest Framework: class SomeViewSet(mixins.ListModelMixin, GenericViewSet): count = None def get_queryset(self): query_set = ... # some_logic self.count = query_set.count() return query_set def list(self, request, *args, **kwargs): response = super().list(request, *args, **kwargs) response.data = {'count': self.count, 'data': response.data} return response That is, the queryset is calculated according to complex logic, and it may contain a different number of objects that need to be returned in a GET request, since I don’t have access to the query_set variable inside the list function and I don’t want to copy the query_set calculation logic, I decided do it with a class variable. But still, the feeling that this is not very correct does not leave. What other options are there?