Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Give List of Objects IDs and add a click event based on each List IDs in Django
Here in my Django code, I have a list of prices. Now I gave them unique IDs which works well, but when I try to add a click event, the click event only works for only one list item continuously. {% for price in logistic_branch_pricing %} <h1 id="select-delivery-location-{{price.id}}" onclick="calculateDeliveryPrice()">{{ price.id }}-{{price.small_kg_price}} </h1> {% endfor %} {% for price in logistic_branch_pricing %} <script> function calculateDeliveryPrice() { var omo = document.getElementById("select-delivery-location-{{ price.id }}") omo.classList.add('d-none') console.log(omo) } </script> {% endfor %} -
How do I view the profile of the authenticated user in Django Rest Framework using the Token
I am learning DRF and creating a simple DRF app that lets user login, and view the profile and update the profile. I am using Django's default User model and using Knox for Token Authentication (if it can be done easier using Django Rest Authentication, please let me know and also tell me the procedure). I have successfully created the API to register and login the user which works fine, but I am stuck at showing the profile to the Authenticated User through a Token. I am only one Model that is Details which acts as to store the Profile details of the user. I have LoginSerializer which is connected to Login API and MainUserSerializer & UserSerializer, both of which are connected to User API (which acts to show the Profile details on frontend). I have tried a lot, searched everywhere, but all they show is how to authenticate the user with token through a url (some thing like using curl https://localhost:8000/api/user... etc.), postman, somehing like http post -a... command in terminal and other ways, but I don't want to test or implement using these ways. I want something that if I open my user profile url after logging in … -
Django list DB entries if LDAP group and key parameter match
Having hard time to figure out mechanism for my django app. I have tabele in db with list of Agents and every agent has assigned specific name of LDAP group in this table. Now i need to somehow compare LDAP group of logged user this LDAP value from agent table and list only those agents which matches LDAP group. I know how to get LDAP group of user. Just need to figure out how to match this value with list of agents and list them. End effect: User logging in and can list agents only which matches his LDAP group. -
Add object to ManyToMany field doesn't work
I have 2 models: class User(AbstractUser): pass class Post(models.Model): poster = models.ForeignKey('User', on_delete=models.CASCADE, related_name='posts') body = models.TextField() likes = models.IntegerField(default=0) likers = models.ManyToManyField('User', blank=True, null=True, related_name='liked_posts') Post has a manytomany field to User model. I try to a user object to the field with the view function below but it doesn't work: @csrf_exempt def likepost(request, like, post_id): if (request.method == 'PUT'): post = Post.objects.get(pk=post_id) if like: post.likers.add(request.user) else: post.likers.remove(request.user) post.save() print(post.likers) return HttpResponse(status=204) else: return JsonResponse({ 'error': 'PUT request required.' }, status=400) -
How to do Total Sum from JS in Django
let x = document.getElementById("food_price"); console.log(x); I want to get total of food items from js, but i could not get the solution, can anyone help me. -
How can I read csv files from the link stored in django model within views file?
I am creating a map with Folium, Django and Pandas. I created a django model where I store my csv file's url. I want to read csv files from there dynamically so that I can use different data dynamically. How can I do that? I used a url of a csv file. I want to make it dynamic so that I can fetch one from models directly. Here is my code. I will be very grateful for your assistance. def mapview(request, map_pk): srlist = Map.objects.filter(pk=map_pk) bd = pd.read_csv("https://docs.google.com/spreadsheets/d/1IohEgJi8ajDoHyPF315vi13F3m0vDtbl7DzmSmtUHpA/gviz/tq?tqx=out:csv") df = pd.DataFrame(bd) lat = df[['lat']] lng = df[['lng']] m = folium.Map(title='Bangladesh', location=[23.7805733, 90.2792399], zoom_start=7) for i, row in df.iterrows(): folium.Marker(location=[row['lat'], row['lng']]).add_to(m) m = m._repr_html_() context = { 'm':m, 'bd':bd, 'lat': lat, 'lng': lng, 'srlist':srlist, 'df':df, } return render(request, 'map/mapview.html', context) -
one django project two apps, problem with generic views( class view)
i have two apps in one project: store and basket. In urls.py in core of project: urlpatterns = [ path('admin/', admin.site.urls), path('', include('jewelry_store.urls', namespace='jewelry_store')), path('basket/', include('basket.urls', namespace='basket')), ] in urls.py in basket app : from django.urls import path from basket import views app_name = 'basket' urlpatterns = [ path('', views.BasketSummary.as_view(), name='basket_summary') ] in urls.py in jewelry_store app : from django.urls import path from jewelry_store.models import Category from . import views app_name = 'jewelry_store' urlpatterns = [ path('', views.AllListView.as_view(), name='all_products'), path('<slug:slug>', views.ProductView.as_view(), name='product_detail'), path('category/<slug:slug>/', views.CategoryView.as_view(), name='all_categories'), path('collection/<slug:slug>/', views.CollectionView.as_view(), name='all_collections'), ] i wold like to have class based view in views.py, like this : from msilib.schema import ListView from django.shortcuts import render import basket from jewelry_store.models import Product # Create your here. class BasketSummary(ListView): model = Product template_name = "jewelry_store/basket/summary.html" but it generate error like this when it is done in functions mode everything is correct. What is proper configuration for class views ? -
Not able to redirect to a specific page on login
I am trying to create django authentication but I am not able to redirect to a specific page. Here is my urls.py file. I think the error may be in this file but I am not able to get it. """demo_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from blog.forms import LoginForm urlpatterns = [ path('admin/', admin.site.urls), path('blogs/', include('blog.urls', namespace='blogs')), path('login/', auth_views.LoginView.as_view(template_name='blog/login.html', authentication_form=LoginForm), name='login'), ] The problem is on clicking the login button the url comes as http://localhost:8000/login/blogs/get_blogs instead of http://localhost:8000/blogs/get_blogs/. Here is the settings.py file. """ Django settings for demo_project project. Generated by 'django-admin startproject' using Django 4.0.3. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, … -
django.db.utils.OperationalError: (1054, "Unknown column 'titile' in 'where clause'")
could anyone help me out with this? operations = [ migrations.RunSQL(""" INSERT INTO store_collection(title) VALUES('collection1') """, """ DELETE FROM store_collection WHERE titile='collection1' """) ] I try searching for a solution but couldn't find anything so I have to post this. -
I am trying to retreive data from data from django backend to react but keep getting TypeError: get() missing 1 required positional argument: 'pk'
I have two concerns here. I am trying to retrieve data from django which contains images and contents. My first concern is whether using "Content-Type": "application/json" is right. The last and major problem is am getting: TypeError: get() missing 1 required positional argument: 'pk'. What could be the issue? Below is the code: import React, { useEffect, useState} from 'react' import axios from 'axios' const GetPostData = () => { const [postState, setPostState] = useState({ loading: true, posts: null }) const config = { headers: { "Content-Type": "application/json", Authorization: `JWT ${localStorage.getItem("access")}`, Accept: "application/json", }, }; useEffect(()=> { const res = axios.get( `${process.env.REACT_APP_API_URL}/api/list/PostView/`, config ); const allPosts = res.data setPostState({loading: false, posts: allPosts}) console.log(res.data) }, [setPostState]) return ( <div className='container'> <h1>Latest Posts</h1> <div> </div> </div> ) } export default GetPostData -
Django i18n set_language for other template extends not work
i am a beginner in django, and i am confused in i18n settings, i have checked many articles to figure out the problem, but it always failed, below is my templates structure: templates folder: |____layouts | |____base.html | |____includes | |____navigation.html | |____home |____index.html In base.html's body, i use {% include 'includes/navigation.html' %} make sure each page has a navigation bar, and index.html use {% extends "layouts/base.html" %} to make my home page. In my settings.py, i followed i18n tutorial to setup multi language, below is my settings: MIDDLEWARE: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES context processors: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', ], }, }, ] Internationalization: from django.utils.translation import gettext_lazy as _ LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', _('English')), ('zh-hant', _('Traditional Chinese')), ('vi', _('Vietnamese')), ) TIME_ZONE = 'Asia/Ho_Chi_Minh' USE_I18N = True USE_L10N = True LOCALE_PATHS = [os.path.join(CORE_DIR, 'locale')] USE_TZ = True In my navigation.html, i put a select form to let users choose their prefer language: <form action="{% url 'set_language' %}" method="POST"> {% csrf_token %} <select class="form-select" name="language" onchange="this.form.submit()"> {% get_current_language as LANGUAGE_CODE %} {% get_language_info_list for … -
Is it possible to use Django to parse locally stored files (csv for example) without uploading them?
I would like to develop a WebApp that parses locally stored data and allows users to create a sorted excel file. It would be amazing if I could somehow avoid the uploading of the files. Some users are worried because of the data, the files can get really big so I have to implement async processes and so on... Is something like that possible? -
django.db.utils.IntegrityError: NOT NULL constraint failed: main_profile.name
I am creating a telegram bot that is a database. There is such an error:django.db.utils.IntegrityError: NOT NULL constraint failed: main_profile.name. What must I do ? Models.py from django.db import models class Profile(models.Model): external_id = models.PositiveIntegerField( verbose_name='User ID', unique=True, ) name = models.TextField( verbose_name='User name', default='None' ) def __str__(self): return f' ID: {self.external_id} | Username: {self.name}' class Meta: verbose_name = 'Profile' class Message(models.Model): profile = models.ForeignKey( to='main.Profile', verbose_name='Profile', on_delete=models.PROTECT, null=True, ) text = models.TextField( verbose_name='Text', ) Forms.py from django import forms from .models import Profile class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'external_id', 'name', ) widgets = { 'name': forms.TextInput } -
How to assign bulk parameter to Django object values list?
How to assign bulk parameters to the Django object values list? Bulk parameter assignment strlist = ["a","b","c"] model1. objects.filter(**kwargs).values_list(strlist) Result: TypeError: unhashable type: 'list' Manual assignment model1. objects.filter(**kwargs).values_list("a","b","c") Result is ok How to assign a bulk parameter assignment? -
Program not save and update new data in Django
I create program stock management system by using Django. When I will update data it can't save and update data. It redirect with same data. I am very new so please introduce me. Program can running but can't save. [This is error in command prompt][1] [forms.py][2] -
Testing Django with MongoDB(Djongo)
I'm looking for a way to test my Django app that works with MongoDB using Djongo. I found Django Test Addons library but as I understood, it only works with mongoengine. Is there any manner to make it work with Djongo or do you know another similar library that I can use? -
Django StreamingHttpResponse: How to quit Popen process when client disconnects?
In django, i want to convert a m3u8 playlist to mp4 and stream it to the client with ffmpeg pipe. The code works and the ffmpeg process also quits, but only when client waits till the end and received the whole file. I want to quit the process when the client disconnects but the process keeps running forever. I have this code: import subprocess from functools import partial from django.http.response import StreamingHttpResponse from django.shortcuts import get_object_or_404 from django.utils.text import slugify def stream(request, uuid): vod = get_object_or_404(Vod, uuid=uuid) def iterator(proc): for data in iter(partial(proc.stdout.read, 4096), b""): if not data: proc.kill() yield data cmd = ["ffmpeg", "-i", "input.m3u8", "-c", "copy", "-bsf:a", "aac_adtstoasc", "-movflags", "frag_keyframe+empty_moov", "-f", "mp4", "-"] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) response = StreamingHttpResponse(iterator(proc), content_type="video/mp4") response["Content-Disposition"] = f"attachment; filename={slugify(vod.date)}-{slugify(vod.title)}.mp4" return response I've seen this answer but I'm not sure if I could use threading to solve my problem. -
TypeError: 'str' object is not callable in django
I am trying to create django authentication but I am getting the following error. TypeError: 'str' object is not callable Here is my urls.py file. I think the error may be in this file but I am not able to get it. """demo_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from blog.forms import LoginForm urlpatterns = [ path('admin/', admin.site.urls), path('blogs/', include('blog.urls', namespace='blogs')), path('login/', auth_views.LoginView.as_view(template_name='blog/login.html', authentication_form='LoginForm'), name='login'), ] [Here is the link to the git repository] (https://github.com/AnshulGupta22/demo-project) I searched for this error but none of the solution is helping me. I am new to django so some help will be appreciated. -
Incorrect display of django admin panel in chrome
My problem is that the admin panel is not displayed correctly in the chrome browser (for example, everything is fine in yandex). Several windows seem to overlap each other and work with the panel becomes impossible. This has happened since the beginning of the project. At the same time, everything seems to be fine with the styles. I would be very grateful for any help! URLs.py: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^accounts/', include('Вход.urls')), url(r'^admin/', admin.site.urls), url(r'^', include('Главная.urls')), url(r'^Новости/', include('Новости.urls')), url(r'^Видео/', include('Видео.urls')), url(r'^Фото/', include('Фото.urls')), url(r'^Аудио/', include('Аудио.urls')), url(r'^Документы/', include('Документы.urls')), url(r'^О_нас/', include('О_нас.urls')), ] if settings.DEBUG: urlpatterns += staticfiles_urlpatterns() + static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Settings.py: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-vs7bbhw5n5trc#9b76jp*7+v%&%ojpodampt5yze=jiy=ahc^z' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Главная', 'Вход', 'Новости', 'Видео', 'Фото', 'Аудио', 'Документы', … -
I have CORS whitelisted in Django and the Cross Origin Request is still blocked
I have a Vue front-end and a Django back-end and I have CORS enabled in settings.py, but I still get these errors: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/register. (Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’). Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/register. (Reason: CORS request did not succeed). Status code: (null). This is at the bottom of my settings.py file: CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:8080', 'http://localhost:8000', ) -
Django extend `UserManager` instead of `BaseUserManager`
Django docs says to define a custom manager you have to extend the BaseUserManager and provide two additional methods. But after doing so, I realized that my custom manager is vary similar to the default UserManager. So, is there a problem with inheriting from that instead? Like this: from django.contrib.auth.models import UserManager class CustomUserManager(UserManager): """Custom user model manager with email as the unique identifier.""" def _create_user(self, email, password, **extra_fields): if not email: raise ValueError("The given email must be set") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user I just overrode the _create_user method, because others were identical. -
ArrayField consisting of composite field type
I have modeled composite field using https://pypi.org/project/django-composite-field/ in my django model (A URL field + a Boolean Field). What I want is to store a number of those (maybe in a list) in my base 'User' model. But ArrayField using django.contrib.postgres.fields only support a single data type. What I want is a list of the object (URL + boolean) for every user. Further I want to add validations for the number of objects eg.(min 2 objects, max 6 objects). What is a good way to model this? Thanks. -
django-tenants: access tenant media files in script
I am running an app built with djang-tenants. The app asks the user (tenant) to upload some data. I want the data to be segregated in sub directories for each tenant. Acccording to the doc (https://django-tenants.readthedocs.io/en/latest/files.html), here is how media root is configured: settings.py MEDIA_ROOT = "/Users/murcielago/desktop/simulation_application/data" MULTITENANT_RELATIVE_MEDIA_ROOT = "%s" On the upload everything is great. Now, I can't find a way to retrieve the file being uploaded within the app. Basically I need the app to serve the file corresponding to which tenant is requesting it. Here is how I thought this would work: from django.conf import settings media_file_dir = settings.MULTITENANT_RELATIVE_MEDIA_ROOT df = pd.read_csv(media_file_dir+'/uploads/sample_orders_data.csv') but this does not work. I have made it work so far grabbing the tenant name from the url and passing it to the app using pickle but this is not right in terms of security and won't scale. Would someone has a clue on the best way to handle the lecture of tenant specific files? -
Docker Django_crispy_forms raise InvalidTemplateLibrary
I was developing a bookstore app using Django on Docker, I created a signup and login page, then utilized the django_crispy_forms for the signup and login page. Here is the commands flow: docker-compose exec web pipenv install django_crispy_forms==2.0.0 docker-compose down -v docker-compose up -d --build Lastly update the settings.py: # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', # new # local apps 'users.apps.UsersConfig', 'pages.apps.PagesConfig', ] # django-crispy-forms CRISPY_TEMPLATE_PACK = 'bootstrap4' # new But when I check the logs with: docker-compose logs The console raise a error: raise InvalidTemplateLibrary(django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'crispy_forms.templatetags.crispy_forms_field': cannot import name 'BoundField' from 'django.forms.forms' (/usr/local/lib/python3.10/site-packages/django/forms/forms.py) My Dockerfile code: FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ And the docker-compose.yml: version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_NAME=bookpostgresv2 - POSTGRES_USER=bookpostgresv2 - POSTGRES_PASSWORD=bookpostgresv2 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=bookpostgresv2 - POSTGRES_USER=bookpostgresv2 - POSTGRES_PASSWORD=bookpostgresv2 depends_on: - db requirements.txt: Django>=3.0,<4.0 psycopg2>=2.8 django-crispy-forms-ng==2.0.0 pipenv==2022.3.24 -
how to pass url name in Django template using context variable
In my Django project, I am experiencing an issue in passing url name in Django template. Say I have this line in urls.py ... path('hd2900', hd2900.as_view(), name='hd2900') ... In template if I pass 'hd2900' ass a string in the {% url %} tag things work. <a class="navbar-brand navbar-left" href="{% url 'hd2900' %}" id="navbarLogoLink"> <img src="{{ navbarLogoPath }}" alt="{{ navbarLogoAlt }}" id="navbarLogo"> </a> But if I use a context variable from a view for example in views.py context['urlName'] = 'hd2900' Then in template if I change 'hd2900' to urlName, I will get an error NoReverseMatch at /hd2900. Somehow it no longer looks for name my url pattern.