Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
GET Error takes from 2 to 3 positional arguments but 12 were given in Djnago Rest Framework
Hi Everyone i am trying to create api using raw sql query, but when i hit url get getting error please help me out. as per me issue in dates parameter where i am using 7 days but something gets wrong, thats why getting error, i didn't know how to solve this, please help me. views.py # this is views file where i have executing my query. class CardailyReportViewset(viewsets.ModelViewSet): queryset=Car_dash_daily.objects.all() serializer_class=CarDashdailySerializer def retrieve(self, request, *args, **kwargs): params= kwargs params_list=params['pk'].split(',') dates=params_list[0] team_id=params_list[1] start_date=params_list[2] end_date=params_list[3] car_report= connection.cursor() car_report.execute(''' SELECT temp2.car_number,sum(temp2.trips)as total_trips, temp2.status, case when sum(temp2.day1_trips)=-10 then 'BD' when sum(temp2.day1_trips)=-20 then 'ND' when sum(temp2.day1_trips)=-30 then 'R' when sum(temp2.day1_trips)=-40 then 'I' when sum(temp2.day1_trips)=-50 then 'P' else sum(temp2.day1_trips) end AS day1_trips, case when sum(temp2.day2_trips)=-10 then 'BD' when sum(temp2.day2_trips)=-20 then 'ND' when sum(temp2.day2_trips)=-30 then 'R' when sum(temp2.day2_trips)=-40 then 'I' when sum(temp2.day2_trips)=-50 then 'P' else sum(temp2.day2_trips) end AS day2_trips, case when sum(temp2.day3_trips)=-10 then 'BD' when sum(temp2.day3_trips)=-20 then 'ND' when sum(temp2.day3_trips)=-30 then 'R' when sum(temp2.day3_trips)=-40 then 'I' when sum(temp2.day3_trips)=-50 then 'P' else sum(temp2.day3_trips) end AS day3_trips, case when sum(temp2.day4_trips)=-10 then 'BD' when sum(temp2.day4_trips)=-20 then 'ND' when sum(temp2.day4_trips)=-30 then 'R' when sum(temp2.day4_trips)=-40 then 'I' when sum(temp2.day4_trips)=-50 then 'P' else sum(temp2.day4_trips) end AS day4_trips, case when sum(temp2.day5_trips)=-10 then 'BD' when … -
ModuleNotFoundError: No module named 'scanner.wsgi'
2022-05-04T03:48:55.987895+00:00 app[web.1]: File "", line 1027, in _find_and_load 2022-05-04T03:48:55.987896+00:00 app[web.1]: File "", line 1004, in _find_and_load_unlocked 2022-05-04T03:48:55.987896+00:00 app[web.1]: ModuleNotFoundError: No module named 'scanner.wsgi' 2022-05-04T03:48:55.988039+00:00 app[web.1]: [2022-05-04 03:48:55 +0000] [9] [INFO] Worker exiting (pid: 9) 2022-05-04T03:48:56.025390+00:00 app[web.1]: [2022-05-04 03:48:56 +0000] [4] [INFO] Shutting down: Master 2022-05-04T03:48:56.025449+00:00 app[web.1]: [2022-05-04 03:48:56 +0000] [4] [INFO] Reason: Worker failed to boot. 2022-05-04T03:48:56.211911+00:00 heroku[web.1]: Process exited with status 3 2022-05-04T03:48:56.415253+00:00 heroku[web.1]: State changed from starting to crashed 2022-05-04T07:19:55.297563+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=eth-scan.herokuapp.com request_id=ebd93840-9d54-4797-ac0c-b095b1c69601 fwd="102.89.33.169" dyno= connect= service= status=503 bytes= protocol=https 2022-05-04T07:19:55.695154+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=eth-scan.herokuapp.com request_id=7a30fa28-053b-46f6-ab2e-3e3d9216c040 fwd="102.89.33.169" dyno= connect= service= status=503 bytes= protocol=https -
Django and Javascript Uploading Images with Progress Bar
Good day, I am trying to upload multiple images in django with a progress bar. Currently, I have a working solution for only one image but now I want to add more fields and I need to show progress bar for all the images I am uploading. Below is my working code and the commented out code in the forms.py are the new fields I want to add. models.py class ProductImage(models.Model): product = models.OneToOneField(Product, on_delete=models.CASCADE, null=True, blank=True) main_image = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_one = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_two = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_three = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_four = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_five = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) forms.py class StoreDashboardProductUpdateForm(forms.ModelForm): class Meta: model = ProductImage fields = [ "main_image", # "img_one", # "img_two", # "img_three", # "img_four", # "img_five" ] views.py def store_dashboard_product_update_view(request, slug, product_slug, pk): product = get_object_or_404(Product, pk=pk) form = StoreDashboardProductUpdateForm(request.POST or None, request.FILES or None) if request.is_ajax(): if form.is_valid(): form.instance.product = product form.save() return JsonResponse({'message': 'hell yeah'}) context = { 'form': form, "object": product } return render(request, 'store/dashboard/product_update.html', context) product_update.html {% extends 'store/dashboard/base/products-second.html' %} {% load crispy_forms_tags %} {% load widget_tweaks %} {% block content %} <style> .not-visible { display: none; … -
Django user check_password returns False in tests
I've customized my User manager created create_user and create_superuser method and it's working fine but when I run test on it it fails because of user.check_password() it returns False. I found this post according to it Django unable to identify the correct hasher. This is my UserManager class class UserManager(BaseUserManager): def create_user(self, email, passowrd=None, **extra_fields): '''Creates and saves a new user''' phone = extra_fields.get('phone') if not email: raise ValueError("User must have an email address") if not phone: raise ValueError("User must have a phone number") user = self.model(email=self.normalize_email(email), **extra_fields) user.phone = phone user.set_password(passowrd) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): '''Creates and saves a new superuser''' user = self.create_user(email, password, **extra_fields) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user and this my test method for testing user creation def test_create_user_with_email_and_phone(self): '''Test creating new user with an email and phone successfuly''' email = 'demo@gmail.com' password = 'demo@1234' phone = 1234567890 user = get_user_model().objects.create_user( email=email, password=password, phone=phone ) self.assertEqual(user.email, email) self.assertEqual(user.phone, phone) print(f'\n User Password : {user.password} \n') print(f'\n Check Password : {user.check_password(password)} \n') self.assertTrue(user.check_password(password)) this is output of print() function User Password : !dAqIjSVT6hpEhKj4JEjLLDAB3hAJt042Zaj8JS8R Check Password : False -
Django channel group_send all messages to one channel in the group
I am trying to make a real time chat web app with Django channel. When I am trying using Postman build multiple WS connections with it. I encountered some weird thing, let's say I have 2 connections to the same server at 8000 port. Then I send a message via group_send, ideally each connection will get 1 message, but it turn out 2 messages are send to the newer connection. Here is my consumer: class RealtimeConsumer(AsyncJsonWebsocketConsumer): async def websocket_connect(self, event): user_id = self.scope['user'] await self.channel_layer.group_add( str(user_id), # use id as the group name self.channel_name ) await self.accept() await self.send_json( { "connectionKey": self.channel_name, "clientId": str(user_id), }, ) async def send_message(self, event): message = event["message"] await self.send_json( { "messages": message, "connectionKey": self.channel_name, }, ) async def websocket_disconnect(self, message): user_id = self.scope['user'] await self.channel_layer.group_discard( str(user_id), # group name self.channel_name ) Send to group func: def send_single_user_msg(channel_name, message): channel_layer = get_channel_layer() async_to_sync(channel_layer.send)( channel_name, { 'type': 'send_message', "text": message, } ) I'm using local redis server as the channel layer. Any idea will be really appreciated. -
"no such table: Sport" on exporting a table from sqlite db (django view)
In my django view, after updating a table, I put this code for exporting that table into csv file: # export Data print ("Export data into csv file..............") conn = sql.connect('sqlite3.db') # I tried: db.sqlite3 -> same cursor=conn.cursor() cursor.execute("select * from Sport") with open("heartrateai_data.csv", "w") as csv_file: csv_writer = csv.writer(csv_file, delimiter="\t") csv_writer.writerow([i[0] for i in cursor.description]) csv_writer.writerows(cursor) dirpath = os.getcwdb()+"/heartrateai_data.csv" print("Data exported Successfully into {}".format(dirpath)) conn.close() But it gives me the error: Exception Value: no such table: Sport. I am sure that the table name is correct because is the same in my model.py. -
css and other assets not loading for my django webapp
CSS, JS, fonts, images and other assets are not being loaded into my django app index.html. All the assets for the app are present inside the application app in my django project under "templates/assets". I have tried the other answer which I was getting as suggestion to this question but even that solution did not work for me. [04/May/2022 05:48:50] "GET /assets/js/glightbox.min.js HTTP/1.1" 404 2311 Not Found: /assets/js/count-up.min.js [04/May/2022 05:48:50] "GET /assets/js/count-up.min.js HTTP/1.1" 404 2308 Not Found: /assets/js/main.js [04/May/2022 05:48:50] "GET /assets/js/main.js HTTP/1.1" 404 2284 Here is my dir tree structure : Project Name : myproject App name that serves index.html : app ├── app │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── admin.cpython-38.pyc │ │ ├── apps.cpython-38.pyc │ │ ├── models.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── views.cpython-38.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ └── __init__.cpython-38.pyc │ ├── models.py │ ├── templates │ │ ├── 404.html │ │ ├── assets │ │ │ ├── css │ │ │ │ ├── LineIcons.2.0.css │ │ │ │ ├── animate.css │ │ │ │ ├── bootstrap.min.css │ │ │ │ ├── glightbox.min.css │ … -
Django paginator and zipping
I want to iterate a list and query set in my html render, but am unable to get the Django paginator to work. I zipped the list and queryset so I could iterate them together. Here's my views.py code. Oddly enough, I am able to access the data in both lists with {% for item1, item2 in posts %}, but {{ posts.next_page_number }} is just blank. How can I access the page in the templating engine? -
I have this error: "error": "invalid_client" in postman
I have this error when I use Django Oauth2 Provider. How can I fix it? Sorry because my english is bad. enter image description here -
Handling SSO between two Django applications
There is two Django-based application under a single platform with different sub-domain. One of the applications is using an OpenSource project. Here databases are different between these applications and both respective user tables. We want to avoid making any major changes to this 2nd application(OSS one) to make sure there is maintainability. The question is how can we have an SSO in a place where the user's signup on the 1st application(our main application), the users should be auto-logged in on the 2nd application too. The 1st application should ideally handle all sign-up/sign-in processes. Both applications support SessionAuthentication. -
Deploy Django to Azure Web Service - Failed running 'collectstatic' exited with exit code
I am trying to deploy a Django app to Azure App Services. It runs on the server now, but without the style.css. When I run it on localhost, everything shows correctly with the style.css. Here is the collectstatic part from the deployment log: 11:23:09 PM voicify: Running collectstatic... 11:23:12 PM voicify: 130 static files copied to '/tmp/8da2d7d5197a819/staticfiles'. 11:23:12 PM voicify: "2022-05-03 07:00:00"|WARNING|Failed running 'collectstatic' exited with exit code . Below is my settings.py file: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] And here is my project structure: voice-project -- app-- settings.py -- wsgi.py -- urls.py -- manage.py --db.sqlite3 -- asgi.py -- static -- website --style.css -- website -- .git -
Python showing remember me checkbox in login page with cookies
My login page needs a remember me checkbox so that it doesnot need to login with password again.I have the html code for it but django code shows error.Can anyone help me to find the code. -
Is there any way to control all the configuration of settings.py from models in django?
I want to control everything from admin panel so that it is easy for the non technical person to control everything from admin panel.Is there any way to control everything from admin panel?? -
I want to compare now time with Django DateTimeField Filed in Django Templates
I want compare now time with Django DateTimeField Filed in Django Templates. -
django.db.utils.ProgrammingError: column _____ does not exist
There are a lot of similar posts to this but none that I have found seem to resolve the program. I have tried to add a field to a custom user model that inherits from Django's AbstractUser: class AppUser(AbstractUser): credibility_rating = models.FloatField(default=0) When I save this and try to run python manage.py makemigrations it gives me this error: Traceback (most recent call last): File "/Users/jhcscomputer1/.local/share/virtualenvs/senior_project-hOu14Mps/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column api_appuser.credibility_rating does not exist LINE 1: ...ppuser"."is_active", "api_appuser"."date_joined", "api_appus... When I replace the field credibility_rating with pass the error goes away. Similarly, when I try to add a new field in a different model, the error doesn't occur either. I am not sure if this matters, but I am using Postgres. My settings.py file does include AUTH_USER_MODEL = "api.AppUser" where api is the name of my app. I am not sure where I am going wrong. Thank you for any help. Full traceback: Traceback (most recent call last): File "/Users/jhcscomputer1/.local/share/virtualenvs/senior_project-hOu14Mps/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column api_appuser.credibility_rating does not exist LINE 1: ...ppuser"."is_active", "api_appuser"."date_joined", "api_appus... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File … -
Django DRF - Is it possible to have a pre-defined form in the browsable API using function-based views?
I have an API built with Django DRF. I'm using function based views and I was wondering if it's possible to add a defined form (based on the model serializer) for the browsable API? I want to turn this (the browsable API I get with function based views): Into this (what I get with class based views): -
Django Model not defined
I've been working on some views and using a model for like a week now and there was no issues until now: I did not change anything but add a new field to the model, and now myModel.objects.create() gives me a name is not defined error. I have the model imported and as I said, I've been working on this for a week and I created several models using the exact same code. models: class Prescription(models.Model): prescription_id = models.CharField(max_length=26, default=prescription_id, editable=False, unique=True) # THIS IS THE FIELD I ADDED BEFORE HAVING THIS ERROR appointment = models.ForeignKey('booking.Appointment', on_delete=models.SET_NULL, null=True, blank=True) doctor = models.ForeignKey('core.Doctor', on_delete=models.CASCADE) patient = models.ForeignKey('core.Patient', on_delete=models.CASCADE) overriden_date = models.DateField(null=True, blank=True) control = models.BooleanField(default=False) control_date = models.DateField(null=True, blank=True) send_email = models.BooleanField(default=False) posted = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name = "Ordonnance" verbose_name_plural = "Ordonnances" def __str__(self): return str(self.id) class PrescriptionElement(models.Model): prescription = models.ForeignKey('Prescription', on_delete=models.CASCADE) drug = models.ForeignKey(Drug, on_delete=models.CASCADE, null=True) custom = models.CharField("Elément", max_length=25, null=True, blank=True) dosage = models.CharField(max_length=45, null=True, blank=True) posologie = models.CharField(max_length=256, null=True, blank=True) duration = models.CharField("Durée", max_length=15, null=True, blank=True) views: PrescriptionElement.objects.create(prescription=prescription, drug=listemedicament, custom=medicament, dosage=dosage, posologie=posologie, duration=duree) error: name 'PrescriptionElement' is not defined -
Code running in local does not work on server (Django)
I created a List in views.py to draw a chart in html. In local PC, the chart is printed well whenever connected. But on the server PC, "Cannot resolve keyword 'jan' into field." An error occurs. I wondered if the indent of the for statement was a problem, but it works fine in local without any problem. But, If I proceed with "sudo systemctl daemon-reload" -> "sudo systemctl restart wsgi" on the server PC, For a few minutes the chart is printed normally. However, when I access the page again after a while The above error occurs. I really don't know what's wrong. Please help... [views.py] team_parameter = request.GET.get('team') monthly_kwargs = {} for i in range(1, 13): gte = datetime(today.year, i, 1) lte = get_last_day_of_month(date(today.year, i, 1)) mo = f'{gte:%b}'.lower() monthly_kwargs[mo] = Count('student_id', filter=Q(date__gte=f'{gte:%Y-%m-%d}', date__lte=f'{lte:%Y-%m-%d}')) monthly_kwargs['SPECIAL_' + mo] = Count('student_id', filter=Q(date__gte=f'{gte:%Y-%m-%d}', date__lte=f'{lte:%Y-%m-%d}', student__class__id__in=special)) monthly_kwargs['total'] = Count('student_id', filter=Q(date__year=today.year)) monthly_kwargs['SPECIAL_total'] = Count('student_id', filter=Q(date__year=today.year)) value_list_args = ['uploader_id__first_name', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec', 'total', 'SPECIAL_jan', 'SPECIAL_feb', 'SPECIAL_mar', 'SPECIAL_apr', 'SPECIAL_may', 'SPECIAL_jun', 'SPECIAL_jul', 'SPECIAL_aug', 'SPECIAL_sep', 'SPECIAL_oct', 'SPECIAL_nov', 'SPECIAL_dec', 'SPECIAL_total'] if not request.GET or parameter == 'ALL': monthly_register = Memo.objects \ .annotate(**monthly_kwargs) \ .values_list(*value_list_args) \ else: monthly_register = Memo.objects \ … -
Tinymce HTMLField Doesn't show in StructBlock
I'm trying to use HTMLField inside a StructBlock, but the text editor doesn't show... Any idea if this is the correct way to use the tinymce with blocks.StructBlock ? Thanks from tinymce.models import HTMLField class BodyBlock(blocks.StructBlock): content = HTMLField(null=False, blank=True) # <-- this is the tinymce rich text field show_share_buttons = blocks.BooleanBlock( verbose_name=_('show share buttons'), default=True, help_text=_('Whether "Share" buttons will appear at the top left corner of the article body') ) class Meta: # noqa template = "blocks/body.html" icon = "doc-full" label = "Body Ritch Text" body.html <div class="find-page__body main-content"> {% if self.show_share_buttons %} <dv class="not-mobile"> {% include 'share_buttons.html' with url=page.get_full_url %} </dv> {% endif %} {{ self.content}} </div> -
Django create model variable based on another model
I'm new in Django and I have a question about architecture. I'm not looking for a ready solution, just for some explanations in a simple way, and maybe tips about architecture. I want to create a simple classic RPG helper, and that's why a need three models: Fraction Class Character And Character stats should be based on another two models. Example: class Fraction(models.Model): describe = models.CharField(max_length=300) hp = models.modelIntegerField(default = 0) dmg = models.modelFloatField(default = 0.0) class Char_class(models.Model): describe = models.CharField(max_length=300) hp = models.modelIntegerField(default = 0) dmg = models.modelFloatField(default = 0.0) skills = models.CharField(max_length=50) class Character(models.Model): char_id = models.modelIntegerField(default = 0) fraction = models.ForeignKey(Fraction, on_delete=models.DO_NOTHING) char_class = models.ForeignKey(Char_class, on_delete=models.DO_NOTHING) hp = model.modelIntegerField(default = fraction.hp + char_class.hp) dmg = model.modelFloatField(default = fraction.dmg + char_class.dmg) And what do I want to obtain? I thought I will just create in admin Django some class, and some fraction. Next after that I will create some characters just picking fractions and classes from the list, and then hp, and dmg, should be a sum of the value from that two models. And I got the error, that ForeignKey doesn't have a dmg/hp variable. I just googled and found some information, and now if I understand … -
Django-tables2, Django-filters how to override .empty_text
Hope everyone is well. I'm using django-tables2 and django-filters to display large datasets in html tables. I wanted to use the django-tables empty_text to return a message when there is zero results. However I currently load the tables with an empty queryset to avoid large load times (Better to let the user decide if they want to generate the whole data set), this causes a problem because the empty_text message populates. I want to know if there is a away to stop the empty_text message appearing if there is no filters applied or no filter URL. If I can't do it that way maybe there is a better way to determine empty set on filter result. Thanks in advance, Thomas -
Python/Django project working correctly on a local host server but not working on a heroku server
I have created a web application where Sign Up and login was create using Django’s authentication system. Basically I used the code from this page: https://www.geeksforgeeks.org/django-sign-up-and-login-with-confirmation-email-python/ On my server the project is working perfectly, but when I did the hosting it is not possible to create users. I have a suspicion that my problem is with the database because I am using the default django settings. This is the error I get when I try to create user on the hosted site: The above exception (relation "auth_user" does not exist LINE 1: SELECT (1) AS "a" FROM "auth_user" WHERE "auth_user"."userna... ^ ) was the direct cause of the following exception: /app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/exception.py, line 55, in inner response = get_response(request) Local vars /app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Local vars /app/user/views.py, line 32, in register if form.is_valid(): To Request information I got: **Request information** USER AnonymousUser **GET** No GET data **POST** Variable Value csrfmiddlewaretoken '4tl1onB5FTWa8FhMwHqiiuVsMo9J8yf5yW0qdiubabYOCeDwngMSnJNXFL08baBO' username 'abacaxi10' email 'abacaxi1012@gmail.com' password1 'mtHya2yaWRw2nxK' password2 'mtHya2yaWRw2nxK' As I said on the local host the site works very well. I would like to know how can I fix the error or how can I build a simple database just for user registration? -
Jsonresponse not working in CreateView - Django
I'm trying to get all the users who has the group 'decoration' into a form field by using JsonResponse to get the list in realtime when the user start to type in the field. The problem here is that I'm not getting any data in the form as a Jsonresponse. If I make a print of "titles", is getting the correct data, but is not bringing the data to the form... views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['...'] def get_form(self, form_class=None): form = super().get_form(form_class) if 'term' in self.request.GET: qs = User.objects.filter(groups__name='decoration', username__icontains=self.request.GET.get('term')) titles = list() for product in qs: titles.append(product.username) return JsonResponse(form, safe=False) return form def form_valid(self, form): form.instance.author = self.request.user return redirect(reverse('blog:post-detail', kwargs={'pk': obj.id})) def form_invalid(self, form): messages.error(self.request, self.error_message) form.instance.thumb.checked = True return super().form_invalid(form) models.py class Post(models.Model): title = models.CharField(max_length=100) culture = models.CharField(max_length=100) .HTML <div class="form-group"> <label>Some text</label> {% render_field form.culture class="form-control form-st text-body" style="box-shadow: none;font-size:1.5rem;" id="nightclub" placeholder='...' autocomplete="off" %} </div> script which handles the autocomplete <script> $( function() { $( "#nightclub" ).autocomplete({ source: '{% url 'blog:post-create' %}' }); }); </script> Any help would be grateful! -
Django Form Field Validation - Input fields reset
I need some help. I have a login form where the user is required to provide a username and password. If the user fails to provide the information I present them with a validation error. The issue I have is that if the user provides a username (for example) the validation error disappears and the value that was in the field. The field value resets again. Not sure what I am doing wrong. Here is my template code: # Create your views here. def login(request): message = '' username = request.POST.get('username') password = request.POST.get('password') if request.method == 'POST': form = LoginForm(request.POST or None) if form.is_valid(): user = authenticate( username=form.cleaned_data['username'], password=form.cleaned_data['password'], ) if user is not None: auth_login(request, user) return redirect('expedition:gallery') else: return render(request, 'account/login.html',{'form':form}) else: form = LoginForm() return render(request, 'account/login.html',{'form':form}) -
Django Rest Framework: Will rejecting uploads at the view level still block the event loop?
Our app is scaling and is lagging due to uploads not being done through signed urls. Will the following code still block the event loop if a user tries to POST a large file to this endpoint? Or will it be rejected, allowing our event loop to continue? If this does still block the event loop, what's a better solution to temporarily turn the endpoints off? Is a 405 from DRF a viable way to do this by turning off the method? We prefer a 400 so we can return a custom error. class UploadViewset( mixins.CreateModelMixin, viewsets.GenericViewSet ): permission_classes = [permissions.IsAuthenticated] def create(self, request, room_pk=None): ######################## # Temporarily Disable ######################## return Response( { "detail": "Uploads have been temporarily disabled for performance." }, status=status.HTTP_400_BAD_REQUEST, )