Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Why is the route correct but still giving 404 error on Django
I got a 404 error on my website when accessing the correct route, did I do something wrong urls.py handles the main route from django.contrib import admin from django.urls import path,include,re_path urlpatterns = [ path('admin/', admin.site.urls), re_path(r'api/facebook/(.+?)', include('apifacebooks.urls')), path('', include('app.urls')), path('getcookie', include('app.urls')), path('change-lang', include('app.urls')), re_path(r'auth/(.+?)', include('app.urls')), ] urls.py handles routes in the apifacebooks app from django.urls import path from . import views urlpatterns = [ path('api/facebook/like-post',views.like_post) ] And when I go to http://localhost:8000/api/facebook/like-post I get a 404 error -
Unable to create super user in django on my online server
Inside the cpanel -> python app i have tried several time to create super user. when I tried to execute this commad inside Execute python script manage.py createsuperuser then it will return this error Superuser creation skipped due to not running in a TTY. You can run `manage.py createsuperuser` in your project to create one manually. How to solve this problem, or any manuall solution, i found several solution but all the solution for local server. -
How to get Radio Radio Button Data from POST Request Data in an HTML form?
So I'm coding a test platform consisting of Multiple Choice Questions ( MCQs ) in Django. Everything is working fine but somehow I think that the radio button value from my question page is not getting fetch via POST request. Would appreciate some help! Here are my models : from django.db import models from django.contrib.auth.models import AbstractUser from .managers import UserManager from questions.models import Question class User( AbstractUser ) : email = models.EmailField( verbose_name = 'Email Address', unique = True, null = False ) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__( self ) : return self.get_username() class Student( models.Model ) : user = models.OneToOneField( User, on_delete = models.PROTECT ) mobile = models.CharField( verbose_name = 'Mobile Number', max_length = 10, unique = True ) def __str__( self ) : return self.user.get_username() JAVA='J' PYTHON='P' DATABASE='D' OPERATING_SYSTEM='O' NETWORKING='N' SUBJECT_CODE = [ ( JAVA,'java' ), ( PYTHON,'python' ), ( DATABASE,'database management' ), ( OPERATING_SYSTEM,'operating systems' ), ( NETWORKING,'Computer Networks' ) ] class Performance( models.Model ) : global SUBJECT_CODE student = models.ForeignKey( Student, on_delete = models.PROTECT ) question = models.OneToOneField( Question, on_delete = models.PROTECT, null = True ) score = models.PositiveSmallIntegerField( verbose_name = 'Score', null = True ) … -
Render a template within def get_object instead of raise raise Http404("Does not exist") in class based view
In the get_object method of class views, can I direct the user to a template instead of returning the object if an if statement fails? Currently raise Http404("Some message.") works good but it doesn't look nice, I want to use my own template. I'm trying to do this but with templates: def get_object(self): product = Product.objects.get(slug=self.kwargs.get('slug')) if product.deleted == False: if product.out_of_stock == False: return product else: raise Http404("This product is sold out.") # return reverse("404-error", kwargs={"error": "sold-out"}) # return render(request, "custom_404.html", {"error": "sold_out"}) else: raise Http404("This product is no longer available.") # return reverse("404-error", kwargs={"error": "deleted"}) # return render(request, "custom_404.html", {"error": "deleted"}) My main goal is to just avoid getting the object. I know I can perform the if statement in the get_context_data method, however I wasn't sure for objects containing sensitive data if there would be any way for a user to access it once it's in the get_object, so I just wanted to avoid getting the object altogether if the condition fails and display a template to the user. -
Django extend base.html along with its context
I've passed a variable to base.html from my views.py file in a context. I've extended this base.html to another several templates. The variable is only visible in the base.html and not any other extended template. It does work if I pass the same context to each templates views.py file. As I extended the base, shouldn't it also extend the variable? Is there any other way to get this working, or am I missing something? -
Student registrations system using django
I am developing a student registrations system using django. Task: Teacher will pay x amount for x students. (Completed) So After payment the teacher will receive a unique url to register their students. (Completed) The URL will be valid for 7 days. (Completed) Apply restrictions for x students for that url. ( Pending ) Example: If a teacher paid for 2 leaders and got the unique url. But he can add 1000 students with that url within 7 days. So my question is how to restrict the registration to 2 students only. Any help?? Thanks -
How to make the FileField downloadable for users that has permission to download in Django?
I am making a simple e-commerce website that sells my own software in a zip file, how to make a download link for the file that can only be accessed with the user who purchased the product? Any advice on how should i manage my product files? This is my Products model class Product(models.Model): name = models.CharField(max_length=150) price = models.FloatField() description = models.CharField(max_length=255, blank=True) product_type = models.CharField(max_length=20, default='tool') date_created = models.DateField(auto_now_add=True) date_updated = models.DateField(auto_now=True) image = models.ImageField(null=True, blank=True)