Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why I am getting Session is disconnected error in python socketio?
I am using python socketio with django. Why am i getting this error while getting session of sid? Can somebody help me with this? my server.py sio = socketio.Server(async_mode="eventlet") @sio.event def connect(sid, environ): user = environ.get("HTTP_USER") sio.save_session(sid, {'user': user}) @sio.event def join_game(sid, game_id): sio.enter_room(sid, game_id) error File "/home/ubuntu/Test-Backend/venv/lib/python3.8/site-packages/engineio/middleware.py", line 63, in __call__ return self.engineio_app.handle_request(environ, start_response) File "/home/ubuntu/Test-Backend/venv/lib/python3.8/site-packages/socketio/server.py", line 597, in handle_request return self.eio.handle_request(environ, start_response) File "/home/ubuntu/Test-Backend/venv/lib/python3.8/site-packages/engineio/server.py", line 429, in handle_request socket = self._get_socket(sid) File "/home/ubuntu/Test-Backend/venv/lib/python3.8/site-packages/engineio/server.py", line 638, in _get_socket raise KeyError('Session is disconnected') KeyError: 'Session is disconnected' -
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' Django Rest Framework
I have this function and i want to make an endpoint for updating (adding) points in an answer. Also when someone upvotes an answer i want them to append to voters list. So they cannot upvote again. But i get this weird error with unsupported operand. Do you have any idea why? Model: class Answer(models.Model): answer = models.TextField() created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) question = models.ForeignKey('Question', on_delete=models.PROTECT) number_of_points = models.IntegerField(default=0) moderate_status = models.BooleanField(default=False) addition_done = models.BooleanField(default=False) subtraction_done = models.BooleanField(default=False) voters = models.ManyToManyField('users.CustomUser', default=None, blank=True, related_name='voters') serializer class AddPointsSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('number_of_points', 'addition_done', 'voters',) Viewset class AddPointsAnswer(generics.UpdateAPIView): queryset = Answer.objects.all() serializer_class = AddPointsSerializer def get_queryset(self): return super().get_queryset().filter( id=self.kwargs['pk'] ) def perform_update(self, serializer): addition_done = serializer.validated_data.get('addition_done', False) number_of_points = serializer.validated_data.get('number_of_points',) voters = serializer.validated_data.get('voters',) if not addition_done and self.request.user not in serializer.instance.voters.all(): number_of_points += 1 addition_done = True voters = voters.append(self.request.user) serializer.save(addition_done=addition_done, number_of_points=number_of_points, voters=voters) Error: Internal Server Error: /api/v1/answers/1/addpoints Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, … -
django runserver returns error when i run py manage.py runserver on a project my friends did how can i resolve this issue?
I wanted to open a Django file my friends did and I installed Django MySQL client etc.. but run server doesn't work, it works when I run my own other file so here's the error and SQL code I pip installed MySQL connector As well but it still didn't change anything do you guys have any suggestions to why the run server is encountering this problem? Requirement already satisfied: mysqlclient in c:\users\user\appdata\local\programs\python\python310\lib\site-packages (2.1.0) C:\Users\user>cd documents C:\Users\user\Documents>cd one_art C:\Users\user\Documents\one_art>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 48, … -
Api: Django with Api-Rest and Scrapy [ValueError: signal only works in main thread of the main interpreter]
I'm trying to return a dictionary with an Api, that dictionary is being filled with a Scrapy script from rest_framework.views import APIView from django.shortcuts import HttpResponse from scrapy.crawler import CrawlerProcess from scrapyProject.spiders.spider import ProductoSpider, outputResponse class Prueba(APIView): def post(self, request): dato = request.data['dato'] if dato == 'dato': datos = [] process = CrawlerProcess({ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' }) process.crawl(ProductoSpider) process.start() datos = outputResponse return HttpResponse(datos) else: return HttpResponse("Adios", content_type='application/json') This is just an experiment. "outputResponse" is a global variable in my spider, and I've already checked out that the info is saving correctly with this: from scrapy.crawler import CrawlerProcess from spiders.spider import ProductoSpider, outputResponse def execute(): process = CrawlerProcess({ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' }) process.crawl(ProductoSpider) process.start() return outputResponse print (execute()) This script it does works, but when I want to try the Api doing "POST" in postman I get this: Internal Server Error: /api/experimento Traceback (most recent call last): File "C:\Users\Duvan Requena\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Duvan Requena\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Duvan Requena\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\Duvan Requena\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) … -
How to properly import CSV datasets to Django models with ManyToMany / ForeignKey relationships?
Novice alert! I want to use django-csv-importer 0.1.3.5 to import data to models with ManyToMany relationships. Should make different model for every relation or should I put everything in the same model? Also note that i want to allow registered users on my site to submit a form to that same model, would that still work? -
Django custom user not having password column, which is expected to have been inherited from AbstractBaseUser
I am a beginner trying to learn to program in django. I have begun my first website. All I want as of now is a registration form (and login form) to create accounts and for those accounts to be stored on a database. I have created a custom user class, and not defined any column called 'password'. If I was subclassing models.Model or something, I would expect it to throw a 'no such column' error. However, django's default user class has a password column and I am inheriting from it y subclassing AbstractBaseUser, right? This is my models.py for reference: from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractBaseUser from django.conf import settings from django.utils.translation import gettext as _ import datetime from django_countries.fields import CountryField # Create your models here. class UserProfile(AbstractBaseUser): phone_number = models.CharField(max_length = 16, unique = True, blank = False, null = False) country = CountryField() date_of_birth = models.DateField(max_length = 8, blank = False, null = True) sex = models.PositiveSmallIntegerField(_('sex'), choices = ((1, _('Male')), (2, _('Female')),) ) USERNAME_FIELD = "phone_number" REQUIRED_FIELDS = ['country', 'date_of_birth', 'sex'] Code to my forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import … -
Plot routes from json file with location coordinates when searched using start and end locations
I have a json file as follows with all the route information such as start station, end station and waypoint information. I would like to plot the entire route if one searches the RouteId, start and end stations. So far I have tried Gmaps python in Jupyter which helps to plot the route automatically by taking the coordinates of origin, destination and waypoints as shown below. In order to plot in python, I convert the coordinates in the form of list of tuples. When I select list[0], etc I can plot the route for each RouteId. I want to plot in a similar way in a more interactive way using javascript / Flask / Django. If I search for a RouteId, I need to automatically get the path along with waypoints. How do I do that? [ { "RouteId": 0, "StartStation": "Rhenen", "EndStation": "Uitgeest", "StartLatitude": 51.95861053, "StartLongitude": 5.578333378, "EndLatitude": 52.52166748, "EndLongitude": 4.701666832, "Segments": [ { "WaypointLatitude": 52.02000046, "WaypointLongitude": 5.548611164, "WaypointStation": "Veenendaal Centrum" }, { "WaypointLatitude": 52.0280571, "WaypointLongitude": 5.53138876, "WaypointStation": "Veenendaal West" }, { "WaypointLatitude": 52.06416702, "WaypointLongitude": 5.369999886, "WaypointStation": "Maarn" }, { "WaypointLatitude": 52.0652771, "WaypointLongitude": 5.258611202, "WaypointStation": "Driebergen-Zeist" }, { "WaypointLatitude": 52.29844, "WaypointLongitude": 4.95972, "WaypointStation": "Amsterdam Holendrecht" }, { "WaypointLatitude": 52.31222153, … -
not able to send email while user creation
I'm trying to put send a random 6 digit otp through email .Below code work for django 4.0 but not working in 3.2 , I'm not getting any error but when i createsuperuser in django 4.0 setup email send work but not the case in django 3.2 views.py @receiver(post_save, sender=CustomUser) def send_email_otp(sender, instance, created, **kwargs): if created: try: subject = "Your email needs to be verified to use this site" message = f'Hi, Dear {instance.name} use this following OTP to Get verified your email : OTP({instance.otpForEmail})/' email_from = settings.EMAIL_HOST_USER recipient_list = [instance.email] send_mail(subject, message, email_from, recipient_list) print(f"Email Sent to {instance.email}") except Exception as e: print(e) print("Something Wrong at send_email_otp") signals.py from django.db.models.signals import pre_save from .models import CustomUser def updateUser(sender, instance, **kwargs): user = instance if user.email != '': user.name = user.email pre_save.connect(updateUser, sender=CustomUser) I'm not sure what can be the problem,please help me to identify and fix . -
Problems placing formsets in wizard forms
I have a question regarding a multi form step wizard, in 3 steps I am using form sets that I have previously set up from the views and rendering it in the template. Now I see that when using the wizard you have to make some modifications to the view, it is something that does not know how to mix the view with the wizard and the formset. I already saw how it is used with simple forms but with formset I have not found tutorials that explain it. I imagine that when I make that change I also have to make adjustments to the template? Percent I was checking django-formtools-addons and django-multipleformwizard but I didn't understand the documentation views.py def create_Presupuestos(request): extra_forms = 1 ParteFormSet = formset_factory(PresupuestosParteForm, extra=extra_forms, max_num=20) ManoObraFormSet = formset_factory(PresupuestosManoObraForm, extra=extra_forms, max_num=20) PagosFormSet = formset_factory(PresupuestosPagosForm, extra=extra_forms, max_num=20) presupuestosclientesform=PresupuestosClientesForm(request.POST or None) presupuestosvehiculosform=PresupuestosVehiculosForm(request.POST or None) presupuestosparteform=PresupuestosParteForm(request.POST or None) presupuestosmanoobraform=PresupuestosManoObraForm(request.POST or None) presupuestospagosform=PresupuestosPagosForm(request.POST or None) presupuestosfotosform=PresupuestosFotosForm(request.POST or None) if request.method == 'POST': formset = ParteFormSet(request.POST, request.FILES) manoObra_formset = ManoObraFormSet(request.POST, request.FILES,prefix='manoobra') pagos_formset = PagosFormSet(request.POST, request.FILES, prefix='pagos') #formset = ParteFormSet(request.POST, request.FILES,prefix='__form') if formset.is_valid() and manoObra_formset.is_valid() and pagos_formset.is_valid(): presupuestosclientesform.save() return redirect('presupuestos:index') else: formset = ParteFormSet() manoObra_formset = ManoObraFormSet(prefix='manoobra') pagos_formset = PagosFormSet(prefix='pagos') presupuestosfotosform = … -
I am getting error while installing Herocu with snap
Here is problem. I installed heroku before But i did not recognized herocu commands like heroku login -
How to send push notification request from android app to django
I have created a sip calling app in android (java).. But it is only able to call if app is open.. When app is closed the registration get destroyed.. I want to invoke the registration using push notification when i call.. I have setup the FCM service for sending push notifications. I am sending device token and username to django where django saves the device taken in "subscribers" table .. But I don't know how to send request to send push notification from android app to django... Please help -
Django connect SQL Server using active directory user
I'm using Django and mssql-django backend to connect to SQL Server. No problems to connect to SQL Server when using sql login. But, when I try to connect using AD user, I get exception: django.db.utils.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server] Login failed for user 'DOMAIN\\myuser'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0); [28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'DOMAIN\\myuser'. (18456); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0)") My database settings in settings.py are: DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': os.environ.get('DB_NAME', 'djangodb'), 'USER': os.environ.get('USER', 'DOMAIN\myuser'), 'PASSWORD': os.environ.get('USER_PASS', 'mypass'), 'HOST': os.environ.get('HOST', 'server.blabla.net'), 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } What I am doing wrong? -
Override top bar in Django admin
I'm trying to override admin/base_site.html to display the top nav bar from the main site. I tried using {% block nav-global %} and adding my navbar there, but it just appends to the existing header. How would I delete the top header all together to replace with my own template? {% extends 'admin/base_site.html' %} {% block nav-global %} {% include 'base/navbar.html' %} {% endblock %} I've considered reconstructing the template as my own by not extending the original admin/base_site.html, however, I can't find the blocks I'd need in the docs anywhere. -
How can I set that when user is admin only then he can view a specific html page in Django
I've a html page called admin_dashboard.html. So, there is a button in the navbar called Admin Dashboard only admin can get this button. If admin click this button he will go to the admin_dashboard.html but a staff can also go to that page by using urls which is http://127.0.0.1:8000/admin_dashboard. So I want that a if staff manually types this url and tries to go to the admin_dashboard.html it will throw an error. here is my code for that button {%if user.is_superuser%} <li><a class="dropdown-item" href="admin_dashboard">Admin Dashboard</i></a></li> {%endif%} urls.py: path("admin_dashboard", views.admin_dashboard, name='admin_dashboard') views.py @login_required(login_url='/login') def admin_dashboard(request): return render(request,'admin_dashboard.html') -
Django array field filter
In my case customer filed are array filed customer = ArrayField(models.TextField(),default=[]) my model look like id customer 1 {1,2,3} 2 {4,2,5} 3 {1,8,9} i want to filter my model by {5,8} output will be 2th ,3th row -
Django, DRF: How to correctly divide the number of pages in a homemade pagination that does not issue count queries
I have created a pagination that does not issue a Count query as shown below, but This code uses sys.maxsize, so the number of pages is 461168601842738816, and if the data does not exist, raise NotFound("No data found for this page") is performed. but how do I make next empty on the page before that one? I need to determine whether to load the next page with or without next in the frontend infinite scroll. class CustomPaginatorClass(Paginator): @cached_property def count(self): return sys.maxsize class CustomPagination(PageNumberPagination): django_paginator_class = CustomPaginatorClass def paginate_queryset(self, queryset, request, view=None): page_size = self.get_page_size(request) if not page_size: return None paginator = self.django_paginator_class(queryset, page_size) page_number = int(self.get_page_number(request, paginator)) data = super().paginate_queryset(queryset, request, view=view) if not data and page_number > 1: raise NotFound("No data found for this page") return data def get_paginated_response(self, data): return Response( OrderedDict( [ ("next", self.get_next_link()), ("previous", self.get_previous_link()), ("results", data), ] ) ) -
Pycharm Debug mode with docker
Starting Pycharm debug mode occurs the following error. python: can't open file '/opt/.pycharm_helpers/pydev/pydevd.py': [Errno 2] No such file or directory It was working until this morning. Pycharm pycharm-2021.1.1 -
I can't get username form django I got only None like on the photo
I cna't get user, I got None intend od username, I don't know how to solve this problem... {% for wiadomosc in wiadomosci %} <li> <strong>{{ wiadomosc.author }}</strong> ({{ wiadomosc.created_date }}): <br /> {{ wiadomosc.tekst }} {% if wiadomosc.author.name == user.name %} &bull; <a href="{% url 'blog_app:edytuj' wiadomosc.id %}">Edytuj</a> &bull; <a href="{% url 'blog_app:usun' wiadomosc.id %}">Usuń</a> {% endif %} </li> {% endfor %} website: Wiadomości Lista wiadomości: None (Feb. 4, 2022, 2:11 p.m.): Czwarta wiadomość edytowana • Edytuj • Usuń None (Feb. 4, 2022, 2:54 p.m.): Piąta wiadomość edytowana • Edytuj • Usuń Strona główna models.py from django.contrib.auth.models import User from django.db import models # Create your models here. class Wiadomosc(models.Model): """Klasa reprezentująca wiadomość w systemie""" tekst = models.CharField('treść wiadomości', max_length=250) created_date = models.DateTimeField('data publikacji') author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) class Meta: verbose_name = u'wiadomość' # nazwa obiektu w języku polskim verbose_name_plural = u'wiadomości' # nazwa obiektów w l.m. ordering = ['created_date'] # domyślne porządkowanie danych def __str__(self): return self.tekst -
Could I send serialized data in Django to JSON dataframe chart.js?
below I send example of candlestick charts.js date structure - (JSON type): <script> const data1 = luxon.DateTime.fromRFC2822('15 Dec 2021 00:00 GMT'); const date2 = luxon.DateTime.fromRFC2822('16 Dec 2021 00:00 GMT'); const data = { datasets: [{ data: [ { x: data1.valueOf(), o: 1, h: 0.75, l: 0.75, c: 1.25 }, { x: date2.valueOf(), o: 1.20, h: 1.5, l: 0.75, c: 0.9 } ], }] }; // config const config = { type: 'candlestick', data, options: {} }; // render init block const myChart = new Chart( document.getElementById('myChart'), config ); </script> It seems similar to serializers? So I wonder if it is possible to send it in context to make this json like data And seems... const data = {{data}} doesn't work... :) -
Django SoftDelete Model And Model Manager Inheritance
i have a soft delete model BasicModel and a user model Paddy. the user model's objects isn't inheriting the BasicModel's object manager core app's models.py class BasicModelQuerySet(models.QuerySet): def delete(self): return self.update(is_deleted = True, deleted_at = timezone.now()) def erase(self): return super().delete() class BasicModelManager(models.Manager): def get_queryset(self): return BasicModelQuerySet(self.model, self._db).filter(is_deleted = False) # Base Application Model class BasicModel(models.Model): """ Base application model to add default fields to models without having to write repeated code. """ deleted_at = models.DateTimeField(blank = True, null = True,) is_deleted = models.BooleanField(default = False,) objects = BasicModelManager() class Meta: abstract = True # extras ... accounts app's models.py class PaddyManager(BaseUserManager): def create_user(self, first_name, last_name, email, password, **extra_fields): # user creation ... skipping code pass def create_superuser(self, first_name, last_name, email, password, **extra_fields): # super user creation ... skipping code pass # BasicModel from core.models.py class Paddy(BasicModel, AbstractUser): # model fields objects = PaddyManger() <-- HOW TO MAKE THIS USE BasicModel's Model Managers AND STILL USE CREATE_USER / CREATE_SUPERUSER METHODS OF PaddyManager() #extras my challenge is how do i get the user model to only return non-deleted objects when i call User.objects.all() and still be able to call the create_user or create_superuser methods of PaddyManager? -
How to get Django Whitenoise to 500 when Debug is True
I'm trying to get our Django app to throw 500s when an asset is not available - rather than somewhat silently throwing 404s. We want this so that our end-to-end tests catch an asset missing before it goes to prod and starts failing. I have WHITENOISE_MANIFEST_STRICT set to True, and I believe that Whitenoise is working - I'm using the --nostatic flag, and see the WHITENOISE_MAX_AGE in the Cache-Control Response Headers (although the assets themselves don't have the hash that we see in production or when Debug is set to false). However I'm still getting 404s for an asset that doesn't exist. Unfortunately we can't use DEBUG = False because the tests themselves depend on Debug being true, so any advice would be super appreciated! -
how to extract actual youtube videos urls through api like below links
i am try to fetch the actual URL of each video from you-tube channel. please help me any one. https://jsoncompare.org/LearningContainer/SampleFiles/Video/MP4/Sample-MP4-Video-File-Download.mp4 https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3 -
Django rest framework Adding Points Put Request
I wanna create an API PUT endpoint that adds/subtracts point to an answer (just like on forums) but i want to limit it so that if user has upvoted, he cant upvote twice. I tried doing something like this logically, but i keep getting an error with voters. I think its because of ManyToMany field, but i dont know why it happens. Do you have any idea why is that? class Answer(models.Model): answer = models.TextField() created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) question = models.ForeignKey('Question', on_delete=models.PROTECT) number_of_points = models.IntegerField(default=0) moderate_status = models.BooleanField(default=False) addition_done = models.BooleanField(default=False) subtraction_done = models.BooleanField(default=False) voters = models.ManyToManyField('users.CustomUser', default=None, blank=True, related_name='voters') Views class AddPointsAnswer(generics.UpdateAPIView): queryset = Answer.objects.all() serializer_class = AddPointsSerializer def get_queryset(self): return super().get_queryset().filter( id=self.kwargs['pk'] ) def perform_update(self, serializer): addition_done = serializer.data.get('addition_done', False) number_of_points = serializer.data.get('number_of_points',) voters = serializer.data.get('voters',) if not addition_done and self.request.user not in serializer.voters.all(): number_of_points += 1 addition_done = True voters.all = self.request.user serializer.save(addition_done=addition_done, number_of_points=number_of_points, voters=self.request.user) serializer class AddPointsSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('number_of_points', 'addition_done', 'voters',) i keep getting the AttributeError: 'AddPointsSerializer' object has no attribute 'voters' -
django html: click form button in sequence
I have a form for user to fill in some data. at the bottom there are two buttons: "Get Price" and "Order Now". the user must click "Get Price" button in the first to get the price, then click "Order Now" button to redirect to a new page. However, we cannot control user behavior, some will directly click the "Order Now" button. So for "Order Now" button configuration, is there a way to enable sequential clicks ("Get Price" -> "Order Now"), i.e. when user click "Order Now" button, the program will click "Get Price" button first, then "Order Now". <form method="POST" hx-post="{% url 'OnlinePricing' %}" hx-target="#pickup_address" hx-target="#delivery_address" hx-target="#distance" hx-target="#charge" @submit.prevent> {% csrf_token %} <div> <label for="s1">pickup_address:</label> <input type="text" name="pickup_address" value="" required="required" /> <br /><br /> </div> <div> <label for='s1'>delivery_address:</label> <input type="text" name="delivery_address" value="" required="required" /> <br /><br /> </div> ... <div> <span id="pickup_address"> {{ pickup_address }} </span> </div> <div> <span id="delivery_address"> {{ delivery_address }} </span> </div> <div> <span id="distance"> {{ distance }} </span> </div> <div> <span id="charge" > {{ charge }} </span> </div> <button type="submit">Get Price</button> <button type="submit" style="margin-left:10px;" onclick="location.href = '/order/'">Order Now</button> </form> -
Why after deploying Django application on Elastic Beanstalk my website doesn't work?
After deploying my application to Elastic Beanstalk, the website doesn't work as expected. I don't know why. This is the database configuration: enter image description here This is the website: enter image description here