Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can not display form in django
i made a from , but for some reason it not show up when i try to display it. my forms supposed to collet information for blood donation. i did it by tutorial, and in the tutrial it just showed up, same as in any other tutorial i saw after. my models.py from django.db import models from django.contrib.auth.models import User class donate(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) doner_ID = models.CharField(max_length=9) blood_types = [ ('A+','A+'), ('B+','B+'), ('AB+','AB+'), ('O+','O+'), ('A-','A-'), ('B-','B-'), ('AB-','AB-'), ('O-','O-'), ] blood_type = models.CharField( max_length=3, choices=blood_types, default=blood_types[0], ) donation_date = models.DateField(auto_now_add=True) def __str__(self): return self.first_name my forms.py from django import forms from django.forms import ModelForm from .models import donate class donationForm(ModelForm): class Meta: model = donate fields = ('first_name', 'last_name', 'doner_ID', 'blood_type') my views.py from .forms import donationForm from .models import donate def donation(request): form=donationForm if request.method == 'POST': return render(request, 'main\donation.html', {'from':form}) else: return render(request, 'main\donation.html', {'from':form}) the donation.html page {% extends 'main\design.html'%} {% block design %} {{ errors }} <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-outline-danger btn-block">Submit</button> </form> {% endblock %} -
Pytest-django won't post json data leading to assertion error. Not permission/method related
I'm writing a test for my django online project and I'm stuck in a function that returns 201 if data is valid (it's testing if data is valid when creating a new product for the store.). Django version 4.1.7 Django Rest Framework 3.14.0 pytest 7.2.2 pytest-django 4.5.2 The issue is that no matter what data I input in the function it always returns a 400 error. I'm sure it's not a permission issue because I've got authenticate(is_staff=True), which works in the previous functions. Also, I'm able to post a "Product" both in the Admin panel and in the products url if i'm logged with an account with Staff privileges. Here's the test_products.py code: from store.models import Collection, Product from rest_framework import status import pytest from model_bakery import baker @pytest.fixture def create_product(api_client): def do_create_product(product): return api_client.post('/store/products/', product) return do_create_product @pytest.mark.django_db class TestCreateProduct: def test_if_user_is_anonymous_returns_401(self, create_product): response = create_product({'title': 'a'}) assert response.status_code == status.HTTP_401_UNAUTHORIZED def test_if_user_is_not_admin_returns_403(self, authenticate, create_product): authenticate() response = create_product({'title': 'a'}) assert response.status_code == status.HTTP_403_FORBIDDEN def test_if_data_is_invalid_returns_400(self, authenticate, create_product): authenticate(is_staff=True) response = create_product({'title': ''}) assert response.status_code == status.HTTP_400_BAD_REQUEST assert response.data['title'] is not None def test_if_data_is_valid_returns_201(self, authenticate, create_product): authenticate(is_staff=True) response = create_product({ "title": "abc", "slug": "abc", "inventory": 1, "unit_price": 2, "collection": … -
raise ToolError(u"Command %s failed" % name) cfnbootstrap.construction_errors.ToolError: Command 01_makemigrations failed
I'm trying to deploy a Django project in AWS Elastic Beanstalk and seems to be an error with the command makemigrations.. I've configured it this way in my django.config file: container_commands: 01_makemigrations: command: "source /var/app/env/*/bin/activate && python3 manage.py makemigrations --noinput" leader_only: true 02_migrate: command: "source /var/app/env/*/bin/activate && python3 manage.py migrate --noinput" leader_only: true I don't know if my config is OK. It's my first time trying to deploy a project and I've followed the steps i've found in a tutorial.. -
Hello Ј'ai this error after deploying my application, Key error
Hello Ј'ai this error after deploying my application, I checked everything works locally for users on Django admin. I don't understand this mistake; Could you help me? It looks like it's from the library in django admin and he says he doesn't know the value 1, so maybe it's a problem with this version of django; I would like to point out that I am using version 3.2.12 of django and that I am using a mysql database. enter image description here -
Django - How do I update one field after my ModelForm has changed another?
I have a ModelForm that currently is used to update 2 fields in a Model. Users don't have to update both fields, however, when they do update the "study" field I need to trigger an update to the "user_study_tag" field to 'True' in the model instance. If they simply update the "notes" field (and not the "study" field), I don't want that update happening. forms.py class Run_UpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") site_study_list = kwargs.pop("site_study_list") super(Run_UpdateForm, self).__init__(*args, **kwargs) self.fields["study"].queryset = Study.objects.filter(name__in=site_study_list) class Meta: model = Runs fields = ( "study", "notes", ) models.py class Runs(models.Model): name = models.CharField(max_length=200) guid = models.CharField(max_length=100) site = models.CharField(max_length=30, choices=site_choices, default="-") instrument = models.CharField(max_length=30, default="-") study = models.ForeignKey(Study, on_delete=models.CASCADE, null=True, blank=True) user_study_tag = models.BooleanField(default=False) project = models.CharField(max_length=30, default="-") inventory = models.BooleanField(default=False) inventory_missing = models.BooleanField(default=False) inventory_dismissed = models.BooleanField(default=False) qc_run = models.BooleanField(default=False) analysis_end_date = models.DateTimeField(default=datetime.now, blank=True) archive = models.BooleanField(default=False) notes = models.CharField(max_length=200, default="-", null=True, blank=True) def __str__(self): return f"{self.name}" I thought I could use the clean(self) method in the model, but I don't think that is the right way to handle this issue since I don't know how to compare the form self.study to the model study that is potentially being changed. -
List comprehension vs. for loop
In an effort to avoid Django ModelSerialization performance hits, I am looking at "serializing" a result set on my own. Research says that list comprehension should be the fastest, but my own tests are showing nested for loops being consistently faster. I have raw DB results (100) that need to be converted into a list of OrderedDict based on an ordered list of fields (14). Is my use case too complex for the list comprehension performance advantage, or my sample size too small? Maybe the performance is negligible? Nested for-loop (0.000919342041015625) serialized = [] start = time.time() for raw in results: result = OrderedDict() for index, field in enumerate(fields): result[field] = raw[index] serialized.append(result) end = time.time() print("For loop + for loop " + str(end - start)) Nested list comprehension (0.011911153793334961) serialized = [] start = time.time() serialized = [OrderedDict((field, raw[index]) for index, field in enumerate(fields)) for raw in results] end = time.time() print("List comprehensions + list comprehensions " + str(end - start)) For-loop + list comprehension (0.020151615142822266) serialized = [] start = time.time() for raw in results: result = OrderedDict((field, raw[index]) for index, field in enumerate(fields)) serialized.append(result) end = time.time() print("For loop + list comprehensions " + str(end - start)) -
How to broadcast a message to channels groups from the outside of consumer in django channel
If you have any suggestions and solutions please let me know. Currently I'm using channels=4.0.1 -
Images not appearing on page - Django
I'm writing my django tutorial project and I've run into a problem that hasn't happened before. When I try to display a picture loaded into a model instance using it, it does not want to be displayed in any way, while the rest of the model fields are displayed correctly: models.py: from django.db import models from django.urls import reverse class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True) price = models.PositiveIntegerField() description = models.TextField() time_create = models.TimeField(auto_now_add=True) is_published = models.BooleanField(default=True) category = models.ForeignKey('ProductCategory', on_delete=models.PROTECT, verbose_name="Категории") brand = models.ForeignKey('Brand', on_delete=models.PROTECT, verbose_name="Бренд") photo_front = models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name="Главное фото", blank=True) photo2 = models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name="Фото 2", blank=True) photo3 = models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name="Фото 3", blank=True) photo4 = models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name="Фото 4", blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('product', kwargs={'product_slug': self.slug}) test.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ title }}</title> </head> <body> {% for b in posts %} <p>{{ b.title }}</p> <img src="{{ b.photo_front.url }}"> {% endfor %} </body> </html> the result is the following output: Images not found And this is what the code outputs in the browser: Browser code And this is what the console says Not Found: /media/photos/2023/03/16/616036_XJFF9_1152_001_100_0000_Light-Cotton-T-shirt-with-Gucci-Blade-print.jpg Not Found: /media/photos/2023/03/16/623953_XDBBQ_4011_001_100_0000_Light-Regular-fit-washed-jeans.jpg Not Found: /media/photos/2023/03/16/clipboard_image_bfd7cf0e7879207e.jpg In general, I assume that … -
django getting data from other model with fk
i have this models class Bus(models.Model): bus_name = models.CharField('Name', max_length=10, unique=True, blank=False, null=False) __________________________________________________ class Soc(models.Model): value = models.FloatField(...) bus = models.ForeignKey(Bus....) __________________________________________________ class Iso(models.Model): value = models.FloatField(...) bus = models.ForeignKey(Bus....) What i want is access to iso value and soc value from the bus model but i dont know how ... any ideas?? -
Django API Query of 2198 Items takes almost 6min how can i improve the speed
I need to query my whole table. This is my view and serializer: @api_view(['GET']) def autofill_api(request): items = Product.objects.all() print(items) serializer = AutoFillSerializer(items, many=True) return Response(serializer.data) class AutoFillSerializer(serializers.ModelSerializer): # integrating the foreignkey Brand_Name into the serializer brand_name = serializers.CharField(source='brand.brand') class Meta: model = Product fields = __all__ Problem The Query takes almost 6min. These are the infos the Django Debug Toolbar gives me. 2198 SQL Queries 376888.26ms Are there any options to make this query faster? In the future i will use Django cache_page decorator. But for the case when my database is updated i don't want the user to wait 6min. -
encoding with 'idna' codec failed (UnicodeError: label empty or too long) Django send_mail
When sending a message to the mail via the send_mail function, an error appears - encoding with 'idna' codec failed (UnicodeError: label empty or too long) What could be the problem and how to make the encoding work correctly And what is most interesting, everything worked fine on another computer and messages were sent without any problems, so the error is clearly not in settings.py models.py file: from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User from slugify import slugify class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts', on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=9, choices=STATUS_CHOICES, default='draft') name = models.CharField(max_length=25, default='') email = models.EmailField(default='') to = models.EmailField(default='') comments = models.TextField(null=True) class Meta: ordering = ('-publish',) def get_absolute_url(self): return reverse('post-detail', args=( self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug, )) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(f'{self.title} {self.author}') super().save(*args, **kwargs) def __str__(self): return self.title settings.py file: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my_mail@gmail.com' EMAIL_HOST_PASSWORD = 'my_password' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False views.py file: def post_share(request, slug): post … -
Custom BooleanField name in Django admin list filter
In Django admin I can change default True/False representation of BooleanField using choices argument. It appears in object page and list page. But it doesn't changes in admin list filter. Why? How can I change defaults 'All/Yes/No/Unknown' in list_filter? app/models.py CHOICES_BUILDING_CONDITION = ( (True, 'New'), (False, 'Old'), (None, 'Unknown'), ) class Flat(models.Model): is_new_building = models.BooleanField( 'Building condition', null=True, blank=True, choices=CHOICES_BUILDING_CONDITION ) app/admin.py class FlatAdmin(admin.ModelAdmin): list_filter = ('is_new_building', ) -
How to run django-apscheduler within a docker container that runs django via gunicorn
Is it possible to run django-apscheduler inside a docker container that runs django via gunicorn? Currently I have the problem that the custom manage.py command inside my entrypoint script runs forever and therefore gunicorn is never being executed. My entrypoint script: #!/bin/sh python manage.py runapscheduler --settings=core.settings_dev_docker My runapscheduler.py # runapscheduler.py import logging from django.conf import settings from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.triggers.cron import CronTrigger from django.core.management.base import BaseCommand from django_apscheduler.jobstores import DjangoJobStore from django_apscheduler.models import DjangoJobExecution from django_apscheduler import util from backend.scheduler.scheduler import scheduler logger = logging.getLogger("backend") def my_job(): logger.error("Hello World!") # Your job processing logic here... pass # The `close_old_connections` decorator ensures that database connections, that have become # unusable or are obsolete, are closed before and after your job has run. You should use it # to wrap any jobs that you schedule that access the Django database in any way. @util.close_old_connections # TODO: Change max_age to keep old jobs longer def delete_old_job_executions(max_age=604_800): """ This job deletes APScheduler job execution entries older than `max_age` from the database. It helps to prevent the database from filling up with old historical records that are no longer useful. :param max_age: The maximum length of time to retain … -
Django Queryset: group by two field values
I have a model like this Class ExchangeMarket(models.Model): base_currency = models.ForeignKey(Currency) quote_currency = models.ForeignKey(Currency) ... various other fields And some entries like base: EUR, quote: USD ... base: EUR, quote: USD ... base: USD, quote: EUR ... base: BTC, quote: USD ... ... I need to find entries sharing the base/quote combination, i.e. in my example that's the first three How to create such a queryset? If I do something like ExchangeMarket.objects.all().values('base_currency', 'quote_currency').annotate(pks=ArrayAgg('pk')) I will only find exact matches with same bases and quotes (like EUR/USD, first two of my entries) while I need to find both EUR/USD and USD/EUR. Thanks! -
Django: color test result in console
I have a Django project for which I have tests (nothing special). The thing is I'd like to have colored results when running tests and I don't know how to do that. On a daily basis, I run tests from my Ubuntu terminal with the command python3 ./backend/manage.py test --settings="backend.settings.testing" backend/ --no-input --verbosity=2 and applying the migrations looks like this at the beginning of the tests : whereas the tests themselves have uncolored results like so : My question is : Is there a simple way to get those ok colored in green and if applicable 'ko' in red ? Thank you in advance. -
how to send real time data from my db to a minimal HTML with django channels?
I`ve read many topic but still not clear. like https://channels.readthedocs.io/en/stable/topics/databases.html I have a project in Django with two apps, one app save data into postgres and I want to send the stored data to a client asynchronously by the other app via django channels. my model contains two fields "data" and "created_date" and I want send those data into websocket client. I got no errors but data doesn`t show on html any thought? consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from save.models import WebhookData class MyConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, close_code): pass # async def receive(self, text_data): # data = json.loads(text_data) # # Get data from Postgres using Django ORM # queryset = WebhookData.objects.all() # # data = [{'id': obj.id, 'name': obj.name} for obj in queryset] # data = [{'id': obj.id} for obj in queryset] # print(data) # # Send data to the client # await self.send(text_data=json.dumps(data)) async def receive(self, text_data): data = json.loads(text_data) # Get data from Postgres using Django ORM queryset = WebhookData.objects.all() result = [] for obj in queryset: result.append({'data': obj.data}) print(result) # Send data to the client await self.send(text_data=json.dumps(result)) html: <!DOCTYPE html> <html> <head> <title>Async Data Example</title> </head> <body> <h1>Async Data Example</h1> … -
Django Form not rendering/loading in BS modal
i am trying to get a Form into a BS modal but the modal is always empty. Searched very much for a solution but nothing worked yet and im helpless. As im quite new to Python and Django i tried to set up a small Event page for updating/adding/deleting Events and Venues for Events. my views.py from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from .models import Event, Venue from .forms import VenueForm, EventForm from django.db.models.functions import Lower def add_event(request): submitted = False if request.method == "POST": form = EventForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/add_event?submitted=True') else: form = EventForm if 'submitted' in request.GET: submitted = True return render(request, 'events/add_event.html', {'form': form, 'submitted': submitted}) def list_venues(request): venue_list = Venue.objects.all().order_by(Lower('name')) return render(request, 'events/venues.html', { "venue_list": venue_list, }) def add_venue(request): submitted = False if request.method == "POST": form = VenueForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form = VenueForm if 'submitted' in request.GET: submitted = True return render(request, 'events/add_venue.html', {'form': form, 'submitted': submitted}) def all_events(request): event_list = Event.objects.all().order_by(Lower('name')) return render(request, 'events/event_list.html', { "event_list": event_list, }) urls.py from django.urls import path from . import views urlpatterns = [ # in path('events/', views.all_events, name="list-events"), path('add_venue', views.add_venue, name="add-venue"), path('list_venues', views.list_venues, name="list-venues"), path('add_event', views.add_event, name="add-event"), ] … -
Tokenauthentication for Angular as frontend and Django as backend
I have an application that uses Django as backend and Angular as frontend. When sending the log-in credentials (username: admin, password: password) via the frontend, it sets a localStorage token and then navigates to tasks. However, it is not a very secure way, since basically everyone can go to the console and write localStorage.setItem('token', 'anything') The code is in my github repository Any help is highly appreciated I tried to create a CustomAuthToken view and to render this view, but it gets blocked by CORS I think class CustomAuthToken(ObtainAuthToken): authentication_classes = [SessionAuthentication] @csrf_exempt def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'username': user.username, 'user_id': user.pk, 'email': user.email }) I also read about token authentication and played around with chatGpt to get up and running, but nothing worked as expected -
Django static files URL return None as part of the source
I have deployed my Django application on EC2 using Docker and Nginx. The static files are referencing a None as part of the URL. Like this <link rel="stylesheet" href="https://None/static/wagtailadmin/css/core.css?v=29e59b04"> These are the values of my settings >>> settings.MEDIA_ROOT '/home/ubuntu/mysite/mysite/media' >>> settings.STATIC_ROOT '/home/ubuntu/mysite/staticfiles' >>> settings.STATIC_URL 'https://mysite.s3.amazonaws.com/static/' >>> settings.MEDIA_URL 'https://mysite.s3.amazonaws.com/media/' # STORAGES # ------------------------------------------------------------------------------ # https://django-storages.readthedocs.io/en/latest/#installation # INSTALLED_APPS += ["storages"] # noqa F405 # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_ACCESS_KEY_ID = config("DJANGO_AWS_ACCESS_KEY_ID", default='mysite') # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_SECRET_ACCESS_KEY = config("DJANGO_AWS_SECRET_ACCESS_KEY", default='mysite') # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_STORAGE_BUCKET_NAME = config("DJANGO_AWS_STORAGE_BUCKET_NAME", default='mysite') # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_QUERYSTRING_AUTH = False AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' # DO NOT change these unless you know what you're doing. _AWS_EXPIRY = 60 * 60 * 24 * 7 # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_S3_OBJECT_PARAMETERS = { "CacheControl": f"max-age={_AWS_EXPIRY}, s-maxage={_AWS_EXPIRY}, must-revalidate" } # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_S3_MAX_MEMORY_SIZE = env.int( "DJANGO_AWS_S3_MAX_MEMORY_SIZE", default=100_000_000, # 100MB ) # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings AWS_S3_REGION_NAME = config("DJANGO_AWS_S3_REGION_NAME", default='us-west-2') # https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#cloudfront aws_s3_domain = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" # STATIC # ------------------------ AWS_PUBLIC_MEDIA_LOCATION = 'media/public' AWS_PRIVATE_MEDIA_LOCATION = 'media/private' STATICFILES_STORAGE = 'config.storage_backends.StaticStorage' # https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = "https://mysite.s3.amazonaws.com/static/" # MEDIA # ------------------------------------------------------------------------------ # DEFAULT_FILE_STORAGE = "mysite.utils.storages.MediaRootS3Boto3Storage" # https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = "https://mysite.s3.amazonaws.com/media/" Nginx configuration server { server_name mysite.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/ubuntu/mysite/mysite/static/; } location /media/ { alias /home/ubuntu/mysite/media/; } location … -
Can't open the django project index page in a browser side in EC2 AWS
Problem: I can't: 1)use a local browser to open http://<public IP>:8000 2)use terminal to curl -v http://<public IP>:8000 3)Ping I can: 1)use terminal to run curl -v http://127.0.0.1:8000, the result indicates the django server is working. Background: I'm working on a MacOS. Python 3.9.13,Django 4.1.7, MySQL 8.0.31. I setup my django project in my EC2 server, also setup a RDS which is working now. Today, I try to open the project's index page via my browser, but there is no response. So I checked inbound rules: 1)All traffic :0.0.0.0/0 2)Custom TCP :port: 8000, 0.0.0.0/0 3)Custom ICMP:echo request, 0.0.0.0/0 4)All TCP : My IP, x.x.x.x/32 5)SSH: port 22, 0.0.0.0/0 Also I set 1)public IP in the settings.py ALLOW_HOSTS = ['public IP', '127.0.0.1'] (no port) 2)firewall allows 8000 port sudo firewall-cmd --add-port=8000/tcp --permanent Finally, I run django server python manage.py runserver 0.0.0.0:8000 Result: 1)curl -v http://127.0.0.1:8000, * Trying 127.0.0.1:8000... * Connected to 127.0.0.1 (127.0.0.1) port 8000 (#0) > GET /login/ HTTP/1.1 > Host: 127.0.0.1:8000 > User-Agent: curl/7.88.1 > Accept: */* > < HTTP/1.1 200 OK < Date: Wed, 22 Mar 2023 11:43:26 GMT < Server: WSGIServer/0.2 CPython/3.9.13 < Content-Type: text/html; charset=utf-8 < X-Frame-Options: DENY < Vary: Cookie < Content-Length: 10761 < X-Content-Type-Options: … -
xmlsec library version mismatch Ubunto 20.04
Currently installed: xmlsec: 1.3.13 lxml:4.9.1 Exception in thread django-main-thread: Traceback (most recent call last): from onelogin.saml2.auth import OneLogin_Saml2_Auth File "/home/vboxuser/Desktop/web/.venv/lib/python3.10/site-packages/onelogin/saml2/auth.py", line 14, in \<module\> import xmlsec xmlsec.Error: (19, 'xmlsec library version mismatch.') I have tried reinstalling the packages but it didn't work. -
How to integrate vuejs in a django project?
we need to create a complete website with django and vue as part of a school project, however, we are having trouble integrating vue into our django project. To keep things simple we want to use vue directly in an index.html file located in a django application in templates/app/index.html thanks to the vue cdn. Without vue, the page content is displayed by django, but when we try to use vue with the cdn in this file, nothing is displayed and we get this error in the chrome console: vue.global.js:1661 [Vue warn]: Component is missing template or render function. here is the code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> <div id="app">{{ message }}</div> <script> const { createApp } = Vue createApp({ data() { return { message: 'Hello Vue!' } } }).mount('#app') </script> </body> </html> when we run the html file directly in chrome (outside of django) everything works, which means the problem comes from djangom. We suspect the problem is that django expects to run django templating code and not vuejs code. Is it possible to use vue js in this way on django and if not, how … -
How to get a dynamic value from a post and use it to get to a specific function in Django
I'm trying to accomplish this. Though this function: my_site/initpage (that renders mysite/initpage.html) I'm proposing a form where I get three values: start_date, end_date and the specific function that computes and render the specific graphic. This function is where we'll land afterwards (for ex. graphic1, graphic2 and so on). So, in the forms.py I put this: class formGraphicChoice(forms.Form): start_date = forms.DateField( widget=NumberInput(attrs={'class': 'form-control','type':'date'}),required=True, label = "Starting Date" ) end_date = forms.DateField( widget=NumberInput(attrs={'class': 'form-control','type':'date'}),required=True, label = "Ending Date" ) selectedGraph = (('graphic1', 'label_1'), ('graphic2', 'label_2'), ('graphic3', 'label_3'), ) Graphfields = forms.ChoiceField(choices=selectedGraph,label = "Choose the graphic") This works just fine. Then, in the mysite/initpage.html, specifically in the {% block content %} part, I placed the following: <form action="form.cleaned_data['Graphfields']" method="post" class="margin-bottom-0" > {% csrf_token %} <br> {{ form | crispy }} <input type="submit" class="btn btn-primary" value="Show it"> </form> Basically, in action="xx" I would like to put the value of the graphicFields field of the form so to call the chosen function, like this example https://my_site/graphic1. This does not work and I don't know how to handle it. At the moment, I get this: https://my_site/form.cleaned_data['Graphfields'] Thanks a lot for your help! -
django model property depended on request.session value
My models have validation_range field. Very complex. For simplicity I will show example - it may looks stupid but this is for explanation only - so don't look at the model itself, please class Person(models.Model): validity_range=DateTimeRangeField(default=(None,None)) class PersonData(models.Model): person = models.ForeignKey(Person, on_delete=models.RESTRICT) first_name = models.CharField(max_length=255) last_name =models.CharField(max_length=255) validity_range=DateTimeRangeField(default=(None,None)) And now Person can have a two names: E.g. Miss Eva Smith born 1.1.1980 gets married 22.03.2022 and becomes Mrs. Eva Novak. (for simplicity I omit time part of validity_range) So datas look like: Person{id:1,validity_range:(1980-01-01,None)} PersonData{id:1,person_id:1,first_name:'Eva',last_name:'Smith',validity_range:[1980-01-01,2022-03-22)} PersonData{id:2,person_id:1,first_name:'Eva',last_name:'Novak',validity_range:[2022-03-22,None)} I preserve context_date in request.session['context_date']. And I will show Eva's full name dependent of request.session['context_date'] def index(request): person = Person.objects.get(pk=1) context ={ 'person' : person, 'context_date' : request.session.get('context_date') } html_template = loader.get_template('index.html') return HttpResponse(html_template.render(context, request)) html: Context_date is: {{ context_date }} At that date Person no {{ person.id }} was called {{ person.person_data.first_name }} {{ person.person_data.last_name }} Of course this is wrong, because person_data is a set not a object. I thought to make a property in model: class Person(models.Model): validity_range=DateTimeRangeField(default=(None,None)) @property def first_name(self, date): try: person_data =PersonData.objects.get(validation_range__contains=date) #We can assume, that validation_ranges don't overlaps (database constraint) return person_data.first_name except PersonData.DoesNotExist: return None #oups - there's no persondata in that date! But how pass parameter … -
Partitioned tables in psql with django
I partitioned a table in Postgres with Django. All was fine, the insertion went good but when I try to make a query the response is just a field from the original table. So my question is: How is right way to make query in partitioned table in Django?