Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass Django template language variables to JavaScript files
The question is partially related to this one here. In addition it should be noted that the notation used below is no safe. For more details see this blog post. I have a Django project that references multiple JS files. Initial the contents of those files were in the HTML but it slowly became too cluttered. The problem is that inside these files I am referencing image files, which are used for creating button elements (in my case easyButton instances from Leaflet). I am looking for a way to somehow fix these references. Note that I have called collectstatic and my HTML is using {% load static %} to load the static content. My JS files are also defined as Django template language variables themselves. I am thinking of perhaps at least loading all the references to the static files inside the HTML and then using those inside my JS files. Here is an example code: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="Content-Type" content="text/application/html; charset=iso-8859-1"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="shortcut icon" href="#" /> <title>Test</title> </head> <body> ... </body> </html> <script> const TEST = {{ test }}; // The 'test' variable unwraps … -
Django queryset show english translations
This is my Django models.py: from django.db import models class Blog(models.Model): pub_date = models.DateTimeField('date published') def __str__(self): return self.pub_date class LanguagesCode(models.Model): code = models.CharField(max_length=5) def __str__(self): return self.code class BlogTranslation(models.Model): name = models.CharField(max_length=250) content = models.TextField(blank=True, null=True) blog_id = models.ForeignKey(Blog, related_name='translations', on_delete=models.CASCADE) language_code = models.ForeignKey(LanguagesCode, related_name='languages', on_delete=models.DO_NOTHING) class Meta: unique_together = ('blog_id', 'language_code') def __str__(self): return self.name I want to show the list of blogs those have english translation, with name in english. How do I need to write my query to get this data: [ { "name": "1st Blog name in english", "content": "content in english", "pub_date": "XXX" }, { "name": "2nd Blog name in english", "content": "content in english", "pub_date": "XXX" }, ] I use Django 4 with Django Rest Framework. This is my best try, which doesn't give me the result I want: Blog.objects.filter(translations__language_code = 2) -
Having both .filter() on query_param and .all() functionality without adding another ViewSet and end-point
I'm trying to avoid making another end-point to handle this query, but thinking there isn't a way around it. Wanted to run it by ya'll before doing so. Basically, I have Documents related to Customers and Products. I want to retrieve only the Documents for a specific Customer and Product. Here are the views.py: class DocumentsViewSet(viewsets.ModelViewSet): filter_backends = [StrictDjangoFilterBackend] filterset_fields = [ 'id', 'filename', ] queryset = Documents.objects.all() serializer_class = DocumentsSerializer class DocumentToCustomerViewSet(viewsets.ModelViewSet): filter_backends = [StrictDjangoFilterBackend] filterset_fields = [ 'id', 'customer_id', 'document_id' ] queryset = DocumentToCustomer.objects.all() serializer_class = DocumentToCustomerSerializer class DocumentToProductViewSet(viewsets.ModelViewSet): filter_backends = [StrictDjangoFilterBackend] filter_fields = [ 'id', 'product_id', 'document_id' ] queryset = DocumentToProduct.objects.all() serializer_class = DocumentToProductSerializer I'm thinking I can do something like this shorthand: class DocumentsViewSet(viewsets.ModelViewSet): filter_backends = [StrictDjangoFilterBackend] filterset_fields = [ 'id', 'filename' ] queryset = Documents.objects.filter(document_to_product__product_id=id, document_to_customer__customer_id=id) serializer_class = DocumentsSerializer Which does seem to work when I tested it. But then it I think I'd need to make another end-point to accommodate both the .all() and .filter()... I think. Additionally, haven't been able to get the filter_fields = [] to work with the relationship either. Trying to do something like /api/documents/?customer_id=123&product_id=123. I get a: TypeError: 'Meta.fields' must not contain non-model field names: Here are the models … -
Why doesn't my article send after I wrote two mixins?
I have written a view to send my form, but I had to level users, so I wrote two mixins, but now my author user can't send an article. View: from .mixins import FieldsMixin, FromValidMixin class ArticleCreate(LoginRequiredMixin, FromValidMixin , FieldsMixin , CreateView): model = Article template_name = "registration/article-create-update.html" Mixins: from django.http import Http404 class FieldsMixin(): def dispatch(self, request, *args, **kwargs): if request.user.is_superuser: self.fields = ["author" ,"title" , "slug" , "category" , "description" , "thumbnail" , "publish" , "status"] elif request.user.is_author: self.fields = ["title" , "slug" , "category" , "description" , "thumbnail" , "publish" , "status"] else: raise Http404("You can't see this page") return super().dispatch(request, *args, **kwargs) class FromValidMixin(): def form_valid(self, form): if self.request.user.is_superuser: form.save() else: self.obj = form.save(commit=False) self.obj.author = self.request.user self.obj.status = 'd' return super().form_valid(form) -
How do I not be placing login_required() in each of my views AND Place for all without having to write it in each one Python (Django)
Ej: **Quiero saber si hay alguna forma de indicarle a login_required algunas vistas en especificas sin tener que hacer esto en cada una Gracias ** ` @login_required() def vista1(request): pass @login_required() def vista2(request): pass @login_required() def vista3(request): pass @login_required() def vista4(request): pass @login_required() def vista5(request): pass ` algo Asi: nose si exista esa posibilidad ` login_required(vista1,vista2,vista3...etc) ` -
Acces static files in javascript on django
i am bilding a online music player from scrach and i moved to django . but i cant change my music from my js file like music.src = "{% static 'music/music.mp3' %}:" and i am loading the static files to , how can i accces the my music folder from inside the js file , btw my js and music are in the same static folder i have the music folder then the assets folder where my js files are . or can i just use music.src = "music/music.mp3" i loaded the files with {% load static %} and tryed to load the files with music.src = "{% static 'music/music.mp3' %}" but no results -
The calculated field on my django admin page is returning the average grade for the wrong column
I'm trying to add a computed column to one of my models on the admin page, specifically adding an average mark from a foreign key in my Mark model, and adding it to the relevant Student in my student model. When I run an aggregate avg command within my StudentAdmin class, it returns the average of the grades id field, not the mark field. Here is the relevant code: models.py class Student(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) def __str__(self) -> str: return self.last_name class Meta: ordering = ['last_name'] class Module(models.Model): module = models.CharField(max_length=255) class Grade(models.Model): mark = models.PositiveSmallIntegerField(null=True) module_id = models.ForeignKey(Module, on_delete=models.PROTECT) student_id = models.ForeignKey(Student, on_delete=models.PROTECT) def __str__(self) -> str: return self.mark ... admin.py ... @admin.register(models.Student) class StudentAdmin(admin.ModelAdmin): list_display = ['id', 'first_name', 'last_name', 'average_grade'] def average_grade(self, student): return student.average_grade def get_queryset(self, request): return super().get_queryset(request).annotate( average_grade = Avg('grade') ) How do I specify which column from Grade to use? -
how can I change a button value to remove from cart if product is already in session
I been trying to changing the button add to cart to remove from cart if it happens that products is in session. This is the template: products.html ... <div id="products-list" class="grid grid-cols-4 gap-4"> {% for product in products %} <div class="card"> <div class="image-container"> <img class="img" src="{% static product.image %}" alt="Card image cap"> </div> <div class="container"> <h5 class="card-title">{{ product.product_name }}</h5> <p class="card-text">{{ product.description }}</p> <p class="card-text">Price - &#8358;{{ product.price }}</p> <form action="{% url "add-cart" %}" method="POST"> {% csrf_token %} <input type="hidden" name="product_id" value= "{{ product.id }}"> from here is where I have problems. I am trying to put an if condition that changes the value of the button e.g if product is in session it will show the remove from cart button, else it will show the add to cart button. {% comment %} {% if {{ request.session.stored_item }} %} {% endif %} {% endcomment %} {% comment %} document.getElementById("btn-green").addEventListener("click", function() { document.getElementById("btn-green").innerText = "remove from cart" }) {% endcomment %} </form> </div> </div> {% endfor %} # views.py # def products(request): # stored_items = request.session.get("stored_items") # product_item = Product.objects.filter(id__in=stored_items) products = Product.objects.all() if 'query' in request.GET: query = request.GET['query'] multiple_q = Q(Q(product_name__icontains=query) | Q(description__icontains=query)) products = Product.objects.filter(multiple_q) # products = … -
InMemoryUploadedFile Django File Read in Bytes - str vs utf8
I'm looking to read the binary content of a Django type InMemoryUploadedFile. The file type/encoding is a variable, so I don't want to assume UTF8, I simply want to read the binary content, then I want to encode with UTF8. Here's what I've tried: str(file.read()).replace('\n', '\r\n') This looks to work, except the string still has the binary 'b' character. To fix this, I tried: file.read().decode('utf8').replace('\n', '\r\n') This works well for reading .txt files. Any other file types fail to read properly, understandably. How can I read the binary content of type "InMemoryUploadedFile" without specifying an encoding? -
{%static %} the page displays the line itself {%load static %} instead of loading the desired file
I wanted to connect a css file to this html file, I wanted to add it via {%load struct%} `{% load static %} <!DOCTYPE html> <html lang="ru"> <head> <title>Brewtopia Cafe form</title> <meta charset="UTF-8"> <link rel="stylesheet" href="{% static 'css/style_contact.css' %}"> </head> <body> <header>` this is urls.py in the app `from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.Brewtopia_view, name='brewtopia'), path('Contact/', views.Contact_view, name='contact') ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ` these are views.py in the app `from django.shortcuts import render def Brewtopia_view(request): return render(request, 'Brewtopia.html') def Contact_view(request): return render(request, 'Contact.html') ` settings.py settings in static `STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ]` the css file is located in the folder C:\Projects\brew\brewtopia\users\static\users\css I added struct and wanted to upload a css file, but the error is in the screenshot enter image description here but even if you delete {%loadstruct%} it won't work -
When the checkbox is checked then immediately get the result in Django
This is my View.py def weight(request): selected_values = request.GET.get('selected_values[]') p = Product.objects.filter(load = selected_values) context = {'prod_fil_by_weight':p} return render(request, 'product-filter.html', context) This is my Template I just want to render the data on same html template. `<div class="checkbox"> {% for w in weight %} {{ w.name }} {% for n in prod_fil_by_weight %} <h5>{{ n.name }}</h5> <h5>{{ n.price }}</h5> <h5>{{ n.old_price }}</h5> <h5>{{ n.image.url }}</h5> <h5>{% endfor %} {% endfor %}` This is my AJAX which I was Created. <script type="text/javascript"> $(document).ready(function() { $('.myCheckbox').change(function() { var selectedValues = []; $('.myCheckbox:checked').each(function() { selectedValues.push($(this).val()); }); $.ajax({ url: "/weight/", data: { 'selected_values[]': selectedValues }, success: function(response) { $('#data-container').html(response.result); } }); }); }); </script> I just want to get immediate result and render the data in the same template. when the checkbox is checked no matter only one checkbox is checked or multiple checkboxes is checked I just want the data get and render to the same template (Most of the website use this feature like when you check the checkbox then immediately you get the result without redirecting any other page. the feature name is Real Time Feedback if I am right). I research a lot but I fail my last hope is … -
how i can fix an smtp error in Django im using gmail
i have this error this morning after a year using it. Anyone knows how i can fix this?Error here I was looking for a solution but i cant find anything -
Fast CGI Handler not installed in Windows IIS
I am trying to run a Django app with IIS server. Here are my settings: Windows Server 2019, IIS 10.\ I am following this tutorial. I am setting up my server and added CGI as shown in the image. enter image description here But, when i deploy the app, i get an error saying that the "FastCgiModule" is not in the list. enter image description here I looked in HandlerMappings to find that the FastCgiModule was indeed not in the list of modules that IIS considers. Help and understanding about this is much appreciated. Things tried Added wfastcgi.exe path to the system path. Expectation: In case that was the reason FastCGI wasn't being built, this would fix it. Result: No change. Installed ASP.net and .NET frameworks. Expectations: If these are dependencies for the FastCGI framework, it might help install it. Result: No change. -
Django Rest Framework - Data is Not Refreshed from Table When Inserted directly from Oracle
When I am manually inserting some records from Oracle directly, it is not refreshed from my Django Rest API application. Only the data that is inserted from POST request from the application is shown in the GET requests. I can see all the rows in the oracle table but it is not showing up in django application. I have created this table from Django itself by migrating all the changes. How can I refresh the queryset to ensure it fetches all the table records no matter where the data was inserted from? Below is my code: Model: class Genre(models.Model): genre_id = models.AutoField(primary_key=True) genre_name = models.CharField(max_length=60) def __str__(self): return self.genre_name class Meta: db_table = "GENRE" Serializer: class GenreSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = "__all__" ViewSet: class GenreViewSet(viewsets.ModelViewSet): queryset = Genre.objects.all() serializer_class = GenreSerializer -
Slow "waiting for server response" in django-plotly-dash
I have a django project that includes many dash apps through django-plotly-dash. I noticed a strange increase in callback update latency recently and cannot identify the cause. I put together a simple dash app with three sequential callbacks below as an example. When I run the app locally in my main project, each callback takes about 500 ms to run. When I run the same app in a brand new django project, each callback only takes 50 ms to run. Looking at the performance monitor in my browser, the difference appears to be in the dash_renderer js "waiting for server response." Is there a way to identify what is happening for the server to respond quickly in one django project versus another? views.py: from django.shortcuts import render from . import lightning def thunder(request): return render(request, 'dpd/thunder.html') lightning.py (the dash app): from dash import dcc, html from dash.dependencies import Input, Output from django_plotly_dash import DjangoDash app = DjangoDash('lightning', external_stylesheets=['https://codepen.io/chriddyp/pen/bWLwgP.css']) app.layout = html.Div([ dcc.Input( id='x0', type='number', value=0 ), html.Table([ html.Tr([html.Td(['x+1']), html.Td(id='x1')]), html.Tr([html.Td(['x+2']), html.Td(id='x2')]), html.Tr([html.Td(['x+3']), html.Td(id='x3')]), ]), ]) @app.callback( Output('x1', 'children'), Input('x0', 'value') ) def callback1(x): return x+1 @app.callback( Output('x2', 'children'), Input('x1', 'children') ) def callback2(x): return x+1 @app.callback( Output('x3', 'children'), Input('x2', 'children') … -
Hola tengo un error con el admin de django en jazzmin [closed]
Cuando entro a una aplicacion en la tabla me aparece con este bug y no se como solucionarlo enter image description here necesito ayuda lo antes posible -
About the URL.createObjectURL
I am a beginner in django with python, there is a problem i confronting now is that I have a image URL e.g. "http://127.0.0.1:8000/media/images/user_1/XXXX.jpg" and I am trying to use URL.createObjectURL to do a preview, but it is not work. There is the error message: companymanage:1278 Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed. at Object.success (companymanage:1278:73) at c (datatables.min.js:14:28327) at Object.fireWith [as resolveWith] (datatables.min.js:14:29072) at l (datatables.min.js:14:79901) at XMLHttpRequest.<anonymous> (datatables.min.js:14:82355) I already try the image URL in chrome browser and arrived the image successfully. So why i can not use the path in URL.createObjectURL? Is the createObjectURL only accept File, Blob only and i enter the path so case this problem?? Is any solution suggest ??? -
MultiValueDictKeyError at /register/ request method post
MultiValueDictKeyError at /register/ 'name' Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 4.1.7 Exception Type: MultiValueDictKeyError Exception Value: 'name' Exception Location: C:\Users\vaibh\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\datastructures.py, line 86, in getitem Raised during: main.views.register Python Executable: C:\Users\vaibh\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.2 Python Path: ['V:\MEMEPROJECT\meme', 'C:\Users\vaibh\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\vaibh\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\vaibh\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\vaibh\AppData\Local\Programs\Python\Python311', 'C:\Users\vaibh\AppData\Local\Programs\Python\Python311\Lib\site-packages'] Server time: Fri, 24 Feb 2023 17:10:06 +0000 here i M TRYING TO GET USER DETAILS but this error MultiValueDictKeyError at /register/ is coming -
How do I stop logs before Django sets up logging
I have a call to Initialization() in wsgi.py in my django app that gets made before django calls setup(). Within that call to Initialization(), there is another call made to IdentityService() which is an imported library. This results in the logs from IdentityService() going to STDOUT when my django app initializes and I want to suppress these logs. The django app uses the normal LOGGING setting, configured by dictConfig(). Am I right in assuming that because the call on the Initialisation class gets made before configure_logging is called by setup(), the LOGGING dictionary can't control the logs of IdentityService() going to STDOUT? Any suggestions for how I can stop these logs being sent to STDOUT? -
Pytest not recognizing tests in some installed apps in django
I have an issue with pytest in which it executes tests in some installed apps but ignores some even after specifically trying to run tests on that said app it still won't recognize the app. The app that's not recognize currently is named file_upload when ever i run pytest with pytest it detects all tests in other apps (collected 52 items) excludes file_upload , when i also run pytest -k file_upload still says it collected 52 items and deselected 52 items, i named the test file with test_endpoints.py and in my pytest.ini i have the following configurations: [pytest] addopts = --ds=config.settings.test --reuse-db python_files = tests.py test_*.py i added file_storage to my installed apps and works perfectly when running migrations and the rest so it's probably a pytest issue but i can't figure exactly what. -
Django template with if - no clue what's wrong
I'm new to Django and followed the Django tutorial to understand and adapt to my needs. I am trying the following template: {% extends "base_generic.html" %} {% block content %} {% if user.is_authenticated %} <h1>List of my Projects</h1> {% if myproject_list %} <ul> {% for projectuser in myproject_list %} -{{ user.username }}-<br> -{{ projectuser.User }}-<br><br> {% if projectuser.User == user.username %} <li> x {{ projectuser.Project }} </li> {% endif %} {% endfor %} </ul> {% else %} <p>There are no projects to list.</p> {% endif %} {% else %} <li><a href="{% url 'login' %}?next={{ request.path }}">Login</a></li> {% endif %} {% endblock %} some code in there like -{{ user.username }}-<br> -{{ projectuser.User }}-<br><br> are just for debugging. with those two lines I get the usernames which I would like to apply here: {% if projectuser.User == user.username %} However the if is always not true!! What am I missing!?!?!?!? PS: I tried to find a solution with some posts here. Couldn't solve my problem -
User Login in DJango
Just learning to write Django APIs. I have created two APIs : one for Signup and one for Login. For signup, I have to send "username, password, password2" fields. password2 acts as retype password. For login, I have to send only "username, password" and if username and password both are there in User object, it should return 200 response code. The issue , I am getting is: while login, it says, "password2" is required. Here is the code: serializers.py: from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password class RegisterSerializer(serializers.ModelSerializer): username = serializers.CharField(required=True) password = serializers.CharField(write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('username', 'password', 'password2', 'email', 'first_name', 'last_name') def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({"password": "Password fields didn't match."}) return attrs def validate_username(self, value): if User.objects.filter(username__iexact=value).exists(): raise serializers.ValidationError("A user with this username already exists.") return value def create(self, validated_data): user = User.objects.create( username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user class LoginSerializer(serializers.ModelSerializer): username = serializers.CharField(required=True) password = serializers.CharField(required=True) class Meta: model = User fields = ('username', 'password') def validate_username(self, value): if User.objects.filter(username__iexact=value).exists() and User.objects.filter(password__iexact=value).exists(): return value else: raise serializers.ValidationError("username/password is incorrect.") views.py: from django.shortcuts import render # Create your views … -
Set correct path to environ file django
I have this project structure in Django: ├── .env ├── app │ ├── Dockerfile │ ├── Dockerfile.prod │ ├── entrypoint.prod.sh │ ├── entrypoint.sh │ ├── hello_django │ │ ├── __init__.py │ │ ├── asgi.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ └── requirements.txt Using django-environ how can i set the path to .env file? environ.Env.read_env(os.path.join(BASE_DIR, '.env')) This one doesn't work because its one level higher that project. How can i set the correct path? -
Django multiple annotate
Can anyone help me for my query. Let say i have this model : class Players(models.Model): ... teams (FK), nationality (FK), ... What i want to achieve is to annotate with this result : [nationality, count_of_players_with_nationality, distinct_teams_that_have_player_of_this_nationality] i only achieve the first two with this: Player.objects.values("nationality").annotate(count=Count("id")).order_by('-count') Can i add the distinct_teams_that_have_player_of_this_nationality with a single query? -
Change a field option in the inherited class
For example, I have a code: from django.db import models class AbstractClass(models.Model): name = models.CharField(max_length=150, null=True) class A(AbstractClass): field = models.CharField() class B(AbstractClass): another_field = models.CharField() # and also for exmaple i need to set max_length 155 for the name field here Can I somehow change a field option max_length of a field name in AbstractClass? I searched through some sites, but, unfortunately, didn't find anything. I saw about get_initial() and self.fields, but I don't know how to imply it to the class and I am not sure if it is even suitable for my situation.