Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Options for running on user demand asynchronous / background tasks in Django?
My Django app generates a complex report that can take upto 5 minutes to create. Therefore it runs once a night using a scheduled management command. That's been ok, except I now want the user to be able to select the date range for the report, which means the report needs to be created while the user waits. What are my options for running the tast in the background? So far I've found these: Celery - might work but is complex django-background-tasks looks like the right tool for the job but hasn't been updated for years, last supported Django is 2.2 The report/background task could be generated by AWS Lambda, basically in a microservice, which Django can call, Lambda can execute the background task then call the Django app with output once finished. This is what I did last time but not sure it would work now as I'd need to send the microservice 10mb of data to process. Use subprocess.popen which someone here said worked for them but other reports say it doesn't work from Django. -
Moving logic from Django views to models
This is my model: class Car(models.Model): make = models.CharField(max_length=30) model = models.CharField(max_length=30) rating = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)], default=0, blank=True) avg_rating = models.FloatField(default=0, blank=True) rates_number = models.IntegerField(default=0, blank=True) def __str__(self): return self.make + ' ' + self.model What's the best way to move the logic from the following perform_create function (in views.py) to my models? class CarRate(generics.CreateAPIView): serializer_class = CarRatingSerializer queryset = Car.objects.all() def perform_create(self, serializer): pk = serializer.validated_data['car_id'] rating = serializer.validated_data['rating'] queryset = Car.objects.all() car_queryset = get_object_or_404(queryset, pk=pk) if car_queryset.rates_number == 0: car_queryset.avg_rating = rating else: car_queryset.avg_rating = (car_queryset.avg_rating + rating)/2 car_queryset.avg_rating = round(car_queryset.avg_rating, 1) car_queryset.rates_number = car_queryset.rates_number + 1 car_queryset.save() -
How to get last number from url in djnago
http://127.0.0.1:8000/orders/order_complete/2022020762/ This is my link the last number 2022020762 I want to get this in a function how to get this? -
How to bulk update using CSV file in Django Rest Framework
class PackageRateListPrice(core_models.TimestampedModel): package = models.ForeignKey( PackageLabPrice, related_name="package_ratelist_price", on_delete=models.CASCADE ) offer_price = models.FloatField(null=True, blank=True, default=None) addon_price = models.FloatField(null=True, blank=True, default=None) is_active = models.BooleanField(default=True) My View: class BulkUpdatePackageRateListPriceUpdateFromFile(APIView): permission_classes = [IsAuthenticated, ] def put(self, request, pk, *args, **kwargs): upload_file = request.FILES.get('package_ratelist_file') file = upload_file.read().decode('utf-8') reader = csv.DictReader(io.StringIO(file)) data = [line for line in reader] for item in data: package_id = item['PackageID'] offer_price = item['OfferPrice'] addon_price = item['AddOnPrice'] is_active = item['IsActive'] models.PackageRateListPrice(package_id = package_id, offer_price = offer_price,addon_price = addon_price, is_active = is_active).save() return Response({"status": True}, status=status.HTTP_200_OK) In this i am trying to bulk update from a csv file. So first i need to check that package_id(first_field) exists or not if it exists then it will update for that id. Any help will be really appreciated. Thank you !! -
kubernetes django deployment with gunicorn
I am trying to deploy an empty image of alang/django using kubernetes on my minikube cluster. This is my manifest file for deployment. apiVersion: apps/v1 kind: Deployment metadata: name: django labels: app: django spec: replicas: 2 selector: matchLabels: pod: django template: metadata: labels: pod: django spec: restartPolicy: "Always" containers: - name: django image: alang/django ports: - containerPort: 8000 env: - name: POSTGRES_USER valueFrom: configMapKeyRef: name: postgresql-db-configmap key: pg-username - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: postgresql-db-secret key: pg-db-password - name: POSTGRES_HOST value: postgres-service - name: REDIS_HOST value: redis-service - name: GUNICORN_CMD_ARGS value: "--bind 0.0.0.0:8000" but i am facing issues with deployment , i think with gunicorn, getting this back: TypeError: the 'package' argument is required to perform a relative import for '.wsgi' Any way please to deploy it correctly? -
how to resolve uwsgi installation error on mac
i have the stack trace when i try to pip install uwsgi and i think its related to the mac os or my m1 chip > Collecting uWSGI Using cached uwsgi-2.0.20.tar.gz (804 kB) Building wheels for collected packages: uWSGI Building wheel for uWSGI (setup.py) ... error ERROR: Command errored out with exit status 1: command: /Users/eliorcohen/placer-django-server/env556/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/fv/r82y8wns2rsgbxjl0k12zxvc0000gn/T/pip-install-UZMqSB/uwsgi/setup.py'"'"'; __file__='"'"'/private/var/folders/fv/r82y8wns2rsgbxjl0k12zxvc0000gn/T/pip-install-UZMqSB/uwsgi/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/fv/r82y8wns2rsgbxjl0k12zxvc0000gn/T/pip-wheel-iPa0EY cwd: /private/var/folders/fv/r82y8wns2rsgbxjl0k12zxvc0000gn/T/pip-install-UZMqSB/uwsgi/ Complete output (154 lines): /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'descriptions' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build/lib copying uwsgidecorators.py -> build/lib installing to build/bdist.macosx-12.0-x86_64/wheel running install using profile: buildconf/default.ini detected include path: ['/Library/Developer/CommandLineTools/usr/lib/clang/13.0.0/include', '/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include', '/Library/Developer/CommandLineTools/usr/include', '/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks'] Patching "bin_name" to properly install_scripts dir detected CPU cores: 10 configured CFLAGS: -O2 -I. -Wall -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -fno-strict-aliasing -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -DUWSGI_HAS_IFADDRS -DUWSGI_ZLIB -mmacosx-version-min=10.5 -DUWSGI_LOCK_USE_OSX_SPINLOCK -DUWSGI_EVENT_USE_KQUEUE -DUWSGI_EVENT_TIMER_USE_KQUEUE -DUWSGI_EVENT_FILEMONITOR_USE_KQUEUE -DUWSGI_UUID -DUWSGI_VERSION="\"2.0.20\"" -DUWSGI_VERSION_BASE="2" -DUWSGI_VERSION_MAJOR="0" -DUWSGI_VERSION_MINOR="20" -DUWSGI_VERSION_REVISION="0" -DUWSGI_VERSION_CUSTOM="\"\"" -DUWSGI_YAML -DUWSGI_XML -DUWSGI_XML_EXPAT -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 0][clang] core/utils.o [thread 2][clang] core/protocol.o [thread 1][clang] core/socket.o [thread 4][clang] core/logging.o [thread 7][clang] core/master.o [thread 6][clang] core/master_utils.o [thread 8][clang] core/emperor.o [thread 5][clang] core/notify.o [thread 3][clang] core/mule.o [thread 9][clang] core/subscription.o [thread 0][clang] core/stats.o [thread 2][clang] core/sendfile.o [thread … -
how fix cycle in django?
I have problem with cycle in djano(Maybe I dont understand this).I have cycle in template and it must to output value from database,but Idk how I can create cycle,which may output value from (id = 1),because this cycle output value (id = 0) again and again. vds.html {% for item in allobjects %} <div class="container-fluid"> <div class="body2"> <li class="title">{{item.title}}</li> <li class="listram">{{item.ram}}<small>ГБ(озу)</small></li> <img class="ram2"width="51px" height="49px" src="/static/main/images/ram.png" ></img> <li class="cpu">{{item.cpu}} vCore</li> <img class="cpu1"width="51px" height="50px" src="/static/main/images/cpu.png" ></img> <li class="hdd">{{item.hdd}}<small> ГБ(ssd)</small></li> <img class="hdd1"width="51px" height="50px" src="/static/main/images/hdd.png" ></img> <li class="os">Установка любой ос</li> <img class="os1 " width="47px" height="49px"src="/static/main/images/os.png"/> <li class="os">Виртуализация KVM</li> <img class="os1 " width="47px" height="49px"src="/static/main/images/vds.png"/> <form action="https://billing.king-host.ru"> <button type="submit" name="buy">Купить</button> </form> <li class= "prise">{{item.name}}₽/месяц</li> </div> </div> <div class="container-fluid"> <div class="body3"> <li class="title">{{item.title}}</li> <li class="listram"><small>ГБ(озу)</small></li> <img class="ram2"width="51px" height="49px" src="/static/main/images/ram.png" ></img> <li class="cpu">2 vCore</li> <img class="cpu1"width="51px" height="50px" src="/static/main/images/cpu.png" ></img> <li class="hdd">40<small> ГБ(ssd)</small></li> <img class="hdd1"width="51px" height="50px" src="/static/main/images/hdd.png" ></img> <li class="os">Установка любой ос</li> <img class="os1 " width="47px" height="49px"src="/static/main/images/os.png"/> <li class="os">Виртуализация KVM</li> <img class="os1 " width="47px" height="49px"src="/static/main/images/vds.png"/> <form action="https://billing.king-host.ru"> <button type="submit" name="buy">Купить</button> </form> <li class= "prise">600 ₽/месяц</li> </div> </div> {% endfor %} models.py class VDSTARIFS( models.Model): id = models.CharField(max_length=40, primary_key= True,serialize=True) name = models.CharField(max_length=20, verbose_name = 'Цены') choosen = models.CharField(max_length= 20, choices = CHOOSE, verbose_name = 'Тариф', help_text='Выбор тарифного плана.') title … -
Field 'id' expected a number but got <User: ben>
I created a population script for a django website however, after running the script and making migrations, I logged in to the django admin page for my site to access the objects created using the script and could not do it for my Business model. It works fine for my other models. I get this error when I try to access the registered Businesses in my database from the Django admin page. It does not seem to trace back to any of my code but rather to a template in the admin folder of my python environment. Here's the error message: error message Here are my models: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to="profile_images", blank=True, default="profile_images/default.png") description = models.TextField(max_length=1024, default="") # boolean flag for identifying business owners is_business_owner = models.BooleanField(default=False) def __str__(self): return self.user.username class Business(models.Model): owner_fk = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=128) address = models.CharField(max_length=128) img = models.ImageField(upload_to="business_images", blank=True) slug = models.SlugField(unique=True) class Meta: verbose_name_plural = 'Businesses' def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Business, self).save(*args, **kwargs) def __str__(self): return f"{self.name} owned by {UserProfile.objects.get(pk=self.owner_fk).username}" Here is how I created the objects through the population script: def add_user(username, firstname, lastname, password, profile_pic, description, is_business_owner): new_user = User.objects.get_or_create(username=username, password=password, … -
Stuck deploying django to herkou posgress pip lock error
I am trying to deploy a Django app to herokou. I am getting a piplock that is out of date. -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in Pipfile.lock -----> Installing python-3.8.12 -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 -----> Installing dependencies with Pipenv 2020.11.15 Your Pipfile.lock (a6086c) is out of date. Expected: (6ce893). [DeployException]: File "/tmp/build_df99f796/.heroku/python/lib/python3.8/site-packages/pipenv/vendor/click/decorators.py", line 73, in new_func [DeployException]: return ctx.invoke(f, obj, *args, **kwargs) [DeployException]: File "/tmp/build_df99f796/.heroku/python/lib/python3.8/site-packages/pipenv/vendor/click/core.py", line 610, in invoke [DeployException]: return callback(*args, **kwargs) [DeployException]: File "/tmp/build_df99f796/.heroku/python/lib/python3.8/site-packages/pipenv/vendor/click/decorators.py", line 21, in new_func [DeployException]: return f(get_current_context(), *args, **kwargs) [DeployException]: File "/app/.heroku/python/lib/python3.8/site-packages/pipenv/cli/command.py", line 233, in install [DeployException]: retcode = do_install( [DeployException]: File "/app/.heroku/python/lib/python3.8/site-packages/pipenv/core.py", line 2052, in do_install [DeployException]: do_init( [DeployException]: File "/app/.heroku/python/lib/python3.8/site-packages/pipenv/core.py", line 1251, in do_init [DeployException]: raise exceptions.DeployException ERROR:: Aborting deploy ! Push rejected, failed to compile Python app. ! Push failed When I try and update the pip lock in the pipenv I am getting. pipenv lock Locking [dev-packages] dependencies… Locking [packages] dependencies… Building requirements... Resolving dependencies... ✘ Locking Failed! ERROR:pip.subprocessor:Command errored out with exit status 1: command: /Users/matthewsmith/.local/share/virtualenvs/devlog-XABMBIas/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/bq/46k05k255snbkf2x3fkzv0380000gn/T/pip-resolver-jdku7f8q/psycopg2/setup.py'"'"'; __file__='"'"'/private/var/folders/bq/46k05k255snbkf2x3fkzv0380000gn/T/pip-resolver-jdku7f8q/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' … -
sorting search result in django rest framework
I have written a search api for my website in django rest framework. when you search a name (e.g. "jumanji") there might be more than one result for the search for many reasons. what I want is for the result to be ordered by the "rating" field or "releaseDate" field of the Film model. here are my codes. # models.py class Film(models.Model): filmID = models.AutoField(primary_key=True) title = models.CharField(max_length=150) duration = models.PositiveIntegerField() typeOf = models.IntegerField(validators=[MaxValueValidator(3), MinValueValidator(1),]) rating = models.FloatField(default=0, validators=[MaxValueValidator(10), MinValueValidator(0),]) releaseDate = models.DateTimeField(null=True) # serializers.py class FilmSerializer(serializers.ModelSerializer): class Meta: model = Film fields = [ "filmID", "title", "price", "duration", "typeOf", "numberOfFilminoRatings", "filminoRating", "rating", "releaseDate", "detailsEn", "salePercentage", "saleExpiration", "posterURL", "posterDirectory", ] # views.py '''Override get_search_fields method of SearchFilter''' class DynamicSearch(filters.SearchFilter,): def get_search_fields(self,view, request): return request.GET.getlist('search_fields',[]) '''Override page_size_query_param attribute of PageNumberPagination''' class CustomizePagination(PageNumberPagination): page_size_query_param = 'limit' """Pagination Handler""" class PaginationHanlerMixin(object): @property def paginator(self): if not hasattr(self, '_paginator'): if self.pagination_class is None: self._paginator =None else : self._paginator = self.pagination_class() else : pass return self._paginator def paginate_queryset(self,queryset): if self.paginator is None: return None return self.paginator.paginate_queryset(queryset, self.request, view=self) def get_paginated_response(self,data): if self.paginator is None: raise "Paginator is None" return self.paginator.get_paginated_response(data) class SearchFilm(APIView,PaginationHanlerMixin): authentication_classes = () permission_classes = (AllowAny,) def __init__(self,): APIView.__init__(self) self.search_class=DynamicSearch self.pagination_class=CustomizePagination def filter_queryset(self,queryset): … -
How to reuse an existing python Enum in Django for chocies?
Django has its own Enumeration types like model.TextChoices. However, if you already use traditional python Enum objects in your codebase, it would be nice to reuse them for fields definition without redefining all the values. Is there an elegant straightforward way to do this without too much boilerplate? What I tried: building a models.TextChoices class from the Enum seems impossible without manually declaring the values building the choices parameter from the Enum instead of dealing with models.TextChoices but then things like obj.field == ENUM.XXX won't work because Enums don't do value comparisons like models.TextChoices does among other things. Any elegant way to do this? form enum import Enum class YEAR_IN_SCHOOL(Enum): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' GRADUATE = 'GR' class MyModel(models.Model): year_in_school = django_model_field_choices_using_enum(YEAR_IN_SCHOOL) So that: Comparaison with the ENUM works my_model.year_in_school == YEAR_IN_SCHOOL.FRESHMAN Saving using the Enum works my_model.year_in_school = YEAR_IN_SCHOOL.FRESHMAN my_model.save() -
I have changed library in django How do I upload it
I have created web app with django and I published it but when I developing the app, I changed django library but I can not import it or change it in amazon web services. I am new so what can I do? -
In django-forms, how can I make the values of 'name' column of foreign database visible in the selection choices
My Django site has a database model named Status with: class Status(models.Model): x = models.ForeignKey(Person, on_delete=models.SET_NULL, null = True) The Person database model referenced here contains attributes such as name, profile_pic etc. In forms.py, I have: class StatusForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StatusForm, self).__init__(*args, **kwargs) class Meta: model = Status fields = ['x'] Now, when running the site, I get: I want the name attribute of the Person to be shown in the choices instead of being shown Person object(1), Person object (2)..... How can I make that happen? -
APScheduler started twice on Django Heroku
I am using APScheduler (backgroundScheduler) to run a background job on Django deployed to Heroku. The job is supposed to run once every minute. I use a view endpoint to start the scheduler. /run is eventually called multiple times but should only start one scheduler. Locally, it works like a charm. However, when deployed to Heroku, calling /run multiple times will start another background scheduler. Interestingly, two schedulers are started, not more. I was thinking if this could be due to threading? Maybe /run is called on different threads. Any help is very much appreciated! views.py def run(request): if cgm_receiver.scheduler.running: logger.info('Background service was already running') else: logger.info('Background service was not running') logger.info("Starting background service") cgm_receiver.scheduler.add_job(cgm_receiver.timed_job, id='cgm_receiver', replace_existing=True, trigger='interval', minutes=1) cgm_receiver.scheduler.start() return render(request, "run.html") This is the output after calling /run first time at=info method=GET path="/run/" host=**** request_id=2bfe4eb3-47dc-41bc-afb9-2f1f20217d9f dyno=web.1 connect=0ms service=5327ms status=200 bytes=3330 protocol=https 2022-02-06 16:48:13,995 | INFO | cgm_importer.views : Background service was not running 2022-02-06 16:48:13,996 | INFO | cgm_importer.views : Starting background service 2022-02-06 16:48:14,001 | INFO | apscheduler.scheduler : Adding job tentatively -- it will be properly scheduled when the scheduler starts 2022-02-06 16:48:14,001 | INFO | apscheduler.scheduler : Added job "timed_job" to job store "default" 2022-02-06 … -
Can Python/Django function objects be executed with map function?
I have some Django model objects that are involved with a background celery task, at some point I have to run a check before creating new objects with these models. The check itself is tricky in that I have to run it multiple times within a single task invocation- my initial solution which I have to repeat multiple times so it includes the latest DB objects looks off so I came up with this instead: from itertools import chain foo = Foo.objects.get(pk=1) check = chain(foo.field.values_list, foo.attribute.values_list, foo.django.values_list) execute_check = map(lambda f: f('link', flat=True), check) print(list(execute_check)) # returns an empty list This solution didn't work out, it returned an empty list and I know for a fact it shouldn't be empty. In contrast with having to rewrite check multiple times so it includes the latest DB objects, I'd prefer writing it once and checking by execution if it matches my condition. Could you point me in the right direction? Thanks -
Can you combine Destroy with Create Django Rest Framework?
I've got a model for adding/subtracting points from an answer (answer and user is unique together meaning that only one person can upvote or downvote one answer), looks like this class Vote(models.Model): class AnswerScore(models.IntegerChoices): add = 1 subtract = -1 score = models.IntegerField(choices=AnswerScore.choices) answer = models.ForeignKey('Answer', on_delete=models.PROTECT) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) class Meta: unique_together = ('answer', 'user',) Here's my viewset and serializer for creating an Api Endpoint for that class VoteSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) answer = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Vote fields = '__all__' class VoteCreate(ParentKeyAPIView, generics.CreateAPIView): model = Vote parent_model_field = 'answer_id' serializer_class = VoteSerializer def perform_create_kwargs(self, **kwargs): return super().perform_create_kwargs(user=self.request.user, answer_id=self.kwargs['pk'], **kwargs) Now i also want to take into consideration the fact, that someone might click plus to an answer, but then decide to minus the answer. And i want create an endpoint to destroy that particular instance of Vote when that happens and then at the same time create a new one with the. opposite choice (add/subtract). Is there anyway to do that in Django Rest Framework? -
Dynamic 'Property' count on applicable foreign keys
I currently have the following three models in my app: Models.py class Guest(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100) class Event(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100) class Invite(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) event = models.ForeignKey(Event, on_delete=models.CASCADE) guest = models.ForeignKey(Guest, on_delete=models.CASCADE) On my index page for the Event model where I show a single event, I also show a list of all guests that could possibly be added to the event: guests = Guest.objects.filter(wedding = event.wedding).order_by("tag", "name") However, in the table, I would like to show next to each guest how many invites for this specific event they have been given. While I could do a property on the guest, its possible that multiple guests could be invited to multiple events. In an ideal world, I would define a property that accepts the event as a parameter so I could do something like this in the template: {% for guest in guests %} {{ guest.name }} ( {{ guest.total_invites(event.id) }} {% endfor %} -
How to use session timeout in django rest view?
I am implementing a view for a game using Django REST's APIView. I am very new to Django and have never done this before so I'm not sure how to implement this. The main idea is that a game only lasts 5 minutes. I am sending a resource to the user and creating a session object. This view. should be unavailable after 5 minutes. Is there such a thing as a view timeout? Will the session timeout then work for the post request as well or do I need to implement it there as well? This is my view: The out commented code at the end is what I was thinking of doing. Can I even do it in the view directly? How else can I do this and test it? views.py class GameView(APIView): """ API View that retrieves the game, retrieves an game round as well as a random resource per round allows users to post tags that are verified and saved accordingly to either the Tag or Tagging table """ def get(self, request, *args, **kwargs): current_score = 0 if not isinstance(request.user, CustomUser): current_user_id = 1 else: current_user_id = request.user.pk random_resource = Resource.objects.all().order_by('?').first() resource_serializer = ResourceSerializer(random_resource) gameround = Gameround.objects.create(user_id=current_user_id, … -
ValueError: Cannot assign "": "Message.name" must be a "CustomUser" instance
I am building a live chat for my website and encountered this error message while trying to save messages to database. I used this tutorial to create the live chat and am now trying to implement it to my site. The difference is that I do not need different rooms and I want only authorized users to access the chat. The problem comes because I use foreign key on my Messages model to create a link with CustomUser model. I am using channels. template where the data comes from: const chatSocket = new WebSocket( 'ws://' + window.location.host ) chatSocket.onmessage = function(e) { console.log(e); const data = JSON.parse(e.data) if(data.message) { document.querySelector('#chat-messages').innerHTML += ('<b>' + data.username + ': </b>' + data.message + '<br>') } else { alert('Empty!') } } chatSocket.onclose = function(e) { console.log('The socket closed unexpectedly'); } document.querySelector('#chat-message-submit').onclick = function(e) { const messageInputDom = document.querySelector('#chat-message-input') const message = messageInputDom.value chatSocket.send(JSON.stringify({ 'message': message, 'name': {{request.user}}, })) messageInputDom.value = '' } code used for saving into database in consumers.py def save_message(self, name, message): Message.objects.create(name=name, content=message) models.py from django.db import models from django.contrib.auth.models import AbstractUser from .managers import CustomUserManager # Create your models here. class CustomUser(AbstractUser): username = models.CharField(max_length=32, blank=True, null=True) name = models.CharField(max_length=200, … -
Upload in Django
I was trying to understand how to upload files using Django, so I used the example (latest version, upload is working): https://github.com/axelpale/minimal-django-file-upload-example I have a few Questions now: How do I set a max file size? (I have checked the documentation of Django, but I don't get it) Is there a way for me to read the file before the user uploads it? (i.e a program that checks certain things and if they are ok, it can be uploaded) -
Django: Access related object attributes from a form field in a template?
I'm building a page that allows users to edit Task and related Activity records (one task can have many activities), all on the same page. Here are extracts from my code... models.py from django.contrib.auth.models import User class Task(models.Model): category = models.CharField(max_length=300) description = models.CharField(max_length=300) class Activity(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) title = models.CharField(max_length=150) notes = models.TextField(blank=True) owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) The activity "owner" is linked to a User from the Django standard user model. views.py def manage_task(request, pk): task = Task.objects.get(pk = pk) TaskInlineFormSet = inlineformset_factory(Task, Activity, form = ActivityForm) if request.method == "POST": form = TaskForm(request.POST, instance = task) formset = TaskInlineFormSet(request.POST, instance = task) if form.has_changed() and form.is_valid(): form.save() if formset.has_changed() and formset.is_valid(): formset.save() return redirect('manage_task',pk=task.id) else: form = TaskForm(instance = task) formset = TaskInlineFormSet(instance = task) context = {'task': task, 'task_form': form, 'formset': formset} return render(request, 'tasks/manage_task.html', context) And manage_task.html excerpt: <h2>{{ task.category }}</h2> <form method="post"> {% csrf_token %} {{ task_form.description }} {% for form in formset %} {{ form.id }} {{ form.title }}</br> {{ form.notes }}</br> {% if user.id == form.owner.value %} You own this Activity!</br> {% else %} {{ form.owner.first_name }} owns this Activity</br> {% endif %} {% endfor %} <input class="save" type="submit" … -
Django - quiz app - issue with views and redirecting i guess
I'm trying to make an app by using django which allow me to study. for now I have already done it models.py from django.db import models from django.contrib.auth.models import User class Question(models.Model): question_text = models.CharField(max_length=200, null=True) answer_text = models.CharField(max_length=200, null=True) date_posted = models.DateTimeField(auto_now_add = True) def __str__(self): return self.question_text class Test(models.Model): name = models.CharField(max_length=200) questions = models.ManyToManyField(Question) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True) date_posted = models.DateTimeField(auto_now_add = True) urls.py urlpatterns = [ path('', views.home, name='home'), path('test/<str:pk>/', views.test), ] urls.py urlpatterns = [ path('', include('exam.urls')), path('admin/', admin.site.urls), ] views.py def test(request, pk): print("Am I getting here?") test = Test.objects.get(id=pk) questions = test.questions.all() form = Answer() context = {'questions':questions, 'form':form} if request.method == 'POST': instance = Question.objects.get(id=pk) form = Answer(request.POST, instance=instance) if form.is_valid(): print("form is valid") if request.POST.get("answer").strip() == instance.answer_text: return HttpResponse('<h1>aaa</h1>') print("answer is correct") # used strip() to remove whitespace before and after the text. return redirect('home') return render(request, 'exam/test.html', context) forms.py from django import forms from django.forms import ModelForm from exam.models import Question class Answer(ModelForm): class Meta: model = Question fields = ['answer_text'] answer = forms.CharField(label='Your answer', max_length=100) html {% for question in questions %} <div class="question-container"> <p>{{question.question_text}}</p> <form method="POST"> <td>{{ form.answer }}</td> {% csrf_token %} <input type="hidden" name="question_id" … -
Get dict's value by key name in Django Tempaltes
in my view.py I have a function with field: context ={'user':user, 'user_gpds':user_gpds, 'team':team, 'team_gpds':team_gpds} which I return: return render(request, 'app/team_gpd_page/team_gpds.html', context) in my templates I have next code: {% for gpd in {{context|key:team_gpds}} %} <tr> <td><a class="nav-link" href="/gpd/{{gpd.employee.end_user_id}}">GPD</a></td> <td>{{gpd.employee}}</td> <td>{{gpd.gpd_year}}</td> <td>{{gpd.gpd_start}}</td> <td>{{gpd.gpd_end}}</td> <td>{{gpd.gpd_status}}</td> </tr> {% endfor %} But in result I have had an empty fields. I am also trying context.team_gpds and context.get('team_gpds'). What I am doing wrong? -
DjangoRestFramework: Nested relationships usage
For my current project I'm using Django and Django Rest Framework. I'm using Nested Relationships for all my views to get strictly what is needed to be displayed in them. However I'm starting to wonder if it is a good practice or not. Let's say I have a kanban view for a project application: I'd have a project With columns in it (stages) With tickets (tasks) in stages. This would lead to a 3 layer serialization (project with its stages with their tasks). I have the following questions : While it does work perfectly for a few tasks, how will it scale for a project with 10.000 and even more tasks ? Since it would load let's say : 1 project, 5 stages, 10K+ tasks ? Is a pagination possible with such nested relations ? If using such nested relations is not the good way. When is it okay to use them ? If using such nested relations is not the good way for a kanban view, how should I do it ? Should I query (from the frontend) first the project with stage_ids, then query those stages 1 by 1 with each their task_ids, and then reconstruct the whole … -
getting a django textfeild to run as code
I'm trying to get a project going and I'm using Django to do it. I have as one of my attributes in models start_lines = models.TextField(blank=True, null=True). These lines are to get code started with the exec() function. As one of them, I have from .code.Lot_sizing_codes import lot_size ls = lot_size(K, h, r, True) output, extra_output = (ls.{str(Functions.objects.get(id=request.POST["function_to_call"]))}({request.POST["inputExtras"]})) I have to run this through function to render what i want: def showProgramX(request, pk): program = Program.objects.get(id=pk) form = ProgramInputForm() keys = "" vars = [] for var in program.inputvariables.split(","): var_name, var_type = var.split("=") keys += f""" <tr> <th><label for="{var_name}">{var_name}:</label></th> <td><input type="text" name="{var_name}" maxlength="1000" class="input" id="id_inputvariables"></td> </tr>""" vars.append(var_name) content = {"program": program, "form": form, "keys": keys} if request.method == "POST": form1 = ProgramInputForm(request.POST) import json req = request.POST for var in vars: line = f"""{var} = {req[f'{var}']}""" exec(line, globals()) exec(program.start_lines, globals()) content["output"] = output content["extra_output"] = extra_output content['form'] = form1 return render(request, "programs/program.html", content) the output if i print program.start_lines should be in this case {str(Functions.objects.get(id=request.POST["function_to_call"]))} = all and {request.POST["inputExtras"]} is nothing/empty from .code.Lot_sizing_codes import lot_size ls = lot_size(K, h, r, True) output, extra_output = (ls.all()) where as I actually get from .code.Lot_sizing_codes import lot_size ls = lot_size(K, h, r, True) …