Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Group permissions per vendor or company
I am using a custom User model. I would like to enforce permissions based on vendor and group. A vendor can create groups and assign those groups permissions from given list of permissions. I have been reading about group permissions and have concluded that Django's Group model is not good choice for this as it doesn't allow multiple groups with same name and some other issues. I looked into some projects like Django-guardian. But don't seem to get an example that fits my case. What I want to do is. A Vendor will have staff users who will then be assigned to groups. So to check permission for a given group or user I will need to take Vendor into consideration. They must be member of the vendor staff and then the permission group. Can anyone point me in the right direction. Thank you -
nginx 502 error on digitalocean after copying code from dev folder to mail folder
I have a Django app deployed on DigitalOcean with Nginx, PostgresSQL. I have copied my code from my main folder to another dev-folder, so initially, both the folders have the same code. Now, I run python manage.py runserver 0.0.0.0:8000 in my def-folder and can access my application on https://server_ip:8000/. Now, I can make any changes in my code without affecting the main application. Once changes are done, I run cp -a /source/. /dest/ to copy my changes from the dev-folder to the main folder. It all looks good, but after copying code from the dev-folder to the main folder, my application gives a 502 error. The error disappears after running systemctl restart gunicorn. But why nginx is giving 502, when there is no timeout issue. Also, is this the accepted way of maintaining dev branch?? -
Django image file upload API no media is getting saved
I am trying to upload image to the server using Django API. The link is getting saved into the database but the actual media is not getting saved in /media folder. My models.py class File(models.Model): # file = models.FileField(blank=False, null=False) file = models.ImageField(upload_to='media/', blank=True) remark = models.CharField(max_length=20) timestamp = models.DateTimeField(auto_now_add=True) url.py: path('upload/', views.FileView.as_view(), name='file-upload'), serializer.py User Interest Serializer class UserInterestSerializer(serializers.ModelSerializer): class Meta: model = UserInterest fields = "__all__" views.py class FileView(generics.ListCreateAPIView): queryset = File.objects.all() serializer_class = FileSerializer Global setting: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Output: Link name is getting saved in the database: "id": 18, "file": "https://<URL>/media/home/tguser/tgportal/core/media/check.png", "remark": "ok", "timestamp": "2021-03-19T16:43:50.131435Z" } But actual media is not getting saved into media folder. Multiplart/form-data is set through postman. Am i doing anything wrong? Do i need /media folder permission? Any help is appreciated. Thanks, PD -
django server is auto reloading and not stopping
I am working on a web project. One moment before all was good but suddenly django localhost server kept itself reloading and not stopping auto-reloading the pages. First I got the following error connectionreseterror: (errno 104) connection reset by peer But now it's not showing any error just reloading itself over and over again. What could be the cause for this? Any help will be appriciated -
'bytes' object has no attribute 'encode' in EmailMessage
I am trying to make an app in Django which accepts information from user and send a HTML template as pdf through an e-mail to the user. But I am getting this error 'bytes' object has no attribute 'encode' Here is my view for the email def email(request, serial_no): user = get_object_or_404(Student, pk=serial_no) # roll_no = {'roll': str(user['roll_no'])} html = render_to_string('card.html', {'user': user}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename={}'.format(user.roll_no + '.pdf') pdf = weasyprint.HTML(string=html, base_url='').write_pdf( stylesheets=[weasyprint.CSS(string='body { font-family: serif}')]) to_emails = [str(user.roll_no) + '@gmail.com'] subject = "Certificate from Nami Montana" email = EmailMessage(subject, body=pdf, from_email='SSC', to=to_emails) email.attach("{}".format(user.roll_no) + '.pdf', pdf, "application/pdf") email.content_subtype = "pdf" # Main content is now text/html email.encoding = 'utf-8' email.send() return HttpResponseRedirect(reverse('id_card:submit')) Thanks in advance -
Problem about getting data from an online csv and put them into a Django database
scripts\loadDateData.py import csv import io import urllib.request from database.models import locationData, dateData def run(): target = locationData.objects.get (pk = 1) webpage = urlib.request.urlopen(target) #from stackoverflow reader = csv.DictReader(io.TextIOWrapper(webpage)) #from stackoverflow dateData.objects.all().delete() for row in reader: d, created = dateData.objects.get_or_create (date = row ["As of date"]) c, created = dateData.objects.get_or_create (confirmedCase = row ["Number of confirmed cases"]) dc, created = dateData.objects.get_or_create (deathCase = row ["Number of death cases"]) n = target.name temp = dateData (name = n, date = d, confirmedCase = c, deathCase = dc) temp.save() models.py from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator #from django.contrib.postgres.fields import ArrayField # Create your models here. class locationData (models.Model): locationID = models.AutoField (primary_key = True) name = models.CharField (max_length = 64) population = models.IntegerField (default = 0, validators = [MinValueValidator(0)]) apiEndpoint = models.URLField (max_length = 256) resourceURL = models.URLField (max_length = 256) class dateData (models.Model): entryID = models.AutoField (primary_key = True) name = models.CharField (max_length = 64) date = models.DateField (auto_now = False, auto_now_add = False) confirmedCase = models.IntegerField (default = 0, validators = [MinValueValidator(0)]) deathCase = models.IntegerField (default = 0, validators = [MinValueValidator(0)]) I am a beginner and I am working on a project about a web-based application to show … -
How to get the absolute path of a uploaded file in Django?
Hello django noob here, I am creating a form where user selects the path where he wants to store his results. And for that I am using FileField model to get the file path from user. But when using the following line of code I am not getting the absolute path of the file that user has uploaded. Please take a look at the code to understand better. models.py class UploadImageModel(models.Model): importPath = models.FileField() views.py def uploadImage(request): if request.method == 'POST': input1 = request.FILES.get('import_path') path = UploadImageModel(importPath=input1).importPath.path print(path) return render(request,'home.html') Now, my project is in directory: C:Users/admin/Desktop/MyProject And the output path variable gives is: C:Users/admin/Desktop/MyProject/filename But the original path of uploaded file is: C:Users/admin/Desktop/Data/filname So how do I get the original file path when user uploads a file? Please help me with this issue -
Stack overflow error when running tests in Django
When attempting to run a selenium test in django I am getting the following error: ConnectionResetError: [Errno 54] Connection reset by peer ---------------------------------------- Not found Fatal Python error: Cannot recover from stack overflow. Python runtime state: initialized Thread 0x000070000cc31000 (most recent call first): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/selectors.py", line 415 in select File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 232 in serve_forever File "/Users/nfishel/Documents/capstone-project-film-club/env/lib/python3.8/site-packages/django/test/testcases.py", line 1380 in run File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932 in _bootstrap_inner File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 890 in _bootstrap Current thread 0x00000001113b7dc0 (most recent call first): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/enum.py", line 561 in __new__ File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/enum.py", line 304 in __call__ File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socket.py", line 103 in _intenum_converter File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socket.py", line 920 in getaddrinfo /urllib3/connection.py", line 234 in request The test causing this issue was previously working, but I am trying to create a parent class with alot of the set up functions to cut down on code duplication for the tests. This is the parent class: class ParentTestCase(LiveServerTestCase): def setUp(self): self.selenium = webdriver.Chrome() self.signup() self.pick_genres() def tearDown(self): self.selenium.quit() super(LogoutTestCase, self).tearDown() def signup(self): selenium = self.selenium selenium.get(self.live_server_url + '/register') firstName = selenium.find_element_by_id('id_first_name') lastName = selenium.find_element_by_id('id_last_name') username = selenium.find_element_by_id('id_username') email = selenium.find_element_by_id('id_email') password1 = selenium.find_element_by_id('id_password1') password2 = selenium.find_element_by_id('id_password2') submit = selenium.find_element_by_id('id_register') firstName.send_keys('Test') lastName.send_keys('Tester') username.send_keys('Test123') email.send_keys('test123@test.com') password1.send_keys('moviepass') password2.send_keys('moviepass') submit.click() def pick_genres(self): selenium … -
displaying django custom validation
Hi I am a newbie in Django, so I want to show some error message in html, I have done methods in forms, def clean_FirstName(self): But I want to show that error message near the first name textbox, how I will do it? -
pip won't install channels_redis
for working with django channels i need to install "channels_redis". while installing "channels_redis" i face this error, any thought? by the way i'm on windows and it showed me an error of C++ first and after installing Microsoft visual studio build tools vanished and now this. ERROR: Command errored out with exit status 1: command: 'E:\Programming projects\Django\channels\chat_launch01\venv\Scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\KaNi\\AppData\\Local\\Temp\\pip-install-dt2d0_z3\\hiredis_a7d15f1044b343288a4bc87864c6418e\\setup.py'"'"'; __file__='"'"'C:\\ Users\\KaNi\\AppData\\Local\\Temp\\pip-install-dt2d0_z3\\hiredis_a7d15f1044b343288a4bc87864c6418e\\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 'C:\Users\KaNi\AppData\Local\Temp\pip-wheel-m0bnautd' cwd: C:\Users\KaNi\AppData\Local\Temp\pip-install-dt2d0_z3\hiredis_a7d15f1044b343288a4bc87864c6418e\ Complete output (23 lines): C:\Users\KaNi\AppData\Local\Temp\pip-install-dt2d0_z3\hiredis_a7d15f1044b343288a4bc87864c6418e\setup.py:7: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import sys, imp, os, glob, io E:\Programming projects\Django\channels\chat_launch01\venv\lib\site-packages\setuptools\dist.py:642: UserWarning: Usage of dash-separated 'des cription-file' will not be supported in future versions. Please use the underscore name 'description_file' instead warnings.warn( running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.9 creating build\lib.win-amd64-3.9\hiredis copying hiredis\version.py -> build\lib.win-amd64-3.9\hiredis copying hiredis\__init__.py -> build\lib.win-amd64-3.9\hiredis running build_ext building 'hiredis.hiredis' extension creating build\temp.win-amd64-3.9 creating build\temp.win-amd64-3.9\Release creating build\temp.win-amd64-3.9\Release\src creating build\temp.win-amd64-3.9\Release\vendor creating build\temp.win-amd64-3.9\Release\vendor\hiredis d:\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.28.29910\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ivendor -IE:\ Programming projects\Django\channels\chat_launch01\venv\include -Ic:\users\kani\appdata\local\programs\python\python39\include -Ic:\users\kani\a ppdata\local\programs\python\python39\include -Id:\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.28.29910\include -IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt /Tcsrc\hiredis.c /Fobuild\temp.win-amd64-3.9\Release\src\hiredis.obj hiredis.c c:\users\kani\appdata\local\programs\python\python39\include\pyconfig.h(200): fatal error C1083: Cannot open include file: … -
Django problem connection after deployment postgres nginx
After deployment on my vps with ubuntu 18.0.4, ngix, gunicorn and postgresql, I can only connect into the admin area but when I try to connect as a simple user I got error 500 it seem like there is not connection between the application and postgres, even when I put wrong email and password I got error 500 but I can connect as I said into the admin Area. Any idea regarding my problem ? Thank you very much. -
no video with supported format and MIME type found in django
no video with supported format and MIME type found A huge screen for video is displayed and says the message above. How do I solve this? This happens to me only in Mozilla Firefox and not on Google Chrome. I am using webm videos and mp4 videos. I'm Uploading a video from the admin panel model.py class Video(models.Model): caption = models.CharField(max_length=70) video = models.FileField(upload_to='video') view.py from .models import Video def home(request): video = Video.objects.all() return render(request, 'video/index.html', {'videos':video}) url.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) home.html {% for video in videos %} <video width="320" height="240" controls> <source src="{{video.video.url}}" type="video/webm"> </video> {% endfor %} -
Hello, im trying to dislpay and image on the django administartion but its just showinig the image extention on the panel
models.py def admin_photo(self): return mark_safe('<img src="()" width="100" />'.format(self.car_image.url)) admin_photo.short_description ="image" admin_photo.allow_tags = True admin.py class CarsAdmin(admin.ModelAdmin): # fields = ('car_name', 'car_image', 'car_model_number', 'car_millage', 'car_description', 'car_price') fields = ('admin_photo',) readonly_fields = ('admin_photo',) list_display = [ 'car_image', 'car_name' ] Hello, im trying to dislpay and image on the django administartion but its just showinig the image extention on the panel -
Django serilizator object updating problem
i would like to ask where could be problem with my serilizator or calling of him. I want to update serializated data inside object personal info but it keep throwing me error: AttributeError: 'PersonalInfoSerializer' object has no attribute 'user' Here's my serilizator class: class PersonalInfoSerializer(serializers.Serializer): user = serializers.IntegerField(required=False) firstname = serializers.CharField(max_length=255) lastname = serializers.CharField(max_length=255) card_id = serializers.CharField(max_length=255) street = serializers.CharField(max_length=255) postal_code = serializers.IntegerField() city = serializers.CharField(max_length=255) debet_card_number = serializers.CharField(max_length=16) created_at = serializers.DateTimeField(required=False) last_update = serializers.DateTimeField(required=False) def create(self, validated_data): return PersonalInfo.objects.create(**validated_data) def update(self, instance, attrs): print("instance", attrs.get('user', instance.user)) instance.user = attrs.get('user', instance.user) instance.save() return instance And here is my view function thats updating serilizator object: json = BytesIO(request.body) data = JSONParser().parse(json) data.update({'created_at': datetime.datetime.now(tz=timezone.utc), 'last_update': datetime.datetime.now(tz=timezone.utc), 'last_login': datetime.datetime.now(tz=timezone.utc), 'token':generate_key()}) user = UserSerializer(data=data) personal_info = PersonalInfoSerializer(data=data) if user.is_valid() and personal_info.is_valid(): if user_exists(data["email"]): response = {'Failed': 'email is already used'} return JsonResponse(response) elif card_exists(data["card_id"]): response = {'Failed': 'card id is already used'} return JsonResponse(response) else: user.save() personal_info = PersonalInfoSerializer(personal_info, {'user':10}, partial=True) personal_info.is_valid() personal_info.save() I think main problem is calling serilizator update but i tried everything :/ Thank you for help :) -
App using Django runs server only once after cloning
I cloned a private GitHub repository that was created using Django into visual studio code and set it up the following way: Open project in visual studio code, there open the project's terminal Create a virtual environment using python -m venv .\venv Active that virtual environment using venv\scripts\activate Import all packages from requirements.txt individually. Since pip freeze -r requirements.txt was giving me an error, I installed each package using pip install packageName Check all models migrated to database with python manage.py makemigrations followed by python manage.py migrate Start server using python manage.py runserver At this point I clicked the local host link and it runs well but after I close the server and try to open it again I first get the error ModuleNotFoundError: No module named 'pymysql'. Then when I do pip install pymysql I get the errors: ModuleNotFoundError: No module named 'rest_framework' OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' After I try and fix the first one by using pip to install rest_framework I only get the same error three times consecutively: Winerror [10061]: No connection could be made because the target machine actively refused it. At this point, I … -
How to solve "FileNotFoundError: [Errno 2] No such file or directory: '/code/static" when deploying a django app to heroku?
I was reading William S. Vincent's book Django for Professionals book, and I tried to deploy a django app to heroku, but static folder location fails while deploying this app, i am using Docker and whitenoise package for handling the static files, here important information in files. settings.py import dj_database_url import socket from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Este cambio es para el despliegue en heroku, ya que hay problemas con los archivos estáticos # para más información vea: https://devcenter.heroku.com/articles/django-assets #BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # El entorno, producción vs desarrollo ENVIRONMENT = os.environ.get('ENVIRONMENT', default='production') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! # por defecto 0, ya que el proyecto estará pronto en producción DEBUG = int(os.environ.get('DEBUG', default=0)) ALLOWED_HOSTS = ['aplicacion-de-ventas.herokuapp.com', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.sites', # 3rd party 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.github', 'allauth.socialaccount.providers.google', 'debug_toolbar', # local apps 'pages.apps.PagesConfig', 'ventas.apps.VentasConfig', 'perfiles.apps.PerfilesConfig', ] MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', … -
docker-compose not creating app for django backend
I am not sure why im not able to serve my django app that i am building with Docker and React. So far I am only at the django level (backend) and its not working. I have the following structure: project (main folder) | |__ docker-compose.yml |__ .env (where i store all the custom database name, user and password) > backend > university | |__ Dockerfile |__ requirements.txt |__ manage.py > frontend I havent connected the front end yet. here my configuration of the Dockerfile of the backend FROM python:3.8 ENV PYTHONUNBUFFERED 1 WORKDIR /app/backend/ COPY requirements.txt /app/backend/ RUN pip install -r requirements.txt COPY . /app/backend and the docker-compose of the main project version: '3.7' services: web: build: ./back_end/university restart: unless-stopped command: python /app/backend/manage.py runserver 0.0.0.0:8000 volumes: - .:/app/backend ports: - 8000:8000 depends_on: - db db: image: postgres:11 restart: always environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '${DB_NAME}', 'USER': '${DB_USER}', 'PASSWORD': '${DB_PASSWORD}', 'HOST': 'db', 'PORT': 5432 } } so when i run docker-compose up -d --build it does build everything but im not able to serve runserver and see the regular django app on port 8000 … -
Static Files Not Loading Django
I am following a tutorial, and I copied the repo, Add for some reason, the static files will not load. This is my folder structure involves having my templates file in my main app and my static files are outside this folder. In the main folder (Django-ecommerce) sitting where my main app is. P.S I have tried moving my static folder into my main app folder but it still does not work. here is my settings.py import os ENVIRONMENT = os.getenv('ENVIRONMENT', 'development') DEBUG = False BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '-05sgp9!deq=q1nltm@^^2cc+v29i(tyybv3v2t77qi66czazj' ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'crispy_forms', 'django_countries', 'core' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware' ] ROOT_URLCONF = 'demo.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ 'templates' ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # static files (CSS, JS, Image) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, '/static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root') DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, … -
Why am I having this Heroku deploying problem?
I have a Django app to be deployed using Heroku, but something went wrong: Processing /tmp/build/80754af9/asgiref_1594338739818/work ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/tmp/build/80754af9/asgiref_1594338739818/work' Below, my requirements.txt file: asgiref==3.2.10 astroid==2.4.2 certifi==2020.6.20 colorama==0.4.3 dj-database-url==0.5.0 Django==3.0.3 django-heroku==0.3.1 django-widget-tweaks==1.4.5 gunicorn==20.0.4 isort==4.3.21 lazy-object-proxy==1.4.3 mccabe==0.6.1 olefile==0.46 pillow==7.2.0 psycopg2==2.8.5 pylint==2.5.3 python-decouple==3.3 pytz==2020.1 six==1.15.0 sqlparse==0.3.1 toml==0.10.1 whitenoise==5.2.0 wincertstore==0.2 wrapt==1.11.2 I've connected Heroku to a Github repository. Do you have any idea what's happening ? -
I'm trying to build an app using Django framework
localhost showing 'TemplateDoesNotExist' especially when i add path('', include('proapp2.urls')), to the settings.py of the project folder. but as soon as i remove path('', include('proapp2.urls')), the Django homepage start showing. -
Django: annotate ranking from related objects
the models: class Competition(TimeStampedModel): name = models.CharField(max_length=255) class Playlist(TimeStampedModel): competition = models.OneToOneField(Competition, on_delete=models.CASCADE, related_name='playlist') class Entry(TimeStampedModel): title = models.CharField(max_length=255) by = models.CharField(max_length=255) class Vote(TimeStampedModel): entry = models.ForeignKey(Entry, on_delete=models.CASCADE, related_name="votes") score = models.IntegerField(validators=[validate_vote_value]) class PlaylistEntry(TimeStampedModel): playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE, related_name='entries') entry = models.ForeignKey(Entry, on_delete=models.CASCADE, related_name='playlistentries') A Competition has one playlist. A Competition playlist has many PlaylistEntry. A PlaylistEntry is one Entry. One Entry can have multiple Vote. What I was able to achieve: Votes for entries counted. What I need to achieve: Ranking for each Playlist. The code I am using now: def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx["compos"] = Playlist.objects \ .filter(competition__hidden_in_results=False) \ .prefetch_related( Prefetch( "entries", PlaylistEntry.objects .select_related("entry") .annotate(score=Sum("entry__votes__score")) .annotate(rank=Window(expression=Rank(), order_by=F('score').desc())) .annotate(overall_rank=Window(expression=Rank(), order_by=F('score').desc())) .all(), to_attr="compo_entries" )) \ .select_related("competition") \ .order_by("competition__results_play_order") return ctx This gives me Sum of votes for each Entry as I want. It also gives me a ranking as a total in all PlayList. I would need a ranking per Playlist Current output: Playlist Item 1 Rank Overall Score 113. 113. 196 124. 124. 178 Playlist Item 2 Rank Overall Score 56. 56. 336 62. 62. 323 What I would like: Playlist Item 1 Rank Overall Score 1. 113. 196 2. 124. 178 Playlist Item 2 Rank Overall … -
widget attrs with self.helper.layout
I'm trying to use in form this forms: class RequestCreateForm(forms.ModelForm): class Meta: model = Request fields = [ 'supplier', 'status', 'requester', 'Procurement', 'comments', ] widgets = { 'supplier': forms.Select(attrs={ 'class': 'form-group col-md-4 mb-0', }), 'Procurement': forms.Select(attrs={ 'class': 'form-group col-md-4 mb-0', }), 'status': forms.Select(attrs={ 'class': 'form-group col-md-4 mb-0', }), 'comments': forms.TextInput(attrs={ 'class': 'form-group col-md-4 mb-0', 'placeholder': 'Enter comment to be print with PO'}), } def __init__(self, *args, **kwargs): super(RequestCreateForm, self).__init__(*args, **kwargs) self.fields['comments', 'Procurement'].required = False self.fields['requester','status'].widget.attrs['readonly'] = True self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Row( Column('supplier', ), Column('status', ), ), Row( Column('Procurement', ), Column('comments', ), ), ) DetailRequestFormSet = inlineformset_factory( Request, RequestDetails, fields=('item', 'typeItem', 'skuinterne', 'skusupplier', 'uomm', 'qty', 'PU', ), extra=3, can_order=True ) but it seems that my template: {% extends "base.html" %} {% load crispy_forms_tags %} {% load tailwind_filters %} {% block content %} <div class="container mx-auto flex flex-wrap"> <div class="w-full mb-6 py-6 flex justify-between items-center border-b border-gray-200"> <div><h3 class="text-2xl text-gray-800">New Request</h3></div> <div><a class="hover:text-blue-500" href="{% url 'items:item_list' %}">Go back to request</a></div> </div> </div> <form method="post"> {% csrf_token %} {% crispy request %} {% for form in requestdetails %} <div class="link-formset"> {% crispy form %} </div> {% endfor %} </form> {% endblock content %} my views: def requestcreateview(request): … -
How can I create unique javascript variable names in a django template for loop?
I am using a django template to loop through hp_tracker objects. Each hp_tracker has its own js code which is used for changing the value via ajax. I'm almost certain I should have this code in the .js file but I was having trouble finding a way to uniquely select each hp_tracker without access to the django template variables in the .js file. So...I moved the js to the html template itself. I am aware this undoubtedly has massive security implications, and I'm open to discussing those as well. Anyway, on to my question. My js fails because I have global variables(!) declared that are not unique. They are being used to control some counters and a setTimeout and I don't see how to now use them to do what I want to do. So the for loop tries to re-declare the same variable over and over. Throughout the rest of the script I'm using JQuery which is perfectly happy to use the django variable {{ hp_tracker.id }}, but javascript is not because "-" characters, which are in the object IDs are not allowed in variable names. What the heck should I do here to fix this hot mess. Is … -
Django as socket.io client
I'm trying to setup a system composed by two servers. One remote express.js api with a socket.io server and a local django one as a socket.io client. For my purpose I want to exchange data frequently between the systems. The problem is that I can't figure out how to integrate a socket.io client with django. I can do it in plain python thanks to the python-socketio package with no problems but integrating it with the framework is tricky. Basically the socket.io client scripts needs to run at django startup and terminate with the server. From what I have understand celery isn't a solution in my case. The socket needs to have access to django database and models system Does anyone have a clean way to implement this? -
Django post operation "violates not-null constraint"
My forms.py: class ReviewForm(ModelForm): class Meta: model = Review fields = ['review_text'] My models.py: class Review(models.Model): reviewer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') review_text = models.TextField(max_length=100000) created_time = models.DateTimeField() def __str__(self): return self.question_text def was_published_recently(self): return self.created_time >= timezone.now() - datetime.timedelta(days=1) My views.py: class IndexView(generic.ListView): template_name = 'review/index.html' context_object_name = 'reviews' def get_queryset(self): return Review.objects.order_by('-created_time')[:5] def create(request): if request.method == 'POST': form = ReviewForm(request.POST) if user_form.is_valid(): form.save() return redirect('review:index') else: pass form = ReviewForm() context = { 'form': form, } return render(request,'review/create.html', context) When I create a post, the error message says I'm violating the non-null constraint for "created_time." The message show 1 for id, dfkjdslafd for review_text, and null for created_time and null for reviewer_id. The data is not saved in the database. When I add the following to the forms.py fields = ['id', 'review_text', 'created_time', 'reviewer_id'] The whole app doesn't run, saying 'django.core.exceptions.FieldError: Unknown field(s) (reviewer_id) specified for Review' in the terminal. I am new to django from rails. Finding simple CRUD much more cumbersome with django -- I must be doing something wrong. I'd appreciate any help.