Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
how to filter with django_filter object stored in filter_class
Is it possible to filter with filter_class object in methods of ViewSet class? class ClassViewSet(mixins....., DefaultApiViewSet): filter_class = ClassFilter Something like: filtered = self.filter_class.base_filters.get('something_severity').filter(queryset, "value") -
Serializing Many to Many DRF
So I have predefined database structure like this: User: id User_1: user_=ForeignKey(User) User_2: user_1=ForeignKey(User_1) Something: owner=ForeignKey(User_2) users=ManyToMany(User_2) Well, I need to fill the table Something. Short story is that from front end I receive the ids of model User but to store I need User_2. One way I see right now is to write custom create method is serializer and do all manually. Are there other ways to solve it? And is it correct to use serializers.PrimaryKeyRelatedField to deal with ForeignKey when payload has next format? { "user": 1 } -
Multiple and single selection with pop up
I have a django project and I have a form in this project. After the selection is made, the pop-up will close and I want the form to appear as written before the form is refreshed. How can I do that ? -
Django custom user model does not work on live server
I am extending the user model, and it works on my local server but does not work on Heroku, nor does it work on Python anywhere. I am using Postgres. It's a fresh database. I can't even run a makemigration due to this error. My setting file also have the error: (mysite-virtualenv) 06:21 ~/go-all-nations-2-backend (main)$ python manage.py makemigrations /home/evolvingtech/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/environ/environ.py:784: UserWarning: Error reading /home/evolvingte ch/go-all-nations-2-backend/.env - if you're not configuring your environment separately, check this. warnings.warn( Traceback (most recent call last): File "/home/evolvingtech/go-all-nations-2-backend/manage.py", line 22, in <module> main() File "/home/evolvingtech/go-all-nations-2-backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/evolvingtech/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_f rom_command_line utility.execute() File "/home/evolvingtech/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/evolvingtech/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/evolvingtech/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/evolvingtech/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/evolvingtech/go-all-nations-2-backend/app_backend_api/models.py", line 8, in <module> from django.contrib.auth.models import User, AbstractBaseUser, _user_get_all_permissions, AbstractUser, AbstractBaseUser, Group, Permission, … -
how can I default a model that is already defaulted to the CurrentUserDefault()
I am creating a bar API where users can create their own bar fractions I want a way by which a user will create a bar contact that will automatically default to the bar that the user has created I already tried overriding the create method in my view models.py class Bar(models.Model): name = models.CharField(max_length=100) barOwner = models.OneToOneField(user, on_delete=models.CASCADE) secondaryUsers = models.CharField(max_length=255, default='jonathan', null=True) def __str__(self): return self.name # Bar contact Info class StoreContact(models.Model): options =( ("MTN", "MTN"), ("ORANGE","ORANGE"), ("NEXTEL", "NEXTEL") ) numberType = models.CharField(max_length=200, choices=options, default='MTN') number = PhoneNumberField(blank=True) bar = models.ForeignKey(Bar, related_name='contact', on_delete=models.CASCADE) def __str__(self): return self.numberType serializers.py class BarContactSerializer(serializers.ModelSerializer): bar = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = StoreContact fields = ('numberType', 'number', "bar") class BarSerializer(serializers.ModelSerializer): storeOwner = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) contact = BarContactSerializer(many=True, read_only=True,) class Meta: model = Bar fields = ('name', 'storeOwner','contact') views.py class BarContact(generics.ListCreateAPIView): queryset = StoreContact.objects.all() serializer_class = BarContactSerializer def perform_create(self, serializer): user = self.request.user.id try: serializer.save(bar_barOwner=user) except IntegrityError: raise ValidationError('something is wrong') -
Query database only on a particular column django ORM
I am new to Django and couldnt find the answer i was looking for so bear with me I have a model class called bid on an auction app that stores all bids that were placed on all items: class Bid(models.Model): title = models.CharField(max_length=64, blank=True) date_time = models.DateTimeField(default=timezone.now, blank=True) price = models.DecimalField(max_digits=4, decimal_places=2) user = models.CharField(max_length=64) now i want to query this table and have it return to me ALL the bid prices that were placed on a particular item, i have this line: bids = Bid.objects.all().filter(title=title) that returns all objects with that title, but i dont care for the other columns of this object, i just want the prices this is kinda stupid but i did try it: bids = bids.price ofcourse it didnt work -
Faust Streaming retry topic mechanism
I have two topics main_topic retry_topic I want if the logic fails in main_topic it should call retry_topic and if that fails so there should be max 3 retries that it should do. I've tried using sink in faust streaming what it does is that it yield result from my main topic to retry_topic but I'm still not able to limit it to 3 retries. Is there a way to do that in faust/kafka streaming because I know that celery has this feature.