Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Page Not Found "GET / HTTP/1.1" 404 2458
This is my project urls.py file from django.contrib import admin from django.urls import re_path, include from website.views import * from website import urls as website_urls from django.conf import settings from django.conf.urls.static import static urlpatterns = [ re_path(r'^/', include(website_urls)), re_path(r'^admin/', admin.site.urls) ] if settings.DEBUG: urlpatterns.extend(static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)) This is my apps urls.py file from django.urls import re_path from .views import * urlpatterns = [ re_path(r'^$', home, name='home'), re_path(r'^placeorder/<str:i>/$', PlaceOrder, name='placeorder'), re_path(r'^login/$', LoginPage, name='loginpage'), re_path(r'^logout/$/', Logout, name='logout'), re_path(r'^register/$', RegisterPage, name='register'), re_path(r'^addproduct/$', AddProduct, name='addproduct'), ] This is my views.py file from django.shortcuts import render, redirect from django.contrib.auth import login, logout,authenticate from .forms import * from django.http import HttpResponse def home(request): products = Product.objects.all() return render(request, 'website/home.html', {'products': products}) def PlaceOrder(request,i): customer = Customer.object.get(id=i) form = CreateOrderForm(instance=customer) if(request.method=='POST'): form = CreateOrderForm(request.POST, instance=customer) if(form.is_valid()) : form.save() return redirect('/') return redirect(request, 'website/placeorder.html', {'form':form}) def AddProduct(request): form = CreateProductForm() if (request.method=='POST'): form = CreateProductForm(request.POST, request.FILES) if (form.is_valid()): form.save() return redirect('/') return render(request, 'website/addproduct.html', {'form': form}) def RegisterPage(request): if request.user.is_authenticated: return redirect('home') else: form = CreateUserForm() customerform = CreateCustomerForm() if request.method == 'POST': form = CreateUserForm(request.POST) customerform = CreatePostForm(request.POST) if form.is_valid(): user = form.save() customer = customerform.save(commit=False) customer.user = user customer.save() return redirect('login') return render(request, 'website/register.html', {'form': form},{'customerform': customerform}) … -
time limits in uploading large files
I want to access users to upload large files to the Django server but my timeout is 50s. I'm using the Minio server so the first user should upload the file to the Django server and then files copies from the Django server to the Minio server using internal IPs. what can I do? -
Multiple select from m2m field in Django
I have an Image model and a Tag model, these models are connected by an m2m relationship. How do I select an Image that has a given set of Tags. For example. Images tagged with Tag1 and Tag2 but not Tag3. I tried to do it like this: Image.objects.filter(Q(tags__tag='Tag1') & Q(tags__tag='Tag2') & ~Q(tags__tag='Tag3')) But it doesn't work that way. -
Django admin InlineFormSet with M2M field
I'm trying to use Django admin to make a page and create related m2m field objects like in the picture, but when saving the object it'd say: Cannot assign "'<p>asfasfsaf</p>'": "Page_name.content" must be a "Content" instance. here's my code: from django.contrib import admin from .models import Page from utils.admin import ContentInlineFormset class PageNameAdmin(admin.TabularInline): extra = 1 model = Page.name.through formset = ContentInlineFormset class PageDescriptionAdmin(admin.TabularInline): extra = 1 model = Page.description.through formset = ContentInlineFormset verbose_name = "Page Description" @admin.register(Page) class PageAdmin(admin.ModelAdmin): inlines = [PageNameAdmin, PageDescriptionAdmin] exclude = ('name', 'description') from django.forms.models import BaseInlineFormSet class ContentInlineFormset(BaseInlineFormSet): def add_fields(self, form: Any, index: Any) -> None: form.fields['language'] = forms.CharField(label='Language') form.fields['content'] = RichTextFormField(label='Content') super().add_fields(form, index) What am I doing wrong? -
How to past multiple list from ajax to Django
I have an issue which I want to get all the data from list, so I want to loop every single data from selected items and insert it to database, currently it returns the data like this when I print it ['[object Object]', '[object Object]'], how can I insert these data one by one? or just print it one by one? I have this list which is selected_items I loop the data and then pass it to ajax selected_items = []; for (var i = 0; i < checkBoxes.length; i++) { var selected_obj ={ stock_id: checkBoxes[i].id, quantity: row.cells[3].innerHTML } selected_items.push(selected_obj); } when console the selected_items it's just like this so now I want to pass these list to django using ajax console.log(selected_items); $.ajax({ type: "POST", url: "{% url 'sales-item' %}", data:{ multiple_list: selected_items.join(','), item_size: selected_items.length } }).done(function(data){... views.py out_items = request.POST.getlist('multiple_list[]') print(out_items) and it prints like this ['[object Object]', '[object Object]'] -
Django Templates - pass %block% data to included template
I've got nested template file, and data from template doesn't shows main.html {% extends "template.html" %} .... {% block include_data %} NOT SHOWN DATA {% endblock %} {% block main_block %} some_data {% include "child.html" %} some_data {% endblock %} child.html <div> <tags></tags> {% block include_data %} that will shown, but i wanna to be shown "NO SHOWN DATA" {% endblock %} </div> How it can be solved? -
django.contrib.auth.models.Permission.DoesNotExist: Permission matching query does not exist
While assigning permissions to users, I am getting the error django.contrib.auth.models.Permission.DoesNotExist: Permission matching query does not exist. When I look into the database, I find that models aren't being shown as contenttypes; nor are the default add/change/delete/view permissions being created for them by django. How can I resolve this issue? Things I've tried: running python manage.py migrate on a new database.... issue persists. unapplying all migrations, then re-applying them... issue persists. applying the auth,contenttypes,sessions,admin migrations before any of my app migrations.. issue persists. Part of the code snippet I'm using is as follows: modelClass = apps.get_model(app, model) contentType = ContentType.objects.get_for_model(modelClass) if (contentType == None): raise Exception("ContentType isn't available.") permissions = Permission.objects.filter(content_type = contentType) for permission in permissions: permission.save() for permissionLiteral in permissionsString: if (permissionLiteral == 'a'): permission = permissions.get(codename__startswith = 'add_') elif (permissionLiteral == 'c'): permission = permissions.get(codename__startswith = 'change_') elif (permissionLiteral == 'd'): permission = permissions.get(codename__startswith = 'delete_') elif (permissionLiteral == 'v'): permission = permissions.get(codename__startswith = 'view_') else: raise Exception("Invalid permission literal.") if (permission != None): group.permissions.add(permission) app = my app's name being passed to function model = model name being passed to function permissionsString = passed 'advc' for all 4 permissions; 'v' for only the view permissions. The … -
How to create tables with "models.py" in the main folder in Django?
I'm trying to create a table with models.py in the main folder core where settings.py is as shown below: Django-project |- core | |-models.py # Here | └-settings.py |- app1 └- app2 This is models.py below: # "core/models.py" from django.db import models class Person(models.Model): name = models.CharField(max_length=20) Then, I tried to make migrations as shown below below: python manage.py makemigrations But, I couldn't make migrations getting the message below: No changes detected So, how can I create a table with models.py in the main folder core? -
HTMX not working when loaded within template tag using Alpine js (x-if)
For a Django project I am trying to build a toggle component to switch from list to grid view without reloading the page. I am using a Flowbite toggle component. Using Alpine's x-if I am able to dynamically change the HTML for the list view and the grid view which are contained in two template tags within the same alpine component. Here is a simplified version of the component: <div x-data="{ value: false }"> <!-- Toggle component from Flowbite --> <label class="relative inline-flex items-center cursor-pointer"> <input x-model="value" type="checkbox" value="" class="sr-only peer"> <div class="w-11 h-6 bg-slate-300 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-yellow-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-yellow-500"></div> <span class="ml-2 font-medium text-slate-600 mdi mdi-view-grid"></span> </label> <!-- Template tags with the HTML code --> <template x-if="value===true"> <div> <a href="{% url 'inventory:inventory' %}">HREF</a> </div> </template> <template x-if="value===false"> <div> <a hx-get="{% url 'inventory:inventory %}">HX-GET</a> </div> </template> </div> The toggle works just fine. However, while the toggled code with the href url works just fine, the code with the hx-get attribute (HTMX) does not work. Clicking on the link does not do anything. I suppose this has to do with inserting HTMX properties after the page is already … -
Querying the most commented Post in Django and django-comments-xtd
I use django-comments-xtd implementing the commenting system in my django project, I've written the following function to query the most commented post in my blog. It works well sorted since I've sorted the comment_counts dictionary, but when I return the result to my caller, the array is unsorted, while I've sorted them. comment_counts is the dictionary which contains object_pk and comment_count How can I return the sorted posts with Post.pusblished.filter(pk__in=post_ids) Here is my snippest after importing all necessary modules:- @register.simple_tag def getMostCommentedPosts(count=5): content_type = ContentType.objects.get_for_model(Post) comment_counts = XtdComment.objects.values('object_pk').annotate(comment_count=Count('object_pk')).order_by('-comment_count')[:count] comment_counts = sorted(comment_counts, key=lambda x: x['comment_count'], reverse=True) post_ids = [comment['object_pk'] for comment in comment_counts] return Post.published.filter(pk__in=post_ids) -
Pass query string of GET parameters into URL
In my Django project I have a page with multiple forms which using method="GET". On this page a list of items are displayed, where users can sort, filter and parse through different pages of these items. For example if a user selected page 4 and set the maximum price to £10, I would like the url to look like this: http://127.0.0.1:8000/trending/?page=4&max_price=10 The problem is when a form is submitted it overwrites the previous GET parameter in the URL For example User selects page 4 http://127.0.0.1:8000/trending/?page=4 Then the user sets max price to £10 http://127.0.0.1:8000/trending/?max_price=10 This is wrong as both parameters should appear in the URL together. I have come up with a method to save the state of these parameters inside request.session and then creating a query string with the values stored in request.session but I can't think of a way to pass the query string into the URL def trending(request): query_string = '&'.join([ f'{param}={request.session.get(param)}' for param in get_params if request.session.get(param) != None ]) return render(request, "App/trending.html", context=context) query_string => page=1&max_price=10 -
Nextjs does not load external image resource while having image url
I am running 3 containers in the same host. The frontend service is a Nextjs app. I use Apollo/client to query the backend server. After run docker-compose up --build (after build process of nextjs app too.), the frontend query a field which has an image, I receive the response with the image url in the frontend as follow node:{ id: "Q2F0ZWdvcnlOb2RlOjI="; name: "name-1"; thumbnail: "http://localhost:8000/graphql/uploads/images/categories/main1.jpeg"; __typename: "CategoryNode"; } but nextjs doesn't show the image and I have the following errors: in the console : Failed to load resource: the server responded with a status of 500 (Internal Server Error) In the terminal: TypeError: fetch failed c-client | at Object.fetch (node:internal/deps/undici/undici:11118:11) c-client | at process.processTicksAndRejections (node:internal/process/task_queues:95:5) c-client | at async imageOptimizer (/app/node_modules/next/dist/server/image-optimizer.js:371:29) c-client | at async /app/node_modules/next/dist/server/next-server.js:217:72 c-client | at async /app/node_modules/next/dist/server/response-cache/index.js:80:36 { c-client | cause: Error: connect ECONNREFUSED 127.0.0.1:8000 c-client | at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) { c-client | errno: -111, c-client | code: 'ECONNREFUSED', c-client | syscall: 'connect', c-client | address: '127.0.0.1', c-client | port: 8000 c-client | } c-client | } Looking the doc I configured next-config file const nextConfig = { reactStrictMode: true, output: "standalone", compiler: { styledComponents: true, }, images: { remotePatterns: [ { protocol: "http", … -
Failed building wheel for mysqlclient on macOS
I have been troubleshooting this problem for the past 3 days, tried every method in stack and no luck, I am relatively new to Django and python so any suggestions will be greatly appreciated. so I have been having a problem with installing mysqlclient through "pipenv install mysqlclient" returning: ERROR: Failed building wheel for mysqlclient full summary: Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning. Installing mysqlclient... Resolving mysqlclient... Installing... ⠸ Installing mysqlclient...[31m[1mError: [0m An error occurred while installing [32mmysqlclient[0m! Error text: Collecting mysqlclient (from -r /var/folders/x4/6p57c76d173_b99bb3rtc2q40000gn/T/pipenv-rva1k23w-requirements/pipenv-xzl65j4d-requirement.txt (line 1)) Using cached mysqlclient-2.1.1.tar.gz (88 kB) Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing metadata (pyproject.toml): started Preparing metadata (pyproject.toml): finished with status 'done' Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (pyproject.toml): started Building wheel for mysqlclient (pyproject.toml): finished with status 'error' Failed to build mysqlclient [36m error: subprocess-exited-with-error … -
VS-Code, Django, runserver plus "Couldn't spawn debuggee: embedded null byte"
If i run ./manage.py runserver_plus --key-file selftest-key --cert-file selftest-cert --nopin localhost:8443 everthing works fine. My launch.json looks like: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver_plus", "--key-file", "selftest-key", "--cert-file", "selftest-cert", "--nopin", "localhost:8443", ], "django": true, "justMyCode": false } ] } What should actually do the exact same thing like running the command in the shell. But if I want to run the Server over VS-Codes "Run And Debug" function, I get following error: Before I checkedout the project again, everything worked fine. I really don't understand what VS-Code wants from me, any help is appreciated. -
Is it possible to find a JWT token is expired in Django rest framework
Is it possible to find whether a JWT token is expired or not when both authentication_classes and permission_classes classes are present? Suggestions showing that try with simplejwt exception class. But when I tried with exception class it showed that the reference is not present. I have tried this code. from rest_framework_simplejwt.exceptions import TokenExpiredError, InvalidToken But it's not working. Please provide an answer. -
In django query filter for empty FileField
I need to filter a QuerySet by a FileField to get only the records where there is no file set on a FileField. Or the vice versa case, only the records with a file set on a FielField. Similar to this: SomeModel.objects.exclude( entry__relation__filefieldname=<set_to_something> ) or SomeModel.objects.filter( entry__relation__filefieldname=<not_set_at_all> ) Using Q-objects does not help. SomeModel.objects.exclude( Q(otherfieldname=None) & Q(filefieldname__isnull=True) ) How do i achieve it ? -
Adding a Search bar to the Filters Section for a Specific Object type in Django Admin Panel
I want to add search functionality to filter the the object types in the filters section (right-side) of django admin panel something as shown below I'm not sure if there is any default way of doing this or plugin for this Thanks in advance if any expansion is required that can be provided -
request.session.get() doesnt retireve values between views in django views.py
I want to pass the data of a client after he logged in, i use a login view to retrieve his data from the database then store it inside session variables, and after that i want to retrieve this data in another view, profile view in this case so i can take this data after i make a get request from a vue view after its mounted, but the issue here that the variable do not pass between the login view and the profile view. Here is my login view : @csrf_exempt def login(request): if request.method == 'POST': data = json.loads(request.body.decode("utf-8")) username = data['username'] password = data['password'] gerant = Gerant.objects.filter(username=username, password=password).first() if gerant is not None: request.session['gerant_nom'] = gerant.nom request.session['gerant_prenom'] = gerant.prenom name = request.session.get('gerant_nom') print(f"name: {name}") return JsonResponse({'url': 'http://localhost:8080/profilgerant'}) the get request for the profile view: mounted(){ axios .get('profile/') .then( response => { this.nom = response.data.gerant_nom this.prenom = response.data.gerant_prenom }, console.log(this.nom) ) } the profile view: @csrf_exempt def profile(request): gerant_nom = request.session.get('gerant_nom') gerant_prenom = request.session.get('gerant_prenom') print(f'nom: {gerant_nom}') data = { 'gerant_nom': gerant_nom, 'gerant_prenom': gerant_prenom } return JsonResponse(data) i want the data to be retrieved after the view is mounted. -
Getting SynchronousOnlyOperation while creating an object in async function in django
while running this :-> async def func(): print("This is async function") Program.objects.create(name="New Program") asyncio.run(func()) Getting this :-> This is async function Error : SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Can anyone help me to resolve this :) async def func(): print("This is async function") Program.objects.create(name="New Program") asyncio.run(func()) This is async function Error : SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Can anyone help me to resolve this :) -
Nested serializer upto a level in django
I have models.py class Attribute(models.Model): name = models.CharField(max_length = 255, null = True, blank = True) class AttributeValue(models.Model): name = models.CharField(max_length = 255, null = True, blank = True) attribute = models.ForeignKey(Attribute, on_delete = models.CASCADE, null = True, blank = True, related_name = 'attribute_value') class Product(models.Model): attribute_value = models.ManyToManyField(AttributeValue, blank = True, related_name = 'products') serializers.py class AttributeSerializer(serializers.ModelSerializer): name = serializers.CharField() class Meta: model = Attribute fields = ['id', 'name'] class AttributeValueSerializer(serializers.ModelSerializer): name = serializers.CharField() attributes = AttributeSerializer(read_only = True, many = True) class Meta: model = AttributeValue fields = ['id', 'name', 'attributes'] class ProductSerializer(serializers.ModelSerializer): attribute_value = AttributeValueSerializer(many = True, read_only = True) class Meta: model = Product fields = ['attribute_value'] I am trying GET request for Product model where i expect data to look like this product1 = { attribute1 = [ {'id': 'someid', 'name':'some_name'}, {'id': 'someid', 'name':'some_name'} ], attribute2 = [ {'id': 'someid', 'name':'some_name'}, {'id': 'someid', 'name':'some_name'} ] } But i am getting like this. Also i got Type error when i added attribute instead of attributes in AttributeValueSerializer serializer class product1 = { "attribute_value": [ {'id': 'someid', 'name':'some_name'}, {'id': 'someid', 'name':'some_name'} ] } Is there anything i am doing wrong ? Thanks in advance. -
can I run a bot inside a Django project that will run independent of other Django app
I have a Django project for a website. And for the same website, I run another Python bot. I was wondering if I could somehow attach the Python bot to the Django project so that they can run on the same server without causing harm to the Django project. Thank you. -
django-chartjs issue. chart not dus
I am currently trying to display a bar chart in my django application this chart is supposed to represent the total mortality rate of all hospitals I have in the database. I can see the data when I type the url in the browser or when I print in the console and I am getting the output I expect. the issue now is the chart is not being displayed on the page layout and I am not getting any errors or warnings. I have the codes here window.addEventListener('DOMContentLoaded', () => { // Get the data from the server fetch('/measures_data') .then(response => response.json()) .then(data => { // Process the data to get the mortality rates by hospital console.log(data) const labels = []; const mortalityRates = []; data.forEach(measure => { labels.push(measure.hospital__name); mortalityRates.push(measure.total_mortality_rate); }); // Create a bar chart const ctx = document.getElementById('motalityRate').getContext('2d'); const chart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: 'Total Mortality Rate', data: mortalityRates, backgroundColor: 'rgba(54, 162, 235, 0.2)', borderColor: 'rgba(54, 162, 235, 1)', borderWidth: 1 }], }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); }); }) views.py @require_http_methods(['GET']) def measures_data(request): measures = Measures.objects.values('hospital__name').annotate( total_mortality_rate=Sum('mortality_rate') ).order_by('hospital__name') … -
Hoe to insert to postgres using Django orm when a generated index field exists
I have a model which has a text field. I have created an index on this field for search purposes: class my_model(models.Model): text = models.TextField(null=True) vector = SearchVectorField(null=True, default='') Till now, I have inserted to this table using insert and to insert I did not provide any data for the field during insertion. Every thing was fine, but now I have added a manytomany field to this model. Since I have not crated an explicit thru table I want to change insert code to use Django orm. The problem that I have is when I try to insert to the model using orm with the following statement, I am getting the error: a1 = my_model(text='test') a1.save() Error: ProgrammingError: column "vector" can only be updated to DEFAULT DETAIL: Column "vector" is a generated column. Also, i tried the following with the same error: a1 = my_model(text='test', vector = '') a1.save() -
why i get [Errno 1131 No route to host in django
In a button click, I need to send an email to the client but I actually get this error. OSError at /insurance-company/requests/63256/accept-policy/ [Errno 1131 No route to host Request Method: POST Request URL: ...... Django Version: 3.2.16 Exception Type: OSError exceorion vanes erno 113 No rouce co nose Exception Location: /us/local/lib/python3.8/socket.py, line 796, in create_connection evthon Executable: /usrocaloin/ovthon ryton version: 3.0.1 Python Path: app' 'Jus/local/bin', rusr/local/aao/pychones.21ps /us~/ocal/110/pychons.s; usr/local/11o/python3.8/lib-dynload" Server time: Thu, 11 May 2023 09:07:27 +0000 Note: I only get this in the prod env, but not in my local enviroinment -
"TypeError: NetworkError when attempting to fetch resource", When trying to fetch JSON data on React native from Djang rest framework
I have some JSON data in a Django app, I deployed the app on AWS, when I try to access it on my browser it works fine, but when I try to fetch on React native, I get: "TypeError: NetworkError when attempting to fetch resource". That's my code on expo snack: import React, { useState, useEffect } from 'react'; import { Text, View } from 'react-native'; const App = () => { const [movies, setMovies] = useState([]); useEffect(() => { const fetchMovies = async () => { try { const response = await fetch( 'http://53.27.198.111:8000/api/' //that's not my real IP btw ); const data = await response.json(); setMovies(data.results); } catch (error) { alert(error); } }; fetchMovies(); }, []); return ( <View> <Text>Loading...</Text> </View> ); }; export default App; I tried django-cors-headers when the Django app was on localhost and it worked fine, but when I deployed it on AWS it's not working anymore.