Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to autocomplete an input search in django
I'm working on a website with django which gives the assessment of data quality. In this project the user can upload a csv, XML, json, html files. So I'm trying to generate regular expressions from a list of strings to verify errors in string type errors .. can you orient me to do that please? -
Can we modify the serializer fields based on view and user type?
I have a User serializer with the below fields, I am trying to add only some fields for List view but want to return different set of fields for Detail View, these are the fields:- super_user_list_fields = ( 'id', 'username', 'email', 'password', 'first_name', 'last_name', 'phone_number', 'birth_date', 'is_active', 'is_staff', 'is_superuser', 'groups', ) super_user_detail_fields = ( 'id', 'username', 'password', 'first_name', 'last_name', 'email', 'bio', 'url', 'company', 'location', 'phone_number', 'birth_date', 'notes', 'is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions', 'last_login', 'date_joined', ) normal_user_list_fields = (.......,) normal_user_detail_fields = (........,) These is my serilaizer:- class UserSerializer(serilaizers.ModelSerializer): class Meta: model = User fields = super_user_list_fields I have two views first one is extensions of ListCreateAPIView, and second is RetrieveUpdateDestroy. Now I also want to change some of these fields based on the type of user objects such as a different set of fields for superUsers, non-superusers, etc. .... I am thinking if there could be some method like this:- class serializer(...): class Meta: model = User fields = get_the_required_fields() .......... .......... ......... def get_the_required_fields(self, ....): user = self.request.user if user.is_superuser and (viewtype is ListCreateAPIView): return super_user_list_fields if user.is_superuser and (viewtype is RetrieveUpdateDestroyAPIView): return super_user_detail_fields ......... ........ ....... -
Django - Check if reverse foreign key relation exists
I have the following database structure: class User(AbstractBaseUser): email = models.EmailField(unique=True) @property def type(self): if getattr(self, 'typeA', None): return 'typeA' elif getattr(self, 'typeB', None): return 'typeB' elif getattr(self, 'typeC', None): return 'typeC' @property def profile(self): return getattr(self, self.type) class TypeA(models.Model): user = models.OneToOneField(User) field1 = ... field2 = ... # -- up to field 5 -- class TypeB(models.Model): user = models.OneToOneField(User) field6 = ... field7 = ... # -- up to field 10 class TypeC(models.Model): user = models.OneToOneField(User) field11 = ... field12 = ... # -- up to field 22 I have three different types of profiles: Type A, Type B and Type C, all of them having different fields from each other. Up until now if i wanted to do a reverse OneToOneField lookup from User to one of the profile types, i'd have a @property which returned the type of profile that the user has. And then i'd have another @property which returns the instance of that profile type. The problem with this approach is that when i call user.profile, up to 3 queries are made to the database in order to return the correct profile type. I want to reduce this to just 1 query in all … -
Django: Conditionally change short_description in ModelAdmin based on request data
Is there a way to conditionally set short_description value inside ModelAdmin based on request data? Suppose, we have Product model, with following list_display values: ['price', 'manufacturer', ...so on]. We want to conditionally change short_description of the 'price' field based on some request data, so it would be called differently for different kinds of users. I haven't found any implementations of such behavior. -
Django signals how to add admin as receiver?
I am using django signals for notifications. I create an signals for notify author when any new blog post will be created or update post status and I am using author both as sender and receiver. I want the author will be sender and all admin will be receiver. How to do that? here is my code: models.py class Blog(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE,max_length=100) title = models.CharField(max_length=300,unique=True) #my others fields...... def blog_notify(sender, instance, *args, **kwargs): blog = instance blog_title = blog.title sender = blog.author if sender == blog.author and blog.is_published == "published": notify = Notifications(blog=blog, sender=sender, reciver=sender,text_preview = blog_title[:250], notification_type="post approved") notify.save() post_save.connect(Blog.blog_notify, sender=Blog) I aslo tried reciver = blog.author.is_superuser for set receiver as admin but sender and receiver still author. How to add admin as receiver in my signals? -
Only homepage url is working in django app. Other urls are not working
My Django app is working on shared Linux hosting but only homepage is working. When I try to access other pages 404 error occurs. I believe urls.py is causing problems. Only empty url path is working others like about, contact, careers are not working. I am using Linux shared hosting by godaddy with cpanel. urls.py--> ``` from django.contrib import admin from django.urls import path from website.views import * urlpatterns = [ path('admin/', admin.site.urls), path('',welcome, name="home"), path('about/',aboutus, name="about"), path('itServ',services, name="serv"), path('itRec',rec, name="rec"), path('ManC',management, name="management"), path('careers',career, name="careers"), path('contact',contacts, name="contact"), ]``` setting.py--> ``` import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'qkepshp^^#7dcucuabdg8@yyo3^2fv9@yyi1a9u7%%4j8*#!v#' DEBUG = True ALLOWED_HOSTS = ['northernrecruiters.com','www.northernrecruiters.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ntmc.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'ntmc.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N … -
Django/React - Cookies Stored Under Wrong Domain Name
I'm using CSRF and Session cookies in a Django React project. Everything works great on local development. I am having an issue with cookies in the production environment. The backend and frontend are hosted on Heroku under different domains. When I request a CSRF token from the backend, the token is stored under the domain name from where the backend is hosted. This means my frontend is unable to access the cookies. If I call the backend APIs directly from the browser, the cookies work fine since they're stored under the same domain name I sent the request to. I've been struggling to solve the issue, and any help would be appreciated. # settings.py SESSION_COOKIE_HTTPONLY = True CSRF_COOKIE_SAMESITE = "Lax" SESSION_COOKIE_SAMESITE = "Lax" if config("ENVIRONMENT") == "PRODUCTION": CORS_ORIGIN_WHITELIST = ["https://biz.mysite.tech"] else: CORS_ORIGIN_WHITELIST = ["http://localhost:3000"] CORS_EXPOSE_HEADERS = ["Content-Type", "X-CSRFToken"] CORS_ALLOW_CREDENTIALS = True // Axios settings in React { withCredentials: true, credentials: "include", headers: { Accept: "application/json", "Content-Type": "application/json", "X-CSRFToken": cookies.get("csrftoken"), }, } -
Exchanging data between view and temaplate via input type="hidden"
So I am coding a little tool for storing recipes as a practice. We are landing on the page called "create_meal/" via button from the main site. On the create meal site you can create meal via ModelForm. Meal is a model that doesn't contain info about indgredients. Info about ingredients is stored in another model called IngredientWithQuantity (IwQ) IwQ refers to Meal as Foreign Key. On the Create Meal Page you can add IwQ to your new meal and it is handled by a ModelForm. When you send this form you are landing on the same page and IwQ is created and assigned to the meal in the database. If you fill the form again it will be assigned to the same meal and so on. Now the logic: If you landed on Create Meal for the first time, a new Meal object is created. Then a form for adding IwQ is created When form is submitted meal new meal is added problem occurs: You need to create the same form but this time not for a new Meal but one that is already there. So you need to exchange data between view and template. My solution is this: … -
Correct syntax in django's forms.py?
I am currently working on forms in django, and wanted to add another field to a preexisting one in a form. The original is: class NewMessageForm(forms.ModelForm): class Meta: model = Message fields = ['content'] There's another field I'd like to add, which is called 'reciever'. I was thinking maybe I'd add it like: fields = ['content'], ['reciever'] but it gave me an error: File "C:\Users\Rebecca.Bi\OneDrive - St. Agnes Academy\Desktop\temp newsment\newsment-copy\env\lib\site-packages\django\forms\models.py", line 190, in if (not exclude or f not in exclude) and f not in ignored TypeError: unhashable type: 'list' What would be the right syntax to add this new field in forms.py? I am using python 3.7 Thank you for your help - any of it counts!! -
how do I create a Web app for processing an excel file
I have to develop a web application that read an excel file, process it and print the result can someone give me the steps to do so, I'm thinking on using django, but i don't know if it is a good idea. -
Django based invoice web app suggestion for novice
I am new to Django and I am making an order management web application for a local food corner. What I want is to take orders from a webpage and further process the data for the store. I am struggling with capturing the data from the web page. In the attached image, if I type 'The Orio Doughnut' and the quantity, the unit price should be extracted from the database and the line total should be calculated automatically by multiplying the quantity*unit price. After the order has been created by 'continue to checkout' how can I capture this data to the backend? I do not need the code. I just need the steps for this task including what should be done by js and what should be by Django. -
Allow user to upload image through HTML form - Django
I am creating a donation web application. I want the user to be able to upload a picture of the item they are donating, and for it to save to my database. This works if I do it through the admin panel, but I can't figure out how to do it with an html form. Thank you to everyone who helps. My code is down bellow. Image upload (this is the part of the form that allows the user to upload an image): <label class="label-input100" for="image">Image*</label> <div class=""> <input id="image" class="input100" type="file" name="image" required> <span class="focus-input100"></span> </div> Donation View (I take a lot of data from other parts of the form, and save it to the model. I haven't added any code to save the image yet, i'm not sure how to do that. def donate(request): if request.method == "POST": title = request.POST['donationtitle'] phonenumber = request.POST['phonenumber'] category = request.POST['category'] quantity = request.POST['quantity'] location = request.POST['location'] description = request.POST['description'] date = datetime.datetime.now().date() ins = Donation(title = title, phonenumber = phonenumber, category = category, quantity = quantity, location = location, description = description, user=request.user, date = date ) ins.save() # New part. Update donor's stats. UserDetail.objects.filter(user=request.user).update(donations=F('donations') + 1) UserDetail.objects.filter(user=request.user).update(points=F('points') + (quantity * … -
How to authorize by qr as in whatsapp?
(I'm a beginner) I would like to make an application on flutter, which will need to be registered and there will be certain data (taken and given books). Make a qr scanner in the same place. there is a shelf with books, which can be accessed only if you scan qr on a computer (qr will not be permanent and will be updated every 1 minute for the sake of safety) and indicate which books you took and which ones you left. The data will be displayed on the client's phone (that is, the application on the client's phone has no functionality other than viewing data about books) (I want to write the server part in python) question: how to log in via qr? or rather, how to send data when scanning qr? i know qr stores small data. how much should I make a qr generator that will store the access key (unfortunately, I also do not understand how to implement the access key to the accounts, and whether it will be safe to make the access key from which you can access all accounts) key (1234) when the scanned application should send example.com/qr/1234, but how to access the … -
Django in Docker: is GNU gettext tools only required in dev?
I'm building a Django app with Docker. I have 2 dockerfiles, one for dev and one for prod. To use Django's i18n, it's required to install "GNU gettext tools". I could add lines to dockerfile.dev to install this RUN apt update RUN apt install gettext -y However, do I need this tool also installed in prod? -
Django/React CORS/Session Cookies only storing on Local Development, not Production Env
I have a web application using CSRF and Session tokens being stored as cookies. My backend application is built on Django. My frontend application is built with React and my requests are being made through the Axios library. Everything works perfectly in development. I can see the CSRF token stored in the browser and I can see the Session token stored after login. After deploying the application, both tokens are no longer stored in the browser. The application is deployed on Heroku and I'm using a custom domain. The only noticeable difference between development and production is my requests are being made over HTTPS. Any help would be appreciated. Below are my CORS settings in my settings.py file and my headers in my Axios requests. CSRF_COOKIE_SAMESITE = "Lax" SESSION_COOKIE_SAMESITE = "Lax" SESSION_COOKIE_HTTPONLY = True if config("ENVIRONMENT") == "DEVELOPMENT": CORS_ORIGIN_WHITELIST = ["http://localhost:3000"] else: CORS_ORIGIN_WHITELIST = ["https://biz.mywebsite.com"] CORS_EXPOSE_HEADERS = ["Content-Type", "X-CSRFToken"] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = default_headers + ("Access-Control-Allow-Origin",) Axios { withCredentials: true, credentials: "include", headers: { Accept: "application/json", "Content-Type": "application/json", "X-CSRFToken": cookies.get("csrftoken"), } } -
How to filter Serializers in DjangoRestFramework based on user id?
I'm new to django, I can't seem to find how to return an api based on the user who requested it and created the Transaction object, can you please guide me through? I have read this, but I can't find a clear guide in the docs to update the Serializer straightaway. In laravel, I can do: Transaction::where('user_id', Auth::user()->id)->get(); This is my serializer: class TransactionSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer(read_only=True) tags = TagShortSerializer(read_only=True, many=True) def get_fields(self, *args, **kwargs): # Override this method so that the list of DatabaseUsers presented in the browseable API # is restricted to the DatabaseUsers owned by the current user. fields = super(TransactionSerializer, self).get_fields(*args, **kwargs) view = self.context["view"] user = view.request.user return Transaction.objects.filter(user=user) class Meta: model = Transaction fields = ["user", "title", "amount", "category", "tags"] My viewset: class TransactionViewSet(viewsets.ModelViewSet): queryset = Transaction.objects.all() serializer_class = TransactionSerializer permission_classes = [permissions.IsAuthenticated, IsOwner] Currently it returns: -
403 CSRF verification failed on Safari Private browser
can't figure it out why CSRF verification failed on safari private browser. Other rest of the browser all seems fine. Also have tested on safari browser but its working there but not on safari private browser. -
Django Admin /img not found
So iam learning Django at the moment but iam kinda stuck with this problem. I have a django app called projects, in which iam showing 3 projects (don't mind the lines around everything, i did this to better learn CSS and Bootstrap containers). So next feature i tried to implement, is that i can change these projects names etc. in the admin view page. I got it all working and i am seeing the projects. But when iam clicking on a project a get this error. So that is the path to the image folder which is defined in my models.py file: from django.db import models class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.FilePathField(path="/img") How can I fix this? -
Submit a file in angular using Django
I'm trying to send a file from an angular frontend to Django, I have this code that uses a basic drag and drop file submission box but I cant get the file to process in typescript. formData.append('file', this.form.get('dragndrop')!.value); throws the error TypeError: Cannot read property 'setValue' of null in my browser console but I don't understand why. Am I missing something? I've set up a basic file submission box that works perfect, the file gets sent to the server with ease. Its only when I use this format of file submission does it happen HTML Component: <div class="dropzone" [class.visible]="onDragViewVisible" (dragenter) = "changeView($event)" (dragleave) = "changeView($event)" (drop) = "onFileDrop($event)" [formGroup]="form" > <input type = "file" name="dragndrop"/><br/><br/> <span class = "uitk-icon uitk-icon-folder_open lg-icon"></span><br /> <h3>Drop file here</h3> </div> Typescript: onFileDrop(event: any) { event.preventDefault(); console.log(event.dataTransfer.files); this.processFile(event.dataTransfer.files); } private processFile(files: FileList){ if(files[0].type == "application/vnd.ms-excel" || files[0].type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){ this.displayConfirmationView(); console.log(files[0]); if (files.length > 0) { const file = files[0]; this.form.get('dragndrop')!.setValue(file); } console.log(files[0]); const formData = new FormData(); formData.append('file', this.form.get('dragndrop')!.value); this.uploadService.upload(formData).subscribe( (res) => { this.response = res; this.imageURL = `${this.DJANGO_SERVER}${res.file}`; console.log(res); console.log(this.imageURL); }, (err) => { console.log(err); } ); } else { this.errorDialog.displayNotification(); this.displayDefaultView(); } } -
How to display a video that is not in static or media folder in Django Template?
I'm trying to add a video with html video tag in the Django template. The video path should come from /var/www/videos path. I have tried these settings below. STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "assets/static"), '/var/www/videos/', ] STATIC_ROOT = os.path.join(BASE_DIR, "assets/staticfiles") Also, my urls.py file is below. urlpatterns = [ path('', index, name='index'), path('terms/', terms, name='terms'), path('privacy/', privacy, name='privacy'), path('error_page/', error, name='error'), path('admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and I have added the video to the template as follows. <video src="{% static 'test101/test101_2021-07-13-12-35-16.mp4' %}"></video> However, I'm getting Failed to load resource: the server responded with a status of 404 (Not Found) error. How can I fix this issue and display my video on the Django template? -
How to change text color of certain row in django admin result list
When we enter the django admin site, we can see the result list of Modeladmin. And I want to change the row text color depending on the certain field value. How can i change text color of row when the field has a certain value? -
Django html page not updating on refresh
I want to know how to update the values in the html page with a simple refresh rather than having to restart the server, Has anyone come accross this and how can I fix it? -
CSS grid in landing django project
Right now I'm on the final stage of my landing project. Trying to understand css grid, but a little bit confused with the my previous code. Here is my image: IMAGE source I would like to center horizontaly and verticaly icons and text with the title in the white background box. Will be very thankful for the help <!DOCTYPE html> {% load static %} <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Home page</title> <link rel="stylesheet" href="{% static 'style.css' %}"> <script src="https://kit.fontawesome.com/5476287230.js" crossorigin="anonymous"></script> </head> <body> <div class="social-menu"> <ul> <li><a href="https://www.instagram.com/kseniia_ifbb_latvia"><i class="fab fa-instagram"></i></a></li> <li><a href="https://www.tiktok.com/@kseniiasherr"><i class="fab fa-tiktok"></i></a></li> <li><a href="https://www.facebook.com/profile.php?id=100009190064504"><i class="fab fa-facebook"></i></a></li> </ul> </div> <div class="title"> <h1>ЧТО ВЫ ПОЛУЧАЕТЕ?</h1> </div> <div id="background"></div> <div class="icons"> <li><i class="fas fa-utensils"></i></li> <li><i class="fas fa-dumbbell"></i></li> <li><i class="fas fa-clock"></i></li> <li><i class="fas fa-heartbeat"></i></li> </div> <div class="icons-text"> <li> <h1>План питания с учетом Ваших вкусовых потребностей</h1> </li> <li> <h1>Тренировки для любого уровня подготовки</h1> </li> <li> <h1>Максимально быстрые результаты</h1> </li> <li> <h1>Тело, о котором Вы могли только мечтать</h1> </li> </div> </body> </html> and: body { background: url(https://images.unsplash.com/photo-1534258936925-c58bed479fcb?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=889&q=80) no-repeat center center fixed; background-size: cover; margin: 0; } #background { position: fixed; top: 35%; width: 100%; height: 20%; background-color: white; z-index: -1; opacity: 0.8; } .social-menu ul { position: absolute; top: 25%; left: … -
How to combine two columns in one in Django?
How to combine two columns in one in Django? What is equivalent to "select col1 | col 2 as bothcols from tbl ..." ? -
python django how save a input field under a associate user
I am trying to save a todo text under a associat user How to do that i attach my models.py file, forms.py file and views.py file. Please Help meenter image description here