Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change the display format of date in a DateTime field in Django?
Im using the django date picker widget with this in forms.py: class DateInput(forms.DateInput): input_type = 'date' and using this on the meta class in the modelForm: widgets = { 'birthdate': DateInput(format=('%Y-%m-%d'),) } at first without the format argument on the DateInput widget it just didnt work, now it works but the date is shown in the field with the format 'mm/dd/YYYY' and I want it to be shown with the format 'dd/mm/YYYY'. Ive tried with the different localization variables on settings.py, this is my current configuration: LANGUAGE_CODE = 'es-MX' TIME_ZONE = 'America/Hermosillo' USE_I18N = True USE_L10N = True USE_TZ = True DATE_INPUT_FORMATS = ('%d/%m/%Y', '%d-%m-%Y') the widget works right and the date value is correctly read and saved but i cant get it to be shown with the correct format on the input -
Updating account info error in UserUpdateForm
I am having a hard time figuring out what's wrong with my UserUpdateForm, I am not able to update the first_name and last_name field, but when i take out the those fields and then leave username and email it works well and uses can actually update their username and email, but somehow the firstname and lastname wouldn't just allow for me to make update to it. Can someone help me please ? class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ( 'username','email', 'first_name','last_name', 'profile_pic','hide_email', ) #widgets ={ # 'gender':forms.Select( #attrs={'class':'custom-select md-form'}), # } def clean_email(self): email = self.cleaned_data['email'].lower() try: account = User.objects.exclude(pk=self.instance.pk).get(email=email) except User.DoesNotExist: return email raise forms.ValidationError('Email "%s" is already in use.' % account) def clean_username(self): username = self.cleaned_data['username'] try: account = User.objects.exclude(pk=self.instance.pk).get(username=username) except User.DoesNotExist: return username raise forms.ValidationError('Username "%s" is already in use.' % username) def clean_first_name(self): first_name = self.cleaned_data["first_name"] try: account = User.objects.exclude(pk=self.instance.pk).get(first_name=first_name) except User.DoesNotExist: return first_name raise forms.ValidationError('UserFirstname "%s is already in use.' % first_name ) def save(self, commit=True): account = super(UserUpdateForm, self).save(commit=False) account.username = self.cleaned_data['username'] account.first_name = self.cleaned_data['first_name'] account.email = self.cleaned_data['email'].lower() account.profile_pic = self.cleaned_data['profile_pic'] if commit: account.save() return account My account edit view. def edit_account_view(request, *args, **kwargs): if not request.user.is_authenticated: return redirect("login") user_id = … -
how to add string to primary key in django model
i want my id to be "ssid"+ (autoimcrement id) example: ssid001 this is my user model class User(models.Model): id = models.CharField(primary_key=True, editable=False, unique=True, max_length=99999) phone = models.CharField(max_length=12, unique=True,default="") name = models.CharField(max_length=50,default="") email = models.EmailField(max_length=50,default="") -
Run a .ipynb file on clicking a web page button
I have written a python code that converts pixel values from a thermal camera to thermal image. I need this process to happen on clicking a button on a web page( just a button saying "start converting" or so). Please help! -
getting manager isn't available , auth.user has been swapped error in Django?
Note Tried everything available on stackoverflow for solution but my error is not resolved my models.py class User(AbstractUser): is_student = models.BooleanField('student status', default=False) is_creator = models.BooleanField('content creator status', default=False) class Classroom(models.Model): name = models.CharField(max_length=31) standard = models.PositiveSmallIntegerField( choices=STUDENT_STD, null=True, blank=True) division = models.CharField(max_length=3, null=True, blank=True) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # ExamSlot = models.ForeignKey(ExamSlot, on_delete=models.CASCADE) name = models.CharField(max_length=40) my view from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ObjectDoesNotExist from django.db import IntegrityError from django.shortcuts import get_object_or_404, render, redirect from rest_framework import exceptions, generics, permissions, status from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.views import APIView from .serializers import * from .models import Student from .forms import SignUpForm from rest_framework_simplejwt.tokens import RefreshToken, AccessToken from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from django.contrib.auth import get_user_model User = get_user_model() def user_register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) my forms.py from django import forms from django.contrib.auth.forms import UserCreationForm # from django.contrib.auth.models import User from django.contrib.auth import get_user_model User = get_user_model() class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, … -
How to send data from React Js to Django without using Django Rest API
Is it possible to send data from ReactJs to Django without using Rest API ? I have an app through which I've sent form data for registrations and got data from the database using the Django REST API but this time, I need to send some data that are not related to the database meaning I shouldn't need a serializer but is it possible ? Data (Json) from ReactJs { payment_data: { command_id: order._id, price: order.TotalPrice }, data: { return_url: "xxxxxxxxxx", cancel_url: "oooooooooo", shop_code: 1, }, } On Click (of a button on the front-end) I would like to send this data to django for further processing but I don't know how I could possibly do that without using Django Rest API -
How do I get Users from one database and save their Profile in another database using Django-Rest-Framework?
I am building a REST API that uses 2 postgresql databases: db1 (default) and db2. I want to get users from db2 and create a profile for them to store in db1. So basically, db2 is used for read-only. I already set databases (added DATABASES in settings.py and run migrate), and set managed=False in the User model but the users do not appear when I enter the admin page (I added User model in admin). -
How to dynamically create cron jobs with Django model?
I need to create a cron job for each object in a model. I researched about celery and crontab, but these libraries use a static crons directly from code. Any library that help to dynamically create a tasks to each object in a model? -
Displaying single Item from Database in django
I want to display single item by my choice. is there a way we can display a single item? Right now I am displaying all items using for loop. Here is my code for all items. Models.py from django.db import models # Create your models here. class Task(models.Model): title = models.CharField(max_length=200) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title views.py from django.shortcuts import render, redirect from django.http import HttpResponse # Create your views here. from .models import * from .forms import * def index2(request): tasks = Task.objects.all() context = {'tasks': tasks} return render(request, 'task/index2.html', context) Index2.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Home</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" /> <link rel="stylesheet" href="{% static '/css/style2.css' %}" /> </head> <body> {% for task in tasks %} {{task}} {% endfor %} </body> </html> -
error at /image_upload/ OpenCV(4.5.2) :-1: error: (-5:Bad argument) in function 'cvtColor' > - Expected Ptr<cv::UMat> for argument 'src'
**Hello I'm working on a web using django and I want to connect with the be cnn . model But after uploading an image to be processed, this error appears What's the problem? ** from django.http import request from django.shortcuts import render ,redirect from django.http import HttpResponse from .forms import Images from django.contrib.auth.decorators import login_required import cv2 import numpy as np from keras.models import load_model import h5py def image_upload(request): data = {} form=Images(request.POST or None, request.FILES or None) data["info"]=form if request.POST: if form.is_valid(): new_form = form.save(commit=False) new_form.user = request.user new_form.save() label_dict={0:'Covid19 Negative', 1:'Covid19 Positive'} img_size = 100 path = 'C:/Users/Dr.Esraa/Desktop/project_covid/covid_19%s'% new_form.Image.url img = cv2.imread(path) gray = cv2.cvtColor(np.float32(img), cv2.COLOR_RGB2GRAY) resized = cv2.resize(gray ,(img_size , img_size) ) data_array = np.array(resized)/255 data = resized.reshape(-1,img_size,img_size,1) model_loded = load_model(r"C:\Users\Dr.Esraa\Desktop\project_covid\covid_19\test_img") predectied = model_loded.predict(data) result=np.argmax(predectied,axis=1)[0] accuracy=float(np.max(predectied,axis=1)[0]) label=label_dict[result] data = {'label':label, 'result':result, 'accuracy':accuracy, 'url': new_form.Image.url, 'info': form} return render(request, 'test_img/test.html', data) return render(request, 'test_img/image_upload.html',data) error at /image_upload/ OpenCV(4.5.2) :-1: error: (-5:Bad argument) in function 'cvtColor' Overload resolution failed: src is not a numpy array, neither a scalar Expected Ptr<cv::UMat> for argument 'src' Request Method: POST Request URL: http://127.0.0.1:8000/image_upload/ Django Version: 3.2.4 Exception Type: error Exception Value: OpenCV(4.5.2) :-1: error: (-5:Bad argument) in function 'cvtColor' Overload resolution failed: src … -
DJANGO - HTML in models' help_text
I'm trying to store come HTML in the model help_text as shown: class InsurancePolicy(models.Model): supplier = models.ForeignKey(CustomerSupplier, on_delete=models.PROTECT, related_name='to_insurances_policies', verbose_name='Fornitore', help_text=mark_safe("""<a href="{% url 'registry:new_customerSupplier' %}">Aggiungilo qui!</a>""")) This way, if a supplier is not found, one can directly jump to page to add one by clicking on the help_text below the form field. this is the forms I use ( normal form using crispy ): class InsurancePolicyForm(forms.ModelForm): class Meta: model = InsurancePolicy exclude = ('documents', 'items') widgets = { 'supplier': autocomplete.ModelSelect2 (url='registry:supplier_autocomplete', attrs={ 'data-theme': 'bootstrap4', # Set some placeholder 'data-placeholder': 'Scrivi il fornitore ...', # Only trigger autocompletion after 3 characters have been typed 'data-minimum-input-length': 3, }, ) } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # CRISPY FORMS self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Row( 'company', 'nick_name', 'supplier', 'insurance_start_date', 'insurance_end_date', 'contract_num', ) ) Although the field is marked safe, the url is not built correctly. this is what I get by inspecting the source code from the browser: <small id="hint_id_supplier" class="form-text text-muted"><a href="{% url 'registry:new_customerSupplier' %}">Aggiungilo qui!</a></small> as you can see from the picture, overall the help_text is rendered correctly, but the href is not built correctly. thanks in advance for any help Carlo -
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?