Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse Relationship Django Rest Framework
i have this serializer of a Photo, that translates uploaded photos to URL class EntityPhotosSerializer(serializers.ModelSerializer): image = serializers.SerializerMethodField('get_img') def get_img(self, entity_photo): if not entity_photo.image: raise NotFound request = self.context.get('request') return request.build_absolute_uri(entity_photo.image.url) class Meta: model = EntityPhoto fields = ('user', 'entity', 'image',) And this serializer is based on a model that's connected to Entity Model reverse relationship. class EntityPhoto(models.Model): user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, related_name='entity_photo_user') entity = models.ForeignKey(Entity, on_delete=models.CASCADE, null=False, related_name='entity_photo') image = models.FileField(upload_to='entities/') created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) The class Entity class Entity(models.Model): Has no fields connecting to EntityPhotos, but i'd like to add the photos to Entity Serializer class EntityCreateSerializer(serializers.ModelSerializer): class Meta: model = Entity fields = '__all__' And i would like to show the EntityPhotos that have Entity_id=pk from url. So that whenever i make a get request to entity/1 i want to see also the photos that have entity_id == 1. Do you have any idea how to do that? -
Error in Pipenv when trying to install django
OK I was learning Django and they told me to use VS CODE so I installed it and when I opened the terminal and did some beginner stuff and then the teacher told me to use pipenv to install Django he used "pipenv install Django" but when I did I received this error Here is link to image please tell me what to do. -
How to use basic deleteview
I start use DeleteView of django.views.generic. However I am still confused about DeleteView Document says you don't need to do anything in DeleteView apart from UpdateView,CreateView So,,,,is this correct?? It doesn't delete the item. in urls.py path('preaction/<int:pk>/delete', PreActionDeleteView.as_view(), name="pre-action-delete"), in views.py class PreActionDeleteView(LoginRequiredMixin, DeleteView): model = PreAction success_url = reverse_lazy("pre-action-list") def delete(self, request, *args, **kwargs): success_url = self.get_success_url() messages_text = "deleted" messages.success(self.request, messages_text) return HttpResponseRedirect(success_url) -
What does a function in a django model do?
i wrote this function in django model that would help send and get messages but tbh i do not understand what the code exactly does because the tutorial teacher didn't explain anything about the code and for days now i have been trying to figure out what the code does with no solutions yet. I do not just want to copy and paste code from a tutorial, i want to also understand what each code does so that's why i would appreciate anyhelp. The code def get_messages(user): messages = Message.objects.filter(user=user).values('recipient').annotate(last=Max('date')).order_by('-last') users = [] for message in messages: users.append({ 'user': User.objects.get(pk=message['recipient']), 'last': message['last'], 'unread': Message.objects.filter(user=user, recipient__pk=message['recipient'], is_read=False).count() }) return users complete models.py class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='from_user') recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='to_user') body = models.TextField(max_length=1000, blank=True, null=True) date = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def send_message(from_user, to_user, body): sender_message = Message( user=from_user, sender=from_user, recipient=to_user, body=body, is_read=True) sender_message.save() recipient_message = Message( user=to_user, sender=from_user, body=body, recipient=from_user,) recipient_message.save() return sender_message def get_messages(user): messages = Message.objects.filter(user=user).values('recipient').annotate(last=Max('date')).order_by('-last') users = [] for message in messages: users.append({ 'user': User.objects.get(pk=message['recipient']), 'last': message['last'], 'unread': Message.objects.filter(user=user, recipient__pk=message['recipient'], is_read=False).count() }) return users views.py if needed def Inbox(request): messages = Message.get_messages(user=request.user) active_direct = None directs = None … -
service postgres not running in docker
I want to change my project Django with postgres to docker and then I make Dockerfile and docker-compose.yml my Dockerfile FROM python:3.10.0-slim-buster ENV APP_HOME=/app RUN mkdir $APP_HOME RUN mkdir $APP_HOME/staticfiles ENV PYTHONBUFFERED=1 RUN apt-get update \ && apt-get install -y build-essential \ && apt-get install -y libpq-dev \ && apt-get install -y gettext \ && apt-get -y install netcat gcc postgresql \ && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ && rm -rf /var/lib/apt/lists/* WORKDIR $APP_HOME RUN pip install --upgrade pip COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY ./docker/local/django/entrypoint /entrypoint RUN sed -i 's/\r$//g' /entrypoint RUN chmod +x /entrypoint ENTRYPOINT [ "/entrypoint"] my docker-compoae.yml version: "3" services: api: container_name: estate-api-container build: context: . dockerfile: ./docker/local/django/Dockerfile command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/app - static_volume:/app/staticfiles - media_volume:/app/mediafiles ports: - "8000:8000" env_file: - .env depends_on: - db db: container_name: estate-db-postgres12 image: postgres:12.0-alpine ports: - 5432:5432 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_DB=${POSTGRES_DB} volumes: static_volume: media_volume: postgres_data: entrypoint #!/bin/sh if [ "$DATABASE" = "estate1" ] then echo "Waiting for postgres..." while ! nc -z $POSTGRES_HOST $POSTGRES_PORT; do sleep 0.1 done echo "PostgreSQL started" fi exec "$@" when I run the command docker-compose build successfully build, my problem … -
what should we do to change page through link in django in urls, views?
Geography from this button i need to go on gallery.html. urlpatterns = [ path('',include('my_app.urls')), path('gallery',include('my_app.urls')), path('admin/', admin.site.urls), ] def gallery(request): return render(request, 'gallery.html') -
How to install uwsgi on windows?
I'm trying to install uwsgi for a django project inside a virtual environment; I'm using windows 10. I did pip install uwsgi & I gotCommand "python setup.py egg_info". So to resolve the error I followed this SO answer As per the answer I installed cygwin and gcc compiler for windows following this. Also changed the os.uname() to platform.uname() And now when I run `python setup.py install``. I get this error C:\Users\Suhail\AppData\Local\Programs\Python\Python39\lib\site-packages\setuptools\_distutils\dist.py:275: UserWarning: Unknown distribution option: 'descriptions' warnings.warn(msg) running install C:\Users\Suhail\AppData\Local\Programs\Python\Python39\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools. warnings.warn( using profile: buildconf/default.ini detected include path: ['/usr/include', '/usr/local/include'] Patching "bin_name" to properly install_scripts dir detected CPU cores: 4 configured CFLAGS: -O2 -I. -Wall -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -DUWSGI_IPCSEM_ATEXIT -DUWSGI_EVENT_TIMER_USE_NONE -DUWSGI_EVENT_FILEMONITOR_USE_NONE -DUWSGI_VERSION="\"2.0.19.1\"" -DUWSGI_VERSION_BASE="2" -DUWSGI_VERSION_MAJOR="0" -DUWSGI_VERSION_MINOR="19" -DUWSGI_VERSION_REVISION="1" -DUWSGI_VERSION_CUSTOM="\"\"" -DUWSGI_YAML -DUWSGI_PLUGIN_DIR="\".\"" -DUWSGI_DECLARE_EMBEDDED_PLUGINS="UDEP(python);UDEP(gevent);UDEP(ping);UDEP(cache);UDEP(nagios);UDEP(rrdtool);UDEP(carbon);UDEP(rpc);UDEP(corerouter);UDEP(fastrouter);UDEP(http);UDEP(signal);UDEP(syslog);UDEP(rsyslog);UDEP(logsocket);UDEP(router_uwsgi);UDEP(router_redirect);UDEP(router_basicauth);UDEP(zergpool);UDEP(redislog);UDEP(mongodblog);UDEP(router_rewrite);UDEP(router_http);UDEP(logfile);UDEP(router_cache);UDEP(rawrouter);UDEP(router_static);UDEP(sslrouter);UDEP(spooler);UDEP(cheaper_busyness);UDEP(symcall);UDEP(transformation_tofile);UDEP(transformation_gzip);UDEP(transformation_chunked);UDEP(transformation_offload);UDEP(router_memcached);UDEP(router_redis);UDEP(router_hash);UDEP(router_expires);UDEP(router_metrics);UDEP(transformation_template);UDEP(stats_pusher_socket);" -DUWSGI_LOAD_EMBEDDED_PLUGINS="ULEP(python);ULEP(gevent);ULEP(ping);ULEP(cache);ULEP(nagios);ULEP(rrdtool);ULEP(carbon);ULEP(rpc);ULEP(corerouter);ULEP(fastrouter);ULEP(http);ULEP(signal);ULEP(syslog);ULEP(rsyslog);ULEP(logsocket);ULEP(router_uwsgi);ULEP(router_redirect);ULEP(router_basicauth);ULEP(zergpool);ULEP(redislog);ULEP(mongodblog);ULEP(router_rewrite);ULEP(router_http);ULEP(logfile);ULEP(router_cache);ULEP(rawrouter);ULEP(router_static);ULEP(sslrouter);ULEP(spooler);ULEP(cheaper_busyness);ULEP(symcall);ULEP(transformation_tofile);ULEP(transformation_gzip);ULEP(transformation_chunked);ULEP(transformation_offload);ULEP(router_memcached);ULEP(router_redis);ULEP(router_hash);ULEP(router_expires);ULEP(router_metrics);ULEP(transformation_template);ULEP(stats_pusher_socket);" *** uWSGI compiling server core *** [thread 1][gcc] core/utils.o [thread 2][gcc] core/protocol.o [thread 3][gcc] core/socket.o [thread 0][gcc] core/logging.o In file included from In file included from core/logging.c:2core/socket.c:1 : : ./uwsgi.h:172:10:: fatal error: sys/socket.h: No such file or directory #include sys/socket.h: No such file or directory #include <sys/socket.h>sys/socket.h: No such file or directory #include ^~~~~~~~~~~~~~^~~~~~~~~~~~~~ cc^~~~~~~~~~~~~~o mm ppiillaattiioonn cttoeemrrpmmiiilnnaaatttieeoddn.. In file included from t rcore/utils.c:1mi: n … -
Data from back end not showing in front end using django
I am trying to insert data into my frontend but not sure what I did wrong here. Here is the code... I don't have any errors showing in my terminal or web browser. my views.py from django.shortcuts import render, get_list_or_404 from adopt.models import Adopt Create your views here. def adopt(request): return render(request, 'adopts/adopt.html') def adopt_detail(request, id): single_pet = get_list_or_404(Adopt, pk=id) data = { 'single_pet': single_pet, } return render(request, 'adopts/adopt_detail.html', data) def search(request): adopt = Adopt.objects.order_by('-created_date') if 'keyword' in request.GET: keyword = request.GET['keyword'] if keyword: adopt = adopt.filter(description__icontains=keyword) data = { 'adopt': adopt, } return render(request, 'adopts/search.html', data) my models.py from django.db import models from datetime import datetime from ckeditor.fields import RichTextField Create your models here. class Adopt(models.Model): pet_gender = ( ('F','Female'), ('M', 'Male'), ) state_choice = ( ('AL', 'Alabama'), ('AK', 'Alaska'), ('AZ', 'Arizona'), ('AR', 'Arkansas'), ('CA', 'California'), ('CO', 'Colorado'), ('CT', 'Connecticut'), ('DE', 'Delaware'), ('DC', 'District Of Columbia'), ('FL', 'Florida'), ('GA', 'Georgia'), ('HI', 'Hawaii'), ('ID', 'Idaho'), ('IL', 'Illinois'), ('IN', 'Indiana'), ('IA', 'Iowa'), ('KS', 'Kansas'), ('KY', 'Kentucky'), ('LA', 'Louisiana'), ('ME', 'Maine'), ('MD', 'Maryland'), ('MA', 'Massachusetts'), ('MI', 'Michigan'), ('MN', 'Minnesota'), ('MS', 'Mississippi'), ('MO', 'Missouri'), ('MT', 'Montana'), ('NE', 'Nebraska'), ('NV', 'Nevada'), ('NH', 'New Hampshire'), ('NJ', 'New Jersey'), ('NM', 'New Mexico'), ('NY', 'New York'), ('NC', … -
Generating new unique uuid4 in Django for each object of Factory class
I have a Model Sector which has a id field (pk) which is UUID4 type. I am trying to populate that table(Sector Model) using faker and factory_boy. But, DETAIL: Key (id)=(46f0cf58-7e63-4d0b-9dff-e157261562d2) already exists. This is the error I am getting. Is it possible that the error is due to the fact that everytime I am creating SectorFactory objects (which is in a different django app) and the seed gets reset to some previous number causing the uuid to repeat? Please suggest some ways as to how I shall get unique uuid for each Factory object? SectorFactory class import uuid from factory.django import DjangoModelFactory from factory.faker import Faker from factory import Sequence class SectorFactory(DjangoModelFactory): id = uuid.uuid4() name = Sequence(lambda n: f'Sector-{n}') class Meta: model = 'user.Sector' django_get_or_create = ['name'] Class Sector class Sector(models.Model): id = models.UUIDField(primary_key=True, default = uuid.uuid4, editable=False) name = models.CharField(max_length=100) class Meta: db_table = 'sector' constraints = [ models.UniqueConstraint('name', name = 'unique_sector_name') ] The script which creates the custom command to create SectorFactory objects. from types import NoneType from django.core.management.base import BaseCommand from user.factories import SectorFactory class Command(BaseCommand): help = 'Generate fake data and seed the models with them.' def add_arguments(self, parser) -> None: parser.add_argument( '--amount', type=int, … -
How to solve local variable error with forloop in django?
Info: I want to get data from context. The context data is coming from for loop function. Problem: I am getting this local variable 'context' referenced before assignment def CurrentMatch(request, match_id): match = Match.objects.get(id=match_id) match_additional = MatchAdditional.objects.get(match=match) innings = match_additional.current_innings recent = Score.objects.filter(match=match).filter(innings=innings).order_by('over_number')[::-1][:1] for score in recent: context = { "ball_number": score.ball_number, "over_number": score.over_number, } return HttpResponse(json.dumps(context)) -
Can't run python manage.py runserver
Hello~ I have installed django-bootstrap-ui-2.0.0 and django-admin startproject, and tried both python and python3 manage.py runserver. However, it says that no such file or directory. Am I missing some functions that have to pip install? Much thanks! C:\Users\user\AppData\Local\Programs\Python\Python310\python.exe: can't open file 'C:\ Users\user\PycharmProjects\Pyshop\manage.py': [Errno 2] No such file or directory PS C:\Users\user\PycharmProjects\Pyshop> -
Change django modal field passing in a attribute
The modal is "account" and I wanna change its integer field "balance" The below code is working: account.balance += amount But the following code is not working: balance = account.balance balance += amount I don't know why it is not working just by holding it in a variable. -
Unable to Pass UUID string to API endpoint using POSTMAN Correctly
The API endpoint is something like that, at django backend /accounts/id/uuid:pk/some_action/ in the models it is defined as id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) The apiview accepts requests and pk which is uuid as pk. @api_view(['PUT']) def some_action(request, pk): when i'm making a request with uuid it is giving me following error Not Found: /accounts/user/{id}/some-action/ [12/Feb/2022 18:41:28] "PUT /accounts/id/%7Bid%7D/some-action/ HTTP/1.1" 404 4930 in Postman i configure the url like this /accounts/id/{id}/some-action/ So what might be the problem in passing the uuid ? -
Reverse relations Image Serialization DRF
I have a Photo serializer that shows me an URL of the photo, and i want to include this reverse relationship in EntityAPIView, so that i can see on a particular Entity the images related to the entity. If i do it like so (just put the related name='entityphotos' into fields, it works, but shows me the IDs of the EntityPhotos instead of URLS.) Do you have any idea how to show the urls? class SpecialistSerializer(serializers.ModelSerializer): reviews_quantity = serializers.IntegerField(source="get_reviews_quantity") class Meta: model = Entity fields = ('id', 'entity_name', 'slug', 'created_at', 'updated_at', \ 'entity_category', 'entity_service', 'entity_animal', \ 'entity_member', 'entity_email', 'entity_address', 'entity_city', \ 'entity_zip_code', 'entity_description', 'entity_phone', \ 'entity_nip', 'gallery', 'points_from_reviews', 'reviews_quantity', \ 'logo', 'payment_method_cards', 'payment_method_cash', \ 'payment_method_blik', 'payment_method_wire', 'payment_method_installments', \ 'creator', 'lat', 'lng', 'img_map', 'entityphoto', ) class SpecialistDetailAPIView(generics.RetrieveAPIView): queryset = Entity.objects.all() serializer_class = SpecialistSerializer lookup_field = 'pk' class Entity(models.Model): ...... class EntityPhoto(models.Model): user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, related_name='entity_photo_user') entity = models.ForeignKey(Entity, on_delete=models.CASCADE, null=False, related_name='entityphoto') image = models.FileField(upload_to='entities/') created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) class EntityPhotosSerializer(serializers.ModelSerializer): image = serializers.SerializerMethodField('get_image') def get_image(self, entity): if not entity.image: return request = self.context.get('request') return request.build_absolute_uri(entity.entity.url) class Meta: model = EntityPhoto fields = ('user', 'entity', 'image',) -
How do I add buttons using javascript in a bunch of divs generated by Django through loop?
I am working on a Django project, where I have made a bunch of HTML divs. I want to add a single button on each div. In the image above, I have created a div of class card-footer with Django for loop. I want to add a blue coloured like button on each of the divs using javascript but you can see in the image that it is being added into only one div. Here I am sharing my HTML template. <div id="posts" class="card"> <ul class="card-body"> {% for posts in page_view %} <li class="card"> <div class="card-header bg-success"> <h5 class="card-title"><a class="text-light" style="text-decoration: none;" href="{% url 'profile' posts.user.id %}">{{ posts.user }}</a></h5> <h6 class="card-subtitle text-light">{{ posts.timestamp }}</h6> </div> <div class="card-body"> <h3 class="card-text">{{ posts.post }}</h3> </div> {% include 'network/like.html' %} </li> {% empty %} <h6>No post availabel 😔</h6> {% endfor %} </ul> </div> Here is my network/like.html: <div class="card-footer"> <form action="{% url 'likepost' posts_id=posts.id %}" id="likeform" method="POST" style="display: inline;"> {% csrf_token %} <button id = "like" class="btn btn-link" type="submit">Like</button> </form> <small id="num_of_likes">{{ posts.likepost.all.count }}</small> {% block script %} <!-- <script> let posts_id = "{{ posts.id }}"; </script> --> <script src="{% static 'network/controller.js' %}"></script> {% endblock %} <button class="btn btn-link" style="text-decoration: none;">Comment</button> <a href="{% url … -
django-simple-history, TemplateDoesNotExist at /admin/shared_models/mannedsetting/1/history/ simple_history/object_history.html
I am using django-history-admin I have model class class MannedSetting(BaseModel): history = HistoricalRecords() class Meta: db_table = 't_manned_setting' confirm_msg = m.CharField(max_length=400) then in admin.py from simple_history.admin import SimpleHistoryAdmin class MannedSettingAdmin(SimpleHistoryAdmin): list_display = ["id","confirm_msg"] admin.site.register(MannedSetting,MannedSettingAdmin) There appears the history button in the edit page of MannedSetting instance However when clicking the button, this error comes. TemplateDoesNotExist at /admin/shared_models/mannedsetting/1/history/ simple_history/object_history.html Request Method: GET Request URL: http://localhost:8010/admin/shared_models/mannedsetting/1/history/ Django Version: 3.2.7 Exception Type: TemplateDoesNotExist Exception Value: simple_history/object_history.html Exception Location: /Users/whitebear/.local/share/virtualenvs/cinnamon-admin-mg9y4sUV/lib/python3.9/site-packages/django/template/loader.py, line 19, in get_template Python Executable: /Users/whitebear/.local/share/virtualenvs/cinnamon-admin-mg9y4sUV/bin/python Python Version: 3.9.10 Python Path: ['/Users/whitebear/MyCode/httproot/s_cdk/myadmin', '/Users/whitebear/MyCode/httproot/s_cdk/myadmin/my-shared-models', '/Users/whitebear/MyCode/httproot/s_cdk/myadmin/$PYTHONPATH', '/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/usr/local/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/whitebear/.local/share/virtualenvs/cinnamon-admin-mg9y4sUV/lib/python3.9/site-packages'] Server time: Sat, 12 Feb 2022 22:24:06 +0900 -
DRF is not updating the database
Here's the model: from django.db import models from datetime import datetime, timedelta # Create your models here. def set_expiration(): return datetime.today().date() + timedelta(days=30) class Customer(models.Model): email = models.EmailField(max_length=254, unique=True) created_on = models.DateField(auto_now_add=True) expires_on = models.DateField(editable=False, default=set_expiration()) def __str__(self): return self.email And this is the view: @api_view(['POST']) def update_customer(request): try: customer = Customer.objects.get(email=request.data['email']) except ObjectDoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = CustomerSerializer(instance=customer, data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) And the serilizer: from rest_framework import serializers from .models import Customer class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__' At this moment I have a record in database with expires_on set to 2022-03-14 and I want to update that to 2024-12-12 so I call the endpoint with the following data: { "email": "myemail@mydomain.com", "expires_on": "2024-12-12" } The view returns this: { "id": 1, "email": "myemail@mydomain.com", "created_on": "2022-02-12", "expires_on": "2022-03-14" } This is the existing data. expires_on is not updated with the new value. I get no error and no exception. It just doesn't work. -
Unabled to deploy django + apache on aws Ubuntu server
I am trying to deploy a Django Application using Apache on an Ubuntu Server, I am having a weird error (500 internal error server error) when using port :80. I made some test using port :8000 running the command: python3 manage.py runserver 0.0.0.0:8000 And the application is working without any problem there, but when I try to access the application using port 80 it does work. My apache config file looks like this: <VirtualHost *:80> Alias /static /home/ubuntu/gh_system/static <Directory /home/ubuntu/gh_system/static> Require all granted </Directory> <Directory /home/ubuntu/gh_system/HRSYSTEM> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess HRSYSTEM python-home=/home/ubuntu/gh_system/env python-path=/home/ubuntu/gh_system> WSGIProcessGroup HRSYSTEM WSGIScriptAlias / /home/ubuntu/gh_system/HRSYSTEM/wsgi.py -
How to create timer in django
I want ,when user click a button a timer start and show it top menu. if user close website or navigate other page it's work. show hh:mm:ss or only minute ,start from user clicked on button. -
Run python script with multiple users accessing Django server
I have built a python script to run some process in downloading files and serve to users, I also built a website and added it to the Django framework, Now it is working properly for a single users (tested in the development environment, not a production environment). For example, If one user is using the website to request a particular file the background script runs properly and completes the task, and make files on the server... but if multiple users try to input the file at the same time, the backend python code is run but the Django produces an error. Is there a way that each individual user will have a separate instance of the script running for them without interrupting the process of other users? In views.py file : def index(request): if(request.method == "POST"): # here I call the function of other python files to run the script # the process may take like 15 - 30 sec based on internet speed # return a FileResponce of the file to be served to the user -
How to restore default celery backend_cleanup task in django?
I'm using Django celery-beat with a Redis backend. I accidentally deleted the celery.backend_cleanup Crontabschedule, which deleted the Periodic task that was using it. How do I put them back? From the celery docs: result_expires Default: Expire after 1 day. Time (in seconds, or a timedelta object) for when after stored task tombstones will be deleted. A built-in periodic task will delete the results after this time (celery.backend_cleanup), assuming that celery beat is enabled. The task runs daily at 4am. A value of None or 0 means results will never expire (depending on backend specifications). -
I am getting an Integrity Error django rest framework?
enter image description here i am getting an error of UNIQUE constraint failed: auth_user.username myuser = User.objects.create_user(username, email, pass1) -
Django models choice textField mapping
I am building a website for myself I am updating my projects from django admin I wanted to create a custom field which is a map of choice(tag color) and tag text. I want to make it look something like this This is my model class Project(models.Model): projectTemplate = CloudinaryField('image') projectTitle = models.TextField(default="Title ") desc = models.TextField(default="not mentioned") projectLink = models.URLField(max_length=200, default="not mentioned") created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.projectTitle} - {self.desc[:15]} ..' views.py def projects(request): Projects = Project.objects.all() return render(request, 'devpage/projects.html',{'Projects': Projects}) This is my current DTL {% for project in Projects %} <div class="col"> <div class="card shadow-sm"> <img src="{{ project.projectTemplate.url }}" height="225" width="100%"> <div class="card-body"> <h6 class="text-center"> {{ project.projectTitle }} </h6> <p class="card-text">{{ project.desc }}</p> <div class="mb-3"> <span class="badge rounded-pill bg-secondary">Django</span> <span class="badge rounded-pill bg-success">Python</span> </div> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <button type="button" class="btn btn-sm btn-warning btn-outline-secondary"><a href="{{ project.projectLink }}" target="_blank" type="button" class="btn">View</a></button> </div> <small class="text-muted">{{ project.created_at }}</small> </div> </div> </div> </div> {% endfor %} I want a custom model field which takes choice of label color and corresponding text with dynamic size I tried using json(field name tags) but its not interactive This is JSON DTL //Inner for loop for tags <div class="mb-3"> {% for color,text … -
Django, Html: How i can display the (number of page / total pages exist) on a pdf printout rendered
I have render an html template to pdf as response working with the framework Django and i want to add a footer contain the number of page in the pdf-printout / total number of pages for example if i have 2 pages in total , the first page should display to me 1/2, How i can do that please using html! I have tried with this code : <footer> {%block page_foot%} <div style="display: block;margin: 0 auto;text-align: center;"> page: <pdf:pagenumber /> </div> {%endblock%} </footer> But it display 0 as a first page. Thanks in advance -
Django Next.js handling responses when signing up
I am building my first Django + Next.js app and I want to display an alert when the user sign up if the username or the email already exists. Currently, if the user chooses an username/email that already exists there is a 400 error (what I want), otherwise everything is working fine. When I try it on postman, I get the explicit problem (username already exists or email already exists). But I didn't manage to achieve that on my frontend, even in the console, I don't see any message. RegisterView : class RegisterView(APIView): permission_classes = (permissions.AllowAny, ) def post(self, request): try: data = request.data email = data['email'] username = data['username'] password = data['password'] re_password = data['re_password'] if password == re_password: if len(password) >= 8: if not User.objects.filter(username=username).exists(): if not User.objects.filter(email=email).exists(): user = User.objects.create_user( email=email, username=username, password=password, ) user.save() if User.objects.filter(username=username).exists(): return Response( {'message': 'Account created successfully'}, status=status.HTTP_201_CREATED) else: return Response( {'message': 'Something went wrong when trying to create account'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: return Response( {'message': 'Account with this email already exists'}, status=status.HTTP_400_BAD_REQUEST,) else: return Response( {'message': 'Username already exists'}, status=status.HTTP_400_BAD_REQUEST) else: return Response( {'message': 'Password must be at least 8 characters in length'}, status=status.HTTP_400_BAD_REQUEST) else: return Response( {'message': 'Passwords do not …