Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to detect change in HTML page after a successful redirect from form?
views.py class ChangePasswordView(PasswordChangeView): form_class = ChangePasswordForm success_url = reverse_lazy("login") login.html {% if XXXXXX %} <p style="color:green;">Password changed successfully! Please login.</p> {% endif %} Basically I want the following message to appear on my login html page if password was changed. Is there a way to detect if form was successful (by passing some parameter to HTML), or if user was redirected from certain URL to current html page? -
No module named 'gotya.views', django/python
**Even if I have written down gotya.views inside of my url file, it does not recognized by the docker. I can run it in my local and its too strange. What am I doing wrong? ** Code: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static #Static function helps us to publish media files at prod creating url pattern from django.conf import settings from gotya.views import homepage, communicate urlpatterns = [ path('admin/', admin.site.urls), path('account/', include('account.urls')), path('', include('gotya.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Result: Exception in thread django-main-thread:gotya | Traceback (most recent call last):gotya | File "/usr/local/lib/python3.11/threading.py", line 1038, in _bootstrap_innergotya | self.run()gotya | File "/usr/local/lib/python3.11/site-packages/sentry_sdk/integrations/threading.py", line 69, in rungotya | reraise(*_capture_exception())gotya | File "/usr/local/lib/python3.11/site-packages/sentry_sdk/_compat.py", line 57, in reraisegotya | raise valuegotya | File "/usr/local/lib/python3.11/site-packages/sentry_sdk/integrations/threading.py", line 67, in rungotya | return old_run_func(self, *a, **kw)gotya | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^gotya | File "/usr/local/lib/python3.11/threading.py", line 975, in rungotya | self._target(*self._args, **self._kwargs)gotya | File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrappergotya | fn(*args, **kwargs)gotya | File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 134, in inner_rungotya | self.check(display_num_errors=True)gotya | File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 475, in checkgotya | all_issues = checks.run_checks(gotya | ^^^^^^^^^^^^^^^^^^gotya | File "/usr/local/lib/python3.11/site-packages/django/core/checks/registry.py", line 88, in run_checksgotya | new_errors = check(app_configs=app_configs, databases=databases)gotya | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^gotya | File "/usr/local/lib/python3.11/site-packages/django/core/checks/urls.py", line 14, in … -
How to order a django query after a distinct operation
I have the following code: # Gets the most recent post from each user # However, the returned set is not ordered by created_on queryset = Post.objects.all().order_by('author', '-created_on').distinct('author') Trying to, for example, tack another order_by onto the end of the query, or changing the current order_by parameters, results in this error: SELECT DISTINCT ON expressions must match initial ORDER BY expressions Is there a way to accomplish my goal here (a list of each user's most recent post, ordered from newest to oldest)? -
django rest framework I want to return in response all the models that have relation to user model as a user login
I want to show all the related to user model field as the user logins in response in a apiview. Views .py code class UserLoginView(APIView): renderer_classes = [UserRenderer] def post(self, request, format=None): serializer = UserLoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.data.get('email') password = serializer.data.get('password') user = authenticate(email=email, password=password) if user is not None: if Profile.objects.filter(user=user).first().is_verified: token = get_tokens_for_user(user) # profile = user.profile.all() # pbys = user.propertiesbystreet.all() # pbyb = user.propertiesbyblocks.all() return Response({'msg': 'Login Success', 'data': serializer.data, 'token': token}, status=status.HTTP_200_OK) else: return Response({'msg': 'Account is not verified'}, status=status.HTTP_404_NOT_FOUND) else: return Response({'errors': {'non_field_errors': ['Email or Password is not Valid']}}, status=status.HTTP_404_NOT_FOUND) Serializers class from serializer.py class UserLoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(max_length=255) userdata = UserDetailsSerializers(read_only=True) class Meta: model = User fields = ['email', 'password', 'userdata'] -
POST method doesn't return output
I'm an absolut beginner in Django, so my problem is probably very basic, but I am currently stuck and I would appreciate any help. I'm trying to create a form where the user can write a text that will be then simply printed out on the webpage. Here is my html file template Here is my views.py views.py Here is my forms.py forms.py Here is my urls.py urls.py. I don't get any errors, but the output doesn't appear on my webpage. I think the function get_translation doesn't work, but I can't figure out why. Thank you for having a look! -
Django / SimpleTestCase / How Mocking the connection with database works?
I am trying to understand how the test/mocking procedure works inside Django (connection to Postgresql) Here is my project structure : wait_for_db.py import time from psycopg2 import OperationalError as Psycopg20pError from django.db.utils import OperationalError from django.core.management.base import BaseCommand class Command(BaseCommand): """Django command to wait for the database""" def handle(self, *args, **options): """ Entry point for command""" self.stdout.write("waiting for database") db_up = False while db_up is False: try: self.check(databases=['default']) db_up = True except (Psycopg20pError, OperationalError): self.stdout.write("database unavailable, waiting 1 seconds") time.sleep(1) self.stdout.write(self.style.SUCCESS("Database available!")) test_commands.py from unittest.mock import patch from psycopg2 import OperationalError as Psycopg2Error from django.core.management import call_command from django.db.utils import OperationalError from django.test import SimpleTestCase @patch("core.management.commands.wait_for_db.Command.check") class CommandTests(SimpleTestCase): def test_wait_for_db_ready(self, patched_check): """ Test waiting for the database to be ready. """ patched_check.return_value = True call_command("wait_for_db") patched_check.assert_called_once_with(databases=['default']) # AssertionError: Expected 'check' to be called once. Called 0 times. @patch('time.sleep') def test_wait_for_db_delay(self, patched_sleep, patched_check): ''' Test that waiting for db when getting operationalError the first two times we call the mock method to raise Psycopg2Error then we raise three times the operationalError ''' patched_check.side_effect = [Psycopg2Error] * 2 + \ [OperationalError] * 3 + [True] call_command("wait_for_db") self.assertEqual(patched_check.call_count, 6) patched_check.assert_called_with(databases=['default']) Indeed this commands docker-compose run --rm app sh -c "python manage.py test" gives … -
How to setup Django channels on GCP App Engine?
I have a Django application that uses the channels package for WebSocket. I'm using the daphne interface server to run the app on the Google Cloud App Engine Flex environment, but the backend service is not able to serve concurrent requests. Is there anyone who faced similar problems before? -
Django: Move migration file to another application
With the help of "contribute_to_class" function of django model Field, I added one extra field in django.contrib.auth.Permission model. This is given below: if not hasattr(Permission, 'module'): module = models.ForeignKey( MModule, on_delete=models.CASCADE, related_name='permissions', default=None, blank=True, null=True ) module.contribute_to_class(Permission, 'module') Everything works fine! The migration file created and migration works perfect. But the problem is that, migration file created at, lib/python3.10/site-packages/django/contrib/auth/migrations/ can I move this migration file into some other applications I am having (instead of keeping it inside system library) ? The migration file created is given below: # Generated by Django 4.1.3 on 2022-12-25 18:16 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('roles_permissions', '0002_mmodule_parent_module'), ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.AddField( model_name='permission', name='module', field=models.ForeignKey( blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='permissions', to='roles_permissions.mmodule' ), ), ] can I move this migration file into some other applications I am having ? -
Type error when accessing Django request.POST
I'm attempting to build an XML document out of request.POST data in a Django app: ElementTree.Element("occasion", text=request.POST["occasion"]) PyCharm is giving me an error on the text parameter saying Expected type 'str', got 'Type[QueryDict]' instead. I only bring up PyCharm because I know its type checker can be overzealous sometimes. However, I haven't been able to find anything about this issue specifically. Am I doing something wrong? Or should I try to silence this error? -
Update Page and Value using JQuery / Ajax in Django
I am using Django Where I want to update page and it's value without reloading the page. I am getting the value from my database and I want to post this value in my template page and also I want to update my html page without reloading it again and again. Here I am sharing my details: views.py: def process(request): hash_id = request.session.get('hash_id') print(hash_id) check = request.session.pop('check_status',) if hash_id and check: stat = status_mod.objects.filter(hash_id = hash_id).order_by('-id').first() if stat: stat = stat.stat_id print(stat) return render(request, 'enroll/status.html', {'status': stat}) models.py: class status_mod(models.Model): id = models.BigIntegerField(primary_key=True) stat_id = models.BigIntegerField() hash = models.ForeignKey(hash, on_delete=models.CASCADE, blank=True, null=True, related_name="hash_status") class Meta: db_table = "****" urls.py: path('status', views.process, name='process') status.html: <td> <form action = "/modules" method="get"> {% if status == 1 %} {% csrf_token %} <button link="submit" class="btn btn-default btn-sm"> <span class="badge badge-dot mr-4"> <i class="bg-success"></i>Completed</button> </form> {% else %} <button type="button" class="btn btn-default btn-sm"> <span class="badge badge-dot mr-4"> <i class="bg-warning"></i>Running</button> {% endif %} </td> jquery / ajax in status.html page: <script> $(document).ready(function() { setInterval(function() { $.ajax({ type: 'GET', url: "{% url 'process' %}", success: function(response){ console.log(response) }, error: function(response){ alert("NO DATA FOUND") } }); }, 2500); }); </script> Here I want that when Status value will … -
Django Channels 4.0.0 + Docker Redis stops sending messages after some time
I am using Django 4.1.3 + Channels 4.0.0 and Docker with Redis 5 in it. It runs on Daphne 4.0.0. Also I have frontend written on React that uses reconnecting websocket for making undead connection to server. But after some time (I can’t say for sure, but about 1 - 2 days) frontend stops recieving messages from Channels. Restarting Redis container fixes this issue as 1 - 2 days as I said. Here is the docker-compose.yml: services: ... redis: image: redis ports: - "6379:6379" container_name: redis restart: always command: redis-server --appendonly yes --replica-read-only no Any thoughts what it could be and and how to fix it? Ps. thank for your time -
How to create base context for class based views Django?
I have multiple class based views that require the same context. How can I create a 'base' context that applies to all the class based views, so that I don't need to repeat the same code over and over again in every class based view? It is maybe possible to create a context class and use that in the get_context function of all the class based views? class ManagerSignUpView(CreateView): model = User form_class = ManagerSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) if self.request.user.is_authenticated: if Student.objects.filter(user=self.request.user).exists(): # if a Student with the request username exists user = User.objects.get(username=self.request.user) student = Student.objects.get(user=user) context['name'] = f'{student.first_name} {student.last_name}' if user.is_student: context['user_type'] = 'Student' elif Teacher.objects.filter(user=self.request.user).exists(): # if a Teacher with the request username exists user = User.objects.get(username=self.request.user) teacher = Teacher.objects.get(user=user) context['name'] = f'{teacher.first_name} {teacher.last_name}' if user.is_teacher: context['user_type'] = 'Teacher' elif user.is_manager: context['user_type'] = 'Manager' elif user.is_superuser: context['user_type'] = 'Admin' context['user_type_to_create'] = 'manager' return context def form_valid(self, form): first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') location = form.cleaned_data.get('location') user = form.save( first_name=first_name, last_name=last_name, location=location, ) return redirect('home') class AdminSignUpView(CreateView): model = User form_class = AdminSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) if self.request.user.is_authenticated: if Student.objects.filter(user=self.request.user).exists(): # … -
How do I avoid overwrite in django models
I have class called AlbumImage class AlbumImage(models.Model): album = models.ForeignKey(Album, on_delete=models.PROTECT,related_name="raters") image = models.ImageField(upload_to="Album") when i upload first image called (for example) image1.png every thing in ok ,,,, But if I upload another image with the same name(image1.png), and go back to the first object, I will find the second image in its place. How do I avoid overwrite ? -
Create super user in Django with email instead of username
This is the first time that I ask something... So I'll try to be precise. I am building a django app for my final project, and I have encountered some trouble with the authentication system. What I'm trying to do is create a superuser with the command: python manage.py createsuperuser But I want to use the email adress, instead of the username field. For this reason, I wrote the following code: My CustomUser: class CustomUser(AbstractUser): username = models.CharField(max_length=50, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] creation_date = models.DateTimeField(auto_now_add=True) modification_date = models.DateTimeField(auto_now=True) name = models.CharField(max_length=50, blank=False, null=False) last_name = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(unique=True) date_of_birth = models.DateField(blank=False, null=False) nif = models.CharField(max_length=9, blank=False, null=False) sex = models.CharField(max_length=1, choices=SEX_CHOICES) phone = models.CharField(max_length=15, blank=True, null=True) mobile = models.CharField(max_length=15, blank=True, null=True) specialty = models.CharField(max_length=30, choices=SPECIALTY_CHOICES) license_number = models.CharField(max_length=50) def __str__(self): string = 'Name: ' + self.name + ' ' + self.last_name + ', email: ' + self.email return string def has_role(self, center, role): try: center_role = CenterRole.objects.get(user=self, center=center, role=role) return True except CenterRole.DoesNotExist: return False And I also created a CustomUserManager (I thought that, by doing that, I wouldn't encounter any more problems): class CustomUserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): … -
Resizing image with passed parameters using Django Rest Framework raises AttributeError: _committed
I need to resize an uploaded image before saving it. Here's my model from django.db import models def upload_to(instance, filename): return f'images/{filename}' class Image(models.Model): title = models.CharField(max_length=64) url = models.ImageField(upload_to=upload_to, width_field='width', height_field='height') width = models.PositiveIntegerField(null=True, blank=True) height = models.PositiveIntegerField(null=True, blank=True) here's serializer class ImageSerializer(ModelSerializer): class Meta: model = Image fields = '__all__' def create(self, validated_data): if validated_data.get('height') and validated_data.get('width'): resized_image = resize_image( image=validated_data.pop('url'), width=validated_data.pop('width'), height=validated_data.pop('height') ) image = Image.objects.create(url=resized_image, **validated_data) else: image = Image.objects.create(**validated_data) return image and the resize_image function from PIL import Image def resize_image(image, width, height): img = Image.open(image) img = img.resize((width, height), Image.ANTIALIAS) return img I totally don't get what could be a reason of raising AttributeError: _committed by this code. -
How to show content only to user that created it?
I have program like todo list. And I need to filter db to show only content that user created I have code like this: name = Gift.objects.filter(author=request.user) But it show error Cannot resolve keyword 'author' into field. Choices are: gift_name, id, person_name, user, user_id -
How can one html form input field update two Django models?
I have two models, Region and Room. One room can only be in one region but one region can have many rooms. When the user is creating a room (createRoom view), I want them to enter a region, which should both update the Region model and also assign this Region to the room. models.py class Region(models.Model): region = models.CharField(max_length=200, unique=True) etc.... class Room(models.Model): region = models.ForeignKey(Region, on_delete=models.SET_NULL, null=True) etc.... forms.py class RoomForm(ModelForm): class Meta: model = Room fields = ['region', etc....] class RegionForm(ModelForm): class Meta: model=Region fields = ['country', 'region'] views.py def createRoom(request): form_room = RoomForm() form_region = RegionForm() if request.method == 'POST': form_room = RoomForm(request.POST) form_region = RegionForm(request.POST) if form_room.is_valid() and form_region.is_valid(): room = form_room.save(commit=False) region = form_region.save(commit=False) room.region = region.region room.save() region.save() return redirect ('home') template.html <form class="form" action="" method="POST"> {% csrf_token %} {{form_room.media}} <div class="form__group"> <label for="region_name">Region</label> {{form_region.region}} </div> </form> The line room.region = region.region in views.py I was hoping would set the region object of the Region model as the region object of the Room model. I receive no errors when submitting the form. However the Room model's region object stays empty. -
Install gdal geodjango on elastic beanstalk
what are the correct steps to install geodjango on elastic beanstalk? got eb instance, installed env and made it two instances now I want to use geodjango on it, I'm already using it on a separate ec2 instance for testing that's my django.config file and it fails option_settings: aws:elasticbeanstalk:container:python: WSGIPath: hike.project.wsgi:application commands: 01_gdal: command: "wget http://download.osgeo.org/gdal/2.1.3/gdal-2.1.3.tar.gz && tar -xzf gdal-2.1.3.tar.gz && cd gdal-2.1.3 && ./configure && make && make install" then tried this instead and also failed from 100% cpu and time limit option_settings: aws:elasticbeanstalk:container:python: WSGIPath: hike.project.wsgi:application commands: 01_install_gdal: test: "[ ! -d /usr/local/gdal ]" command: "/tmp/gdal_install.sh" files: "/tmp/gdal_install.sh": mode: "000755" owner: root group: root content: | #!/usr/bin/env bash sudo yum-config-manager --enable epel sudo yum -y install make automake gcc gcc-c++ libcurl-devel proj-devel geos-devel # Geos cd / sudo mkdir -p /usr/local/geos cd usr/local/geos/geos-3.7.2 sudo wget geos-3.7.2.tar.bz2 http://download.osgeo.org/geos/geos-3.7.2.tar.bz2 sudo tar -xvf geos-3.7.2.tar.bz2 cd geos-3.7.2 sudo ./configure sudo make sudo make install sudo ldconfig # Proj4 cd / sudo mkdir -p /usr/local/proj cd usr/local/proj sudo wget -O proj-5.2.0.tar.gz http://download.osgeo.org/proj/proj-5.2.0.tar.gz sudo wget -O proj-datumgrid-1.8.tar.gz http://download.osgeo.org/proj/proj-datumgrid-1.8.tar.gz sudo tar xvf proj-5.2.0.tar.gz sudo tar xvf proj-datumgrid-1.8.tar.gz cd proj-5.2.0 sudo ./configure sudo make sudo make install sudo ldconfig # GDAL cd / sudo mkdir -p /usr/local/gdal … -
unsupported operand type in django project
I am working on a django project where i am going to create a tranfer money process. but when im doing this, i am getting following error unsupported operand type(s) for -=: 'int' and 'str' views here. from django.shortcuts import render,redirect from .models import * # Create your views here. def Moneytransfer(request): if request.method == 'POST': try: user= request.POST.get('user') user_two= request.POST.get('user_two') balance= request.POST.get('balance') #print(phone) user_obj= TransferMoney.objects.get(user=user) user_obj.balance -= balance user_obj.save() user_two_obj= TransferMoney.objects.get(user=user_two) user_two_obj.balance += balance user_obj.save() except Exception as e: print(e) return redirect('/') return render(request, 'transaction/transfermoney.html') models.py class TransferMoney(models.Model): user= models.CharField(max_length=50) phone= models.CharField(max_length=20, unique=True,default=None) balance= models.IntegerField(default=0) def __str__(self) -> str: return self.user -
How to make Model.clean work before saving?
I'm a beginner in Django and I'm trying to make a quiz app. I need to have a validation for admin panel so at least one answer was correct and at least one answer was wrong. I override a clean() method, it works incorrectly. For example - I make all answers incorrect - saving is okay, than I want to change it back - it raises an error 'There should be at least one correct answer'). My models: from django.core.exceptions import ValidationError from django.db import models class Quiz(models.Model): name = models.CharField(max_length=100) image = models.ImageField(blank=True, null=True, upload_to='images/quiz/') class Meta: verbose_name_plural = 'Quizzes' def __str__(self): return self.name class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions') question = models.CharField(max_length=255) def __str__(self): return self.question def clean(self): correct_answers = Answer.objects.filter(question=self).filter(is_correct=True).count() if correct_answers == 0: raise ValidationError('There should be at least one correct answer') elif self.answers.count() == correct_answers: raise ValidationError('There should be at least one wrong answer') class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') answer = models.CharField(max_length=255) is_correct = models.BooleanField() def __str__(self): return self.answer It seems like the clean method works before save method with the original data and doesn't check new data which I'm trying to save. I tried to override the save() method with self.clean() … -
serve django staticfiles with nginx
i have django back-end and reactjs front-end. i want to load static files of django back-end with nginx but he can't find anything . gunicorn can find django pages but can't load staticfiles so i want nginx to serve django page and staticfiles. this is my settings.py : STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, '/static') docker-compose : version: "3.9" services: backend: build: context: ./backend ports: - "8000:8000" entrypoint: ./entrypoint.sh # command: gunicorn server.wsgi:application --bind 0.0.0.0:8000 volumes: - static:/static nginx: build: context: . dockerfile: ./webserver/Dockerfile restart: always ports: - "80:80" volumes: - static:/static depends_on: - backend volumes: static: and this is my default.conf : upstream api { server backend:8000; } server { listen 80; server_name myapp.loc; root /usr/share/nginx/html/frontend1; location / { try_files $uri /index.html; } location /admin/ { proxy_pass http://api; } location /static/ { alias /static/; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } } server { listen 80; server_name newapp.loc; root /usr/share/nginx/html/frontend2; location / { try_files $uri /index.html; } location /admin/ { proxy_pass http://api; } location /static/ { alias /static/; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } } -
Django forms: MultipleChoiceField set active options on init
I'm building a custom form using ul and li items for selecting options and I have a problem that is based on a logic I have in my forms. So I have some models in which I create my product attributes and a separate model which has those attributes values. So this is how I create my form class PropertyAttributeForm(FormSpamDetect, forms.Form): adg = HoneypotField() def __init__(self, *args, **kwargs): super(PropertyAttributeForm, self).__init__(*args, **kwargs) # TODO add cache # Get custom attribute fields for attribute in PropertyAttribute.objects.filter(is_active=True): # TODO: add more types if attribute.type == PropertyAttribute.STRING: if choices := attribute.value_choices.all(): choices_tuple = ((choice.value_slugified, choice.value) for choice in choices) self.fields[attribute.slugified_name] = forms.MultipleChoiceField() self.fields[attribute.slugified_name].choices = choices_tuple self.fields[attribute.slugified_name].required = False self.fields[attribute.slugified_name].widget.attrs.update({"class": "hidden"}) def save(self, commit=True): if self.is_valid(): try: property = Property.objects.last() # TODO pass pk from session property.attrs = json.dumps(self.cleaned_data) property.save() except Property.DoesNotExist: return And this is my form in template: <form id="property-ajax-form" class="grid gap-12 mt-10 grid-flow-row grid-cols-1"> {{ form.adg }} {% for field in form.attribute_fields %} <div class="text-lg text-center"> <span class="text-left text-2xl font-medium text-primary">{{ attr_name_by_slugified_name[field]|safe }}</span> {{ form[field] }} <ul id="{{ field }}-options" class="grid grid-flow-row grid-cols-4 mt-5 gap-5 w-3/5 mx-auto"> {% for attribute in form[field] %} <li data-type="{{ attribute.data.value }}" class="flex flex-col m-auto items-center justify-center … -
Apex chart not changing colors when using candlestick chart
I am using apex charts to develop charts for the stock market and in the backend I use Django. I have a problem with changing the colors of candlesticks. I have multiple stocks with years of data and on some stocks, chart colors are correctly displayed but on most of them, they are displayed incorrectly. I have no idea what is causing this and how to fix this. Any idea? Chart code: <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script> <div id="chart"> </div> <script> var options = { series: [{ name: 'OHLC', type: 'candlestick', data: [ {% for stock in stocks %} { x: "{{stock.date}}", y: ["{{stock.open|floatformat}}", "{{stock.high|floatformat}}", "{{stock.low|floatformat}}", "{{stock.price|floatformat}}"], }, {% endfor %} ] }, ], chart: { id: 'chart_1', group: 'social', type: 'candlestick', height: 900 }, title: { text: '{{ticker}} Stock ', align: 'center' }, yaxis: { tooltip: { enabled: true } } }; var chart = new ApexCharts(document.querySelector("#chart"), options); chart.render(); </script> With this part of django template: {% for stock in stocks %} { x: "{{stock.date}}", y: ["{{stock.open|floatformat}}", "{{stock.high|floatformat}}", "{{stock.low|floatformat}}", "{{stock.price|floatformat}}"], }, {% endfor %} I am looping through a list of data that I have in the backend filtered from the database. This is how chart looks like with incorrect colors: Data … -
How do I integrate my Django Project with an existing Vue3 template that I purchased?
I recently purchased a template from themeforest and they are using vue3 , I want to use the existing code and the design elements in my production ready Django project but I don't have any idea on how to do so. I want to add the templates in my existing project and use those elements. After reading this article , I am just able to load all of the code to the the django local host , but I am not able to specifically use only some parts of the html. I have set up static files. -
I want to migrate spring security sha256 (80byte) to Django
I want to migrate spring security sha256 (80byte) to django. import org.springframework.security.crypto.password.PasswordEncoder; passwordEncoder.encode("Mypassword"); **Security config** encoders.put("sha256", new org.springframework.security.crypto.password.StandardPasswordEncoder()); I did a hash of sha256 password through spring security. However, it is 80 bytes, not 64 bytes. **Result value: {sha256}80byte** I think it's made by adding a random salt value. But if it's a random salt value, how can I compare the values? **It should be implemented the same way in Python Django.** I don't know how to implement it. The method of adding a random salt value or **I'm going to show you how to do it in Python Django Please give it to me!** First of all, I don't understand the salt value. The password entered by the user and the password stored in the database should be compared, but how can it be processed if it is a random salt value?