Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to include html template into another html with javascript
I have an html page called main.html that is extended with base.html. I like to find a solution how can I include another html template (individual_sum.html) into it with the javascript too. individual_sum.html has lots of javascript codes in the file. I don't use external javascript file because I don't know how if there any way to use Django Template Language in js. I have queries in my view that pushes data dynamically so I need DTL. I included the individual_sum.html into the main.html and the content appears but charts and other javascript stuff are blank. main.html {% extends 'stressz/base.html' %} {% block body%} content of main.html {% include 'stressz/individual_sum.html' %} {% endblock %} Is there any solution to have fully (with javascript) working individual_sum.html in main.html? Or can I use external javascript file that has Django's for and if/elif statements working in it? My aim is to have smaller separated files and not one giant. -
What is the use of "created" attribute of django post_save() signal?
Is there any use of created attribute in django's post_save() signal as it is always returning true. The post_save() will be called only when an object has been created, so what's the need for verifying it with created attribute? -
ModuleNotFoundError: No module named 'models' and TypeError: argument of type 'PosixPath' is not iterable
I tried the previous fixes in other tutorials but they didn't work. Here's what I have: ... from models import Tutorial #crashes from backend.restApis.tutorials.serializers import TutorialSerializer @api_view(['GET', 'POST', 'DELETE']) def tutorial_list(request): # GET list of tutorials, POST a new tutorial, DELETE all tutorials if request.method == 'GET': tutorials = Tutorial.objects.all() title = request.GET.get('title', None) if title is not None: tutorials = tutorials.filter(title__icontains=title) tutorials_serializer = TutorialSerializer(tutorials, many=True) return JsonResponse(tutorials_serializer.data, safe=False) ... I have tried renaming the reference but it doesn't work, here's the file structure Project File Structure I am new to django and appreciate any help ! -
Django. Admin. Upload image from database
How can I select images for ImageField in admin from those already loaded earlier in the database? -
Test Django ImageField with Pytest
I am trying to write a test for the following model class Person(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to='images') The fixture for it is as below: @pytest.fixture def generate_img(): root = join(dirname(__file__), 'imgs') return [join(root, "test_image.png")] @pytest.fixture def person_single(generate_img): return {'name':'test name', 'image': open(generate_img[0], 'rb')} How do I test the image upload correctly? -
Getting error ModuleNotFoundError: No module named 'rest_framework_sso'
I am following https://pypi.org/project/djangorestframework-sso/ tutorial for sso authentication in django, In first step they added 'rest_framework_sso' in INSTALLED_APPSin settings.py without installing any such liberary. When I tried to do the same I got: ModuleNotFoundError: No module named 'rest_framework_sso' Then I tried pip/pip3 install 'rest_framework_sso' but I got: ERROR: Could not find a version that satisfies the requirement rest_framework_sso (from versions: none) ERROR: No matching distribution found for rest_framework_sso Then I installed django rest framework but it is stil not working. I want to know why is it not working and how can I solve this, I didn't found anything that can help me related to this. -
Exception with django-awesome-avatar, ModuleNotFound
I am trying to install and use awesome avatar for my user from awesome_avatar.fields import AvatarField class MyUser(models.Model): image = AvatarField(upload_to='users/%Y/%m/%d/', width=100, height=100) but when i trying to start my project i had an problem with module name "StringIo" from StringIO import StringIO ModuleNotFoundError: No module named 'StringIO' I tried to install it but it has not a proper version of it Here full text of error Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\awesome_avatar\fields.py", line 8, in <module> from cStringIO import StringIO ModuleNotFoundError: No module named 'cStringIO' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen … -
Django issue with post_delete signal when deleting a object having child objects of the same model
When the post_delete signal is used to send a notification alert to user about comment deletion the following error occurs only when there is replies associated with it. If the comment has no replies it works fine. Comment models.py partial code user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, default=None) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) content = models.TextField() So, the comment without a parent is main comment and with a parent is reply. signals.py partial code def CommentDelete_handler(sender, instance, **kwargs): print(instance) post_delete.connect(CommentDelete_handler, sender=Comment) Here just accessing the instance will generate an error Comment matching query does not exist. I am not clear with the working mechanism inside this process, and why it works with a single comment but when it has replies inside it generates errors. Note: I fixed this case using the pre_delete signal instead of the post one which works fine in both cases. If anyone suggests the working mechanism and why post_signal fails on this or is there any update I can do to make it work in post_signal. Thank you for the support. -
How do I solve a Django NoReverseMatch Error?
When I visit basic_list, I get the error "Reverse for 'manage_account' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['manage_account/(?P[0-9]+)/$']" but all the other links are working. models.py from django.db import models class Wine(models.Model): name = models.CharField(max_length=300) year = models.IntegerField() objects = models.Manager() def __str__(self): return str(self.pk) + ": " + self.name class Account(models.Model): username = models.CharField(max_length=20) password = models.CharField(max_length=20) objects = models.Manager() def __str__(self): return str(self.pk) + ": " + self.username urls.py from django.urls import path from . import views urlpatterns = [ path('login', views.view_login, name='view_login'), path('basic_list', views.view_basic_list, name='view_basic_list'), path('manage_account/<int:pk>/', views.manage_account, name='manage_account'), ] views.py from django.shortcuts import render, redirect, get_object_or_404 from .models import * from django.core.exceptions import ObjectDoesNotExist def view_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') account = Account.objects.get(username=username) if password == account.password: return redirect('view_basic_list') else: return render(request, 'myapp/login.html', {'warning': "Invalid login"}) else: return render(request, 'myapp/login.html') def view_basic_list(request): wine_objects = Wine.objects.all() return render(request, 'myapp/basic_list.html', {'Wines':wine_objects}) def manage_account(request, pk): a = get_object_or_404(Account, pk=pk) return render(request, 'myapp/manage_account.html', {'a': a}) basic_list.html {% extends 'myapp/base.html' %} {% load static %} {% block content %} <div class="container"> <div class="row"> <div class="col-12"> <table class="table table-striped"> <thead> <th scope="col"> Name </th> <th scope="col"> Year </th> </thead> <tbody> {% for d … -
Is there any way to set all methods in a class as being in an atomic transaction in Django?
While using the custom action method of ViewSet in Django, I separated some business logics into another class, of which name is BusinessService. The BusinessService class can be used from many other methods, and after some analysis, I found all methods (more than 5) in the class should be in an atomic transaction. So the easiest but repetitive way might be adding @transaction.atomic decorator above the name of the methods, but as a way to follow the DRY principle, I was struggling to remove the redundant repetitions, but couldn't make it in a simple way. Is there any to make a whole class in an atomic transaction? Till now, I tried attaching @transaction.atomic above the name of a class, but, of course, had no success, so I analyzed the decorator, and found out the Atomic class which uses __enter__ and __exit__ for transaction management, which requires with or additional something. -
Whats the most efficient way to get all related models in a tree-like structure in django?
I have this model structure: models.py class Region(models.Model): code = models.CharField(max_length=10, unique=True, verbose_name=_('code')) name = models.CharField(max_length=255, verbose_name=_('name')) class Province(models.Model): code = models.CharField(max_length=10, unique=True, verbose_name=_('Code')) name = models.CharField(max_length=255, verbose_name=_('Name')) parent_region = models.ForeignKey('Region', on_delete=models.CASCADE, related_name='province', verbose_name=_('Regione')) class City(models.Model): code = models.CharField(max_length=10, unique=True, verbose_name=_('Code')) name = models.CharField(max_length=255, verbose_name=_('Name')) parent_province = models.ForeignKey('Province', on_delete=models.CASCADE, related_name='city', verbose_name=_('Region')) class CustomArea(models.Model): cities = models.ManyToManyField("City", verbose_name=_("Cities"), blank=True, related_name="in_area") provinces = models.ManyToManyField("Province", verbose_name=_("Provinces"), blank=True, related_name="in_area") regions = models.ManyToManyField("Region", verbose_name=_("Regions"), blank=True, related_name="in_area") I want to write a method for CustomArea model that returns a queryset with all the single City element in it. this is what I came up with: def list_cities(self): pks_provinces= self.provinces.all().values_list('id', flat=True) pks_regions= self.regions.all().values_list('id', flat=True) comuni = City.objects.filter(provincia__pk__in=pks_provinces).values_list('id', flat=True) | City.objects.filter(provincia__regione__pk__in=pks_regions).values_list('id', flat=True) | self.cities.all().values_list('id', flat=True) return comuni.distinct() Is this efficent enough? How can I improve this query to have all the single City element? -
Use template tags within a TextField
How to load a template tag within object that is retrieved from the models. email = models.TextField() Saved to model: this is a texts with a {{ test }} In my view i return: test = 'test' email_db = someclass.objects.get(pk=1) email_text = email_db.email return render(request, 'somepage.html', {'test':test, 'email_text':email_text}) somepage.html: {{ email_text }} outcome: this is a texts with a {{ test }} Is there a quick solution herefore ? thnx! -
TemplateSyntaxError at /AR Could not parse the remainder: '="AR"' from '="AR"'
I am trying to check if the language is == to AR to get a specific value from db and this is what I get: Internal Server Error: /AR Traceback (most recent call last): File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/smartif.py", line 175, in translate_token op = OPERATORS[token] KeyError: '="AR"' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/miryamelliye/development/spa/spa/frontend/views.py", line 10, in home return render(request, 'frontend/home.html', context) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/loader.py", line 15, in get_template return engine.get_template(template_name) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/backends/django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/loaders/base.py", line 30, in get_template contents, origin, origin.template_name, self.engine, File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/base.py", line 155, in init self.nodelist = self.compile_nodelist() File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/base.py", line 193, in compile_nodelist return parser.parse() File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/base.py", line 478, in parse raise self.error(token, e) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/base.py", line 476, in parse compiled_result = compile_func(self, token) File "/Users/miryamelliye/Library/Python/3.7/lib/python/site-packages/django/template/defaulttags.py", line 964, in do_if … -
Django - How can I remove an html attribute from a Django widget?
I'm styling a search page in a Django project. I want to remove a single boolean attribute from the <select> tag generated by a ManyToManyField. The widget generated by Django looks like this: and I want it to look like this: I can get that result by inspecting the element in Firefox and simply changing <select id="id_regions" name="regions" multiple=""> to <select id="id_regions" name="regions"> Normally if you want a standard dropdown in Django, you would use a CharField in your model and set the choices to a list of tuples. We already do that in another place. However this is for work, and I don't want to change the relations in the database just for the sake of pretty frontend. This is the form in question: class ProviderFilter(django_filters.FilterSet): text = CharFilter(field_name="name", lookup_expr='icontains') class Meta: model = Provider fields = [ "regions", "themes", "sexes" ] The ManyToManyField called "regions", which I want to change the appearance of, comes from the model Provider and looks like this: class Provider(BaseModel): # Many fields omitted for brevity regions = models.ManyToManyField(Region, blank=True) and uses this class: class Region(BaseModel): name = models.CharField(max_length=255, unique=True) def __str__(self): return self.name Not sure if it's necessary, but here is a part … -
got an unexpected keyword argument 'update_fields', User needs to have a value for field "id" before this many-to-many relationship can be used
My models.py: class Source(models.Model): title = models.CharField(max_length=300) users = models.ManyToManyField(User, blank=True) def __str__(self): return self.title class Headline(models.Model): title = models.CharField(max_length=300) slug = models.SlugField(max_length=200, unique=True) content = models.TextField(default="") created_date = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, related_name='like', blank=True) dislikes = models.ManyToManyField(User, related_name='dislike', blank=True) lols = models.ManyToManyField(User, related_name='lol', blank=True) saves = models.ManyToManyField(User, related_name='save', blank=True) bearishes = models.ManyToManyField(User, related_name='bearish', blank=True) importants = models.ManyToManyField(User, related_name='important', blank=True) toxics = models.ManyToManyField(User, related_name='toxic', blank=True) source = models.ForeignKey(Source, on_delete=models.CASCADE) def __str__(self): return self.title class Comment(models.Model): author = models.ForeignKey(User, related_name='author', on_delete=models.CASCADE, blank=True, null=True) comment = models.TextField() newspost = models.ForeignKey(Headline, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return f"{self.author}" When I add a few ManyToMany field related to User model, it causes error when login/register/etc. These errors: File "/Users/mahdi/PycharmProjects/Project/venv/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1584, in _changeform_view self.save_model(request, new_object, form, not add) File "/Users/mahdi/PycharmProjects/Project/venv/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1097, in save_model obj.save() File "/Users/mahdi/PycharmProjects/Project/venv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 536, in get return self.related_manager_cls(instance) File "/Users/mahdi/PycharmProjects/Project/venv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 853, in init (instance, self.pk_field_names[self.source_field_name])) ValueError: "<User: test>" needs to have a value for field "id" before this many-to-many relationship can be used. What's wrong? -
installing gdk-pixbuf on Elastic Beanstalk v2
I am trying to get Django-Weasyprint working correctly on an AWS Linux2 Elastic Beanstalk instance. I have come across [this question][1] and when I add the code to .platform/hooks/predeploy the images all work but the href links stop working. I have, therefore, tried to upgrade the packages within the script and my script now looks like: #!/usr/bin/env bash yum install -y libxml2-devel libxslt-devel python-devel redhat-rpm-config libffi-devel cairo pango export PKG_CONFIG_PATH=/usr/lib64/pkgconfig:/usr/lib/pkgconfig export PATH=/usr/bin:$PATH export LDFLAGS=-L/usr/lib64:/usr/lib export LD_LIBRARY_PATH=/usr/lib64:/usr/lib export CPPFLAGS=-I/usr/include sudo yum-config-manager --enable epel sudo yum update -y sudo yum install -y gcc gcc-c++ glib2-devel.x86_64 libxml2-devel.x86_64 libpng-devel.x86_64 \ libjpeg-turbo-devel.x86_64 gobject-introspection.x86_64 gobject-introspection-devel.x86_64 wget http://ftp.gnome.org/pub/GNOME/sources/libcroco/0.6/libcroco-0.6.13.tar.xz tar xvfJ libcroco-0.6.13.tar.xz cd libcroco-0.6.13 ./configure --prefix=/usr make sudo make install cd .. wget http://ftp.gnome.org/pub/GNOME/sources/gdk-pixbuf/2.42/gdk-pixbuf-2.42.6.tar.xz tar xvfJ gdk-pixbuf-2.42.6.tar.xz cd gdk-pixbuf-2.42.6 ./configure --prefix=/usr --without-libtiff make sudo make install cd .. sudo yum install -y pixman-devel.x86_64 harfbuzz-devel.x86_64 freetype-devel.x86_64 wget http://www.freedesktop.org/software/fontconfig/release/fontconfig-2.13.93.tar.gz tar xvf fontconfig-2.13.93.tar.gz cd fontconfig-2.13.93 ./configure --prefix=/usr --enable-libxml2 make sudo make install cd .. wget http://cairographics.org/releases/cairo-1.16.0.tar.xz tar xvfJ cairo-1.16.0.tar.xz cd cairo-1.16.0 ./configure --prefix=/usr make sudo make install cd .. wget http://ftp.gnome.org/pub/GNOME/sources/pango/1.48/pango-1.48.4.tar.xz tar xvfJ pango-1.48.4.tar.xz cd pango-1.48.4 ./configure --prefix=/usr make sudo make install cd .. wget http://ftp.gnome.org/pub/GNOME/sources/librsvg/2.50/librsvg-2.50.5.tar.xz tar xvfJ librsvg-2.50.5.tar.xz cd librsvg-2.50.5 ./configure --prefix=/usr make sudo make install cd .. sudo ldconfig … -
Wagtail / Using ListBlock without some atributes in mixin
My mixin class: class FeatureList(blocks.StructBlock): title = blocks.TextBlock(default=None, blank=True, null=True) description = blocks.ListBlock(blocks.TextBlock(default=None, blank=True, null=True)) button_label = blocks.TextBlock(required=False, default=None, blank=True, null=True) button_url = blocks.URLBlock(required=False) and my models class ThreeListsBlock(DefaultFields, ThemeChooser, blocks.StructBlock): class Meta: icon = 'grip' tiles = blocks.ListBlock(FeatureList(), required=True) How can i use in ThreeListsBlock attributes from FeatureList() without button_url and button_label? I dont want creating copy FeatureList mixin. I want see in ThreeListsBlock only title and description. Thanks -
django rest framework serializer saving field value as empty strings, but no errors
django rest framework serializer saving field value as empty strings, but no errors views.py from django.shortcuts import render from rest_framework import viewsets from rest_framework.authentication import TokenAuthentication from .models import MyTodo from .serializers import MyTodoSerializer class MyTodoView(viewsets.ModelViewSet): queryset = MyTodo.objects.all() serializer_class = MyTodoSerializer and my model is models.py from django.db import models # Create your models here. class MyTodo(models.Model): # Autoincrement id id = models.AutoField(primary_key=True) title = models.CharField(max_length=200, blank=True, default='') description = models.CharField(max_length=20, blank=True, default='') created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title and my serializer is serializers.py from rest_framework import serializers from mytodo.models import MyTodo class MyTodoSerializer( serializers.ModelSerializer ): title = serializers.CharField(max_length=200, default='') description = serializers.CharField(max_length=200, default='') created_on = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S", required=False) def create(self, validated_data): return MyTodo.objects.create(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.description = validated_data.get('description', instance.description) instance.created_on = validated_data.get('created_on', instance.created_on ) instance.save() return instance class Meta: model = MyTodo fields = [ 'id','url','title','description', 'created_on' ] Looks pretty simple, straight forward but by CURL calls are saving empty fields, but Browsable API View is working very fine. Please tell me what am I doing wrong. Here is what I am trying to do Curl Client #!/bin/bash b64credential=$(echo 'admin:admin' | base64) access_token=$(curl -d "username=admin&password=admin" -X POST 'http://localhost:8000/api/token/' \ -H 'Accept:application/json' \ … -
Can i customise my crispy form in template?
I need to add after every label tag which will be button to enable input, so can i somehow do that in template? so can i turn this <form method="POST" action="/guide_register/" class="guide_register col-md-4"> {% csrf_token %} {%crispy form%} </form> into something like this <form action="/profile/" method="POST"> {% csrf_token %} {% for field in form %} <div class="form-row"> {{field.label_tag}} <i class="fas fa-pen"></i> {{field}} </div> {% endfor %} <br> <div class="form-row"> <input type="submit" value="Підтвердити" class="btn btn-primary"> <input type="reset" class=" btn btn-secondary" value="Відмінити"> </div> </form> but with crispy -
How to create database Structure Like Amazon Prime / Netflix / Hotstart in Django (ORM)
I want to create model with this fields -Basic Data to store -- Image Banner / Video Banner -- Title -- Description -- Directors -- Starring -- Genres -- Subtitles -- Year -- Length -- Audio languages -- Video Link -- Episode 2 or Movie Part 2 Avaiable -Buttons -- Add Watchlist Button -- Download Button -- Play Button / Continue Watching (if Applicable) -- Share Buttons -- Feedback - Lower Content Tab -- Episodes (If Applicable) -- Related - Details -- Producers -- Studio Need a poster for every show or movies and a thumbnail for every video (if episode applicable) *If Episode 2 or Movie's part two available they should be linked. Easy Upgradable / Manageable Ideas -
saving model to database throw ValueError in django
I have two model employee and department. Employee has one to one connection with department like class Employee(models.Model): department = models.ForeignKey(to=Department, on_delete=models.CASCADE) but when I try to create object from rest request, it throws ValueError: Cannot assign "{'id': 1, 'name': 'wrewrwerwe'}": "Employee.department" must be a "Department" instance. -
ORM django , filtre by object.proprety
Im trying to get result from this view Here is the models -
Waiting list in Django
I am making a model for a training that has the fields below: class Training(models.Model): class Meta: verbose_name = _("Training") registered = models.ManyToManyField(User, blank=True, null=True) waiting_list = models.ManyToManyField(User, blank=True, null=True) max_registered = models.models.PositiveSmallIntegerField() date = models.DateField(auto_now_add=False, auto_now=False) starting_time = models.TimeField(auto_now_add=False, auto_now=False) finishing_time = models.TimeField(auto_now_add=False, auto_now=False) My problem is to implement functionality for max registered participants to a training. When registered.count() == max_registered it should put users on the "waiting_list" instead of "registered". Any suggestions on how I should implement this? Is this something done in backend or frontend? Thanks in advance -
Show string if value is None in template
If a value is None I would like to show a - rather than rendering None in the table. However I get the following error: Could not parse the remainder: ' or '-'' from 'employee.full_name or '-'' I'd like to avoid doing a ton of if else statements if possible. Here's my code: {% for employee in employees %} <tr> <td>{{employee.full_name or '-'}}</td> <td>{{employee.position or '-'}}}</td> <td>{{employee.dob or '-'}}}</td> <td>{{employee.phone or '-'}}}</td> <td>{{employee.email or '-'}}}</td> <td>{{employee.address or '-'}}}</td> <td>{{employee.joined or '-'}}}</td> </tr> {% endfor %} The following Python code works as expected: dog = None print(dog or '-') -
How to pass JSON data through the Django backend to frontend view using Angular
I need a solution for this logic read the JSON files through Django backend, pass the data to the AngularJS frontend and populate the charts using the Google Charts library in the User Interface. Below is the structure of the barChart.json payload. { "chart_type": "bar", "x_data": ["primary School","None", "Phd","High School","Master"], "x_data": [29.817000007,41.25000,48.00000,187.00000,134.000000], "x_name": "education_level", "y_name": "city_development_index", "title": "city_develpoment_index group by education_level" }