Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model Multi Select form not rendering properly
I am trying to display all the categories to appear as a list that I can click and select from, just an exact replica of what I have in my admin panel, but it still display's as a list that isn't clickable. forms.py class ProfileEditForm(forms.ModelForm): """ Form for updating Profile data """ class Meta: model = Profile fields = [ "first_name", "last_name", "about_me", "profile_image", "username", "email", "categories", ] first_name = forms.CharField(label="First Name", max_length=63, required=False) last_name = forms.CharField(label="Last Name", max_length=63, required=False) about_me = forms.CharField(label="About Me", max_length=511, required=False) email = forms.EmailField(label="Email", disabled=True) username = forms.CharField(label="Username", disabled=True) profile_image = forms.ImageField(required=False) categories = forms.ModelMultipleChoiceField( queryset=Category.objects.all(), required=False, widget=forms.CheckboxSelectMultiple(), ) settings.html <div class='row'> <div class="col s12 m6"> {{form.categories.errors}} {{form.categories.label_tag}} {{form.categories}} </div> </div> Output -
image 404 in django template
I am making a catalog of film directors for an introduction to django exercise and im trying to load the images from my database to my template but is not working. All my steps: I added an imagefield to the directors model class, which I have then filled in from the admin version. Then in my view I have made a request to collect a list of all directors like so: directors = Directors.objects.all() and then I have returned it with render. In the template I have done this {%for director in directors%} <img src="{{director.director_image.url}}" alt="{{director.first_name}}"> {% endfor %} And everything is fine except that the images are not loaded, the alt with the names of the directors are ok :D (an advance). I get the feeling that somehow I have to define the url of the images??? because from the browser console it get the url of the images properly but it gives a 404. im really on my first days using django so I guess im missing something with how the media urls works. hope someone can help me. tysm <3 What I tried? I haven't tried anything else since I'm very new to django. I have searched … -
How to change the label in display_list of a field in the model in django admin
I have a model with some fields with a verbose_name. This verbose name is suitable for the admin edit page, but definitively too long for the list page. How to set the label to be used in the list_display admin page ? -
passing url parameters using custom url converter in django
I am getting this error when I use my custom url converter Reverse for 'user-update' with keyword arguments '{'pk': 'Rwdr4l3D'}' not found. 1 pattern(s) tried: ['users/(?P<pk>[a-zA-Z0-9](8,))/update/\\Z'] Question: why isn't the pk matching the regex whats wrong details given below urls.py from utils.url import HashIdConverter register_converter(HashIdConverter, "hashid") app_name = "users" urlpatterns = [ path("<hashid:pk>/update/", views.UserUpdateView.as_view(), name="user-update"), ******* utils/url.py class HashIdConverter: regex = f'[a-zA-Z0-9]{8,}' def to_python(self, value): return h_decode(value) def to_url(self, value): return h_encode(value) template I've tried using <a href="{% url 'users:user-update' pk=user.hashed_id %}" also, <a href="{% url 'users:user-update' user.hashed_id %}" where hashed_id is as below def hashed_id(self): return h_encode(self.id) neither of them is working -
choice modify in foreignkey Django or add default 'other' in foregin key
Department Name is a foreignkey in django, And I wanted to add new choice 'other' . Do know how to achieve that either by forms or ? -
NetSuite Script AWS SP API STS request
I am trying to connect to Amazon SP API through NetSuite scripts but unable to establish the connection, i am able to get the access token but when i try to create the authorization i keep getting the error that signature does not match. Need help to get the STS connection setup. Below is part of the STS request that i am trying. const amzDate = getAmzDate(); const datestamp = amzDate.split("T")[0]; var host = "sts.amazonaws.com"; //https://sts.amazonaws.com/?Version=2011-06-15&Action=AssumeRole&RoleSessionName=Test&RoleArn=myactualARN&DurationSeconds=3600 const canonicalUri = '/'; const canonicalQuerystring = "?Version=2011-06-15&Action=AssumeRole&RoleSessionName=Test&RoleArn=mayactualARNe&DurationSeconds=3600"; const canonicalHeaders = 'host:' + host + '\n' + 'x-amz-date:' + amzDate + '\n'; const signedHeaders = 'host'; const payloadHash = crypto.createHash({ algorithm: crypto.HashAlg.SHA256 }); const canonicalRequest = 'GET\n' +canonicalUri + '\n' +canonicalQuerystring + '\n' +canonicalHeaders + '\n' +signedHeaders + '\n' +payloadHash.digest().toLowerCase(); log.debug("canonicalRequest",canonicalRequest); const credentialScope = datestamp + '/' + REGION + '/' + SERVICE_NAME_STS + '/' + 'aws4_request'; const canonicalHash = crypto.createHash({ algorithm: crypto.HashAlg.SHA256 }); canonicalHash.update({ input: canonicalRequest }); const stringToSign = ALGORITHM + '\n' +amzDate + '\n' +credentialScope + '\n' +canonicalHash.digest().toLowerCase(); log.debug("stringToSign",stringToSign); const signingKey = getSignatureKey(amamzonConnectionKeysArray.secretkey, datestamp, REGION, SERVICE_NAME_STS); const signature = CryptoJS.HmacSHA256(stringToSign, signingKey); const authorizationHeader = ALGORITHM + ' ' + 'Credential=' + amamzonConnectionKeysArray.accesskey + '/' + credentialScope + ', ' + 'SignedHeaders=' … -
mod_wsgi.py no module namesd django Centos7
I have a django project which works fine in the development envirnonment. I seem to have set something wrong in my httpd .conf file. When I attempt to use production mode and to go to the page - I get an 500 Internal Server Error. My wsgi.py Module complains that it cannot find django. Error is: File "/var/www/trackx_proj/trackx_root/trackx/wsgi.py", line 17, in <module> [Tue Nov 08 11:54:17.140508 2022] [wsgi:error] [pid 2969] [remote xxx.xxx.95.97:56342] from django.core.wsgi import get_wsgi_application [Tue Nov 08 11:54:17.140549 2022] [wsgi:error] [pid 2969] [remote xxx.xxx.95.97:56342] ModuleNotFoundError: No module named 'django' In my configuration file I have: WSGIDaemonProcess trackx_proj python-home=/home/bakert/.local/share/virtualenvs/trackx_proj-2E2CC07X WSGIProcessGroup trackx_proj WSGIScriptAlias / /var/www/trackx_proj/trackx_root/trackx/wsgi.py I pointed this at the virtual environment for the user that I used when I created this app. It's all owned by apache.. If I change it to the www directory i.e.: WSGIDaemonProcess trackx_proj python-home=/var/www/trackx_proj/trackx_root WSGIProcessGroup trackx_proj WSGIScriptAlias / /var/www/trackx_proj/trackx_root/trackx/wsgi.py Then I get a recurring error in the log file: Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' Not sure why it cannot seem to find the right environment. Maybe I need to set up the virtual environment for the application under www ?? Any ideas about this … -
Django RadioSelect choices with "Other" Text Field - [Form not saving]
I'm trying to add a radioselet button and an 'other' option that includes a freeform text. How do I create this is in Django. I've gotten my form to have this input type and capture the information. However, my form refuses to save and validate the field. Here's my models.py file. Here's my forms.py file. Can you help me? Thank you! -
Django rest api create email login along with password
Hi. I've created the employee management system using django rest api. I've created the models, views and serializers like shown below. What i need is I've created employee details like his personal details as a register view, but when he login i want to use email and password field as a field to sign with jwt token. How to implement this. Models.py Class Employee (models.Model): Fname = models.charfield() Lname = models.charfield() Personal _email=models.Emailfield() Department= models.choicefield() Designation= models.charfield() Serializer.py Class Employeeserializer(models.Modelserializer): class Meta: model = Employee fields = '__all__ Views.py Registeremployeeview(createAPIview): serializer_class = Employeecreateserializer def post(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({ "user": serializer.data, "message": "User Created Successfully..!", }) Now i want to create login view. How to i make email and password login view and serializers without I haven't included that in my models. Alos i want to login and set authentication with jwt authentication. Please somebody help -
django csrf / how it works?
we have good page But if we add csrf token in the top of html template All head's content will move in body and head will be empty How it works? I think csrf does input and all info after input teleport in body :/ but why -
Plotly Dash - Change number abbreviations format
I have lots of tables and plots shown about transactions on my web app, with the frontend based on Dash. The issue is that Plotly uses d3 format to format all numbers, and d3 format doesn't include "Million" & "Billion". Therefore, I'm getting the abbreviations "G" & "T", that are used for example in "gigabytes" or "terabytes". Do you know any way of changing those ? I haven't found anything relevant online... Here are some examples: For the table, here is the corresponding code: format_number = Format().precision(2).scheme("s") format_amount = Format().precision(2).scheme("s").symbol(Symbol.yes).symbol_suffix(" €") table = DataTable( columns=[ { "name": ["Transactions", "Total number"], "id": "nb_operation", "type": "numeric", "format": format_number, }, { "name": ["Transactions", "Total amount"], "id": "amount_euro", "type": "numeric", "format": format_amount, }, ], [...] -
Django + Celery + Nginx
I try to run my django application in docker with Celery and Nginx. Docker-compose version: '3' services: helpdesk_web: build: context: ./ dockerfile: Dockerfile container_name: helpdesk_web volumes: - ./static:/usr/src/app/static - media:/usr/src/app/media ports: - "8000:8000" - "5678:5678" env_file: - ./.env restart: always depends_on: - helpdesk_db - helpdesk_redis helpdesk_db: image: postgres container_name: helpdesk_db volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env ports: - "5432:5432" environment: POSTGRES_DB: helpdesk_db POSTGRES_PASSWORD: itds POSTGRES_USER: itds nginx: build: context: ./docker/nginx dockerfile: Dockerfile container_name: helpdesk_nginx restart: on-failure depends_on: - helpdesk_web - helpdesk_db ports: - "80:80" volumes: - ./static:/usr/src/app/static - media:/usr/src/app/media helpdesk_redis: image: redis ports: - "6379:6379" helpdesk_celery: build: context: . dockerfile: Dockerfile command: celery -A helpdesk worker -l INFO --pool=solo depends_on: - helpdesk_web - helpdesk_redis helpdesk_celery-beat: build: context: . dockerfile: Dockerfile command: celery -A helpdesk beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler depends_on: - helpdesk_web - helpdesk_redis volumes: postgres_data: media: Dockerfile FROM python:3.10 WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip COPY requirements.txt . RUN pip install -r requirements.txt COPY . . RUN chmod +x entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] entrypoint.sh #! /bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi python manage.py … -
how to fix deployment of django app using elastic beanstalk
I am trying to use elastic beanstalk to deploy my little django app. the app runs locally fine and it appears that my EB stack is created fine, what's happening is that from the logs (eb-engine.log) it fails to run the container commands in the django.config file, which is: option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "personal_portfolio.settings" PYTHONPATH: "/var/app/current:$PYTHONPATH" AWS_STORAGE_BUCKET_NAME: "xxxx-personal-portfolio" AWS_S3_REGION_NAME: "us-east-1" RDS_USERNAME: "xxx" RDS_PASSWORD: "password" RDS_PORT: 5432 aws:elasticbeanstalk:container:python: WSGIPath: "personal_portfolio.wsgi:application" aws:elasticbeanstalk:environment:process:default: HealthCheckPath: "/about" MatcherHTTPCode: "200-499" container_commands: 01_makemigrations: command: "source /var/app/venv/*/bin/activate && python3 manage.py makemigrations --noinput" leader_only: true 02_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate --noinput" leader_only: true 03_createsu: command: "source /var/app/venv/*/bin/activate && python3 manage.py createsu" 04_collectstatic: command: "source /var/app/venv/*/bin/activate && python3 manage.py collectstatic --noinput" leader_only: true the logs don't say why? I am deploying using this script: #!/bin/bash python create_s3bucket.py eb init eb create portfolio1 -db.engine postgres --database.version 12 --database.username xxx --database.password "1234" is there a way to understand what is wrong? I have to say I deployed the same thing quicker writing Terraform. -
Django: How to download data in excel from frontend
We are having a HTML page where data is being populated in a table. The data in table comes from the API response. These APIs are being called using Django. The view.py file returns the data to HTML webpage. I am looking for a solution when customer clicks on the download button then the data which is being shown in the table should get downloaded in the excel file. Here, "transaction" contains the data returned by API <div class="card-header-left"> <i class="fa fa-print" style="font-size:22px;color:#c30038;margin-left: -3px;"></i> <i class="fa fa-download" style="font-size:22px;color:#c30038;margin-left: 40px;"></i> </div> <div class="card-block p-b-0"> <div class="table-responsive"> <div id="table-wrapper"> <div id="table-scroll"> <table class="table table-hover m-b-0"> <thead> <tr> <th>Name</th> <th>Age</th> <th>Mobile</th> <th>Email</th> <th>Id</th> </tr> </thead> <tbody> {% load tag_filter %} {% for i in transaction %} <tr> <td class="{% if forloop.counter|divisibleby:2 %}list{% endif %}">{{i.name|slice:"0:20"}}</td> <td class="{% if forloop.counter|divisibleby:2 %}list{% endif %}">{{i.age }}</td> <td class="{% if forloop.counter|divisibleby:2 %}list{% endif %}">{{i.mobile}}</td> <td class="{% if forloop.counter|divisibleby:2 %}list{% endif %}">{{i.email}}</td> <td class="{% if forloop.counter|divisibleby:2 %}list{% endif %}">{{i.id}}</td> </tr> {% endfor %} -
Django: Are Django models dataclasses?
Can we say that Django models are considered dataclasses? I don't see @dataclass annotation on them or on their base class model.Models. However, we do treat them like dataclasses because they don't have constructors and we can create new objects by naming their arguments, for example MyDjangoModel(arg1= ..., arg2=...). On the other hand, Django models also don't have init methods (constructors) or inherit from NamedTuple class. What happens under the hood that I create new Django model objects? -
Do I have to verify JWT for every api calls?
I am making a simple project for practicing django. I used simplejwt to implement the auth process with JWT. Also, I have React frontend environment and making API calls using axios, but there are some questions: Do I have to verify JWT for every API call? And which is the better way to verify the token: Making an API request from the client(frontend) to "api/token/verify/" with token, or designing every API starting from calling its verifying API on the server-side(but it seems a little weird because every API need to require the token additionally)? For instance, if I write a comment and click the submit button, the former does call the token verifying API before calling the writing API on the client side(React), while the latter only calls the writing API but the API itself calls the verifying API before handling its own API logic. Thanks in advance. -
How to create as many ModelForms as the Select option value
I want to create x ModelForms - x is the value of the selected option value of a Select. If Select option value = 5, then I want to create 5 ModelForms How can I achieve that? -
Assertion fctx error using Django & Opencv
I have a python app with the Django framework. I display a video stream with detection using yolov5, sometimes the stream crashes and it's display this eroor Assertion fctx->async_lock failed at libavcodec/pthread_frame.c:167 I think that it happens because of my detection() function . the goal of the detection() function is to send to the client the percent of the detection any time that I have detect when my custom object appears in the video. cap = cv2.VideoCapture("video.mp4") def stream(): model.iou=0.5 while (cap.isOpened()): ret, frame = cap.read() if not ret: print("Error: failed to capture image") break results = model(frame,augment=False) for i in results.render(): data=im.fromarray(i) data.save('demo.jpg') annotator = Annotator(frame, line_width=2, pil=not ascii) im0 = annotator.result() image_bytes = cv2.imencode('.jpg', im0)[1].tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + image_bytes + b'\r\n') cap.release() cv2.destroyAllWindows() def detection(): if(cap.isOpened()): ret,frame = cap.read() if not ret: print("Erorr:faild to capture image") data={"isRunning":False} dataJson=json.dumps(data) return dataJson results = model(frame, augment=False) pred = results.pandas().xyxy[0] for index, row in pred.iterrows(): if float(row['confidence']) > 0.15: detection=float(row['confidence']) det = '%.2f' % detection data={"det":det,"isRunning":cap.isOpened()} dataJson=json.dumps(data) return dataJson data={"isRunning":cap.isOpened()} dataJson=json.dumps(data) return dataJson data={"isRunning":False} dataJson=json.dumps(data) return dataJson def video_feed(request): return StreamingHttpResponse(stream(), content_type='multipart/x-mixed-replace; boundary=frame') def detection_percentage(request): return HttpResponse(detection()) I think that I need to read the frame from the video … -
send dotted value query in table column name in django
I'm getting data from a remote database with Django, all my operations are completed, but there is a table, I can't get data from here, when I ask a question in the form of the table title Shape.STLength(), it gives a column name not found warning. tablo5.objects.using('database').all() -
OSError: [Errno 34] Result too large
I am new to python and have been developing my first project, which you can find here: https://github.com/XhesB/my_happy_place. There is something that is not quite working because as soon as I do an action, for example, adding a book, I get an error that I can't reach the site, and on the terminal, I get this error: OSError: [Errno 34] Result too large. I have to run the server from the beginning, do another action, and it starts all over again. I removed all integers I had, and even converted them from int to string. Can I also say that it was working yesterday and today is not? Please help. -
Project created but its fields are empty when sent from React to Django API
I've been working on this React + Django APP. And I have been making a simple CRUD functionality into this app. everything goes fine but when i came to create project and send it to the django database, it gets created but when i look at it at projects/list it only shows the delete button and and image field which is not important, i only want the title and body fields to be shows This is views.py class CreateProjectView(viewsets.ModelViewSet): serializer_class = ProjectSerializer def post(self, request): project = ProjectSerializer(data=request.data) if project.is_valid(raise_exception=True): project.save() return Response(project.data) urls.py create_project = CreateProjectView.as_view({"get": "post"}) urlpatterns = [ path("project/create", create_project, name="create-project"), ] Now React CreateProject.js import React, { useState } from 'react' const CreateProject = () => { let [project, setProject] = useState([]) let [title, setProjectTitle] = useState("") let [body, setProjectBody] = useState("") const handleChangeTitle = (value) => { setProjectTitle(project => ({ ...title, 'title': value})) console.log("Title:", value) } const handleChangeBody = (value) => { setProjectBody(project => ({ ...body, 'body': value})) console.log("Body: ", value) } let createProject = async () => { fetch('http://localhost:8000/api/project/create', { method: "POST", headers: { 'Content-Type': "application/json" }, // title: JSON.stringify(project_title), // title: project_title, // body: project_body, // image: "hello", // title: title, // body: … -
Class-based Django API only GET method. It's possible?
I'm building a class-based only GET method API with Django and Rest Framework. However, looking on internet, it seems to be impossible to do that. Here is my urls.py: from django.urls import path, include from rest_framework import routers from . import views api_router = routers.DefaultRouter() api_router.register(r"get_foo_id", views.GetFooIdViewSet) urlpatterns = [ path( "", include(api_router.urls)), ] views.py from app.models import * from app.serializers import * from rest_framework import viewsets from django_filters.rest_framework import DjangoFilterBackend class GetFooIdViewSet(viewsets.ModelViewSet): queryset = Foos.objects.all() serializer_class = FoosSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['foo_id'] It's really impossible? -
Return html tag by calling python function in django template
Guys actually i am expecting the django view should return only the tag like def load_tags(): return httpresponse("<span>span tag</span>") def home(request): return render(request, 'index.html',{"func":load_tags()}) html file <h2>Calling python function {{ func }} </h2> -In browser it displayed as Calling python function <HttpResponse status_code=200, "text/html; charset=utf-8"> -But i am expecting as Calling python function span tag Guys can you help me to achieve this functionality -
Print dictionary value having a letter '
Sorry for the basic question. But I cannot find a solution of this problem. I'd like to print dictionary value at the Django terminal. Here, I have a dictionary c={'code': '12'} I just want to print 12 at the terminal But when I enter print(c.values()) in the terminal, nothing appears. I think the latter ' is the problem. What should I do? -
How to transform th function into decorator in Django?
I have the fucntion header which values I need to put into 3 urls, I don't want to request the values in every view and render the context, because it takes some lines. How can I make the decorator? def acc_profile(request): refferals, balance= header(request) context = {'refferals':refferals,'balance':balance} return render(request, 'accounts/profile.html') def header(request): user_id = request.user.id refferals = Customer.objects.filter(name_id=user_id).values("refferals").first())['refferals'] balance = Customer.objects.filter(name_id=user_id).values("nickname").first())['nickname'] How can I make the def header into decorator and upper def acc_profile just put @header for example