Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SMTPNotSupportedError at /contact/email STARTTLS extension not supported by server. Django 2
SMTPNotSupportedError at /contact/email STARTTLS extension not supported by server. Request Method: POST Request URL: http://127.0.0.1:8000/contact/email Django Version: 2.2.12 Exception Type: SMTPNotSupportedError Exception Value: STARTTLS extension not supported by server. Exception Location: /usr/lib/python3.8/smtplib.py in starttls, line 755 Python Executable: /usr/bin/python3 Python Version: 3.8.2 -
Is django-filter FilterSet behavior consistent with native Django behavior for queries spanning multi-valued relationships?
I’m trying to query all unread messages for a user via the recipient model (i.e. each message has many recipients with a read property). The query works as expected when run with the model manager. For example: Message.objects.filter(**{"recipients__user_id": 1, "recipients__read": False }) However, the query includes all messages the user received regardless of read status when run with FilterSet (using django-filter version 2.3.0). For example: MessageFilter(data={"recipients__user_id": "1", "recipients___read": False }).qs Here’s the MessageFilter: class MessageFilter(FilterSet): class Meta: model = Message exclude = ('deleted_at', ) fields = ('chat_id', 'recipients__user_id', 'recipients__read', ) filter_overrides = { # NOTE: enables support for querying pk rather than relay uuid models.ForeignKey: { 'filter_class': LocalIDFilter }, } # NOTE: enables mapping from camelcase to snakecase order_by = OrderingFilter(fields=(('created_at', 'createdAt'),),) Anyone know if my implementation is incorrect or if this is just desired library behavior (I couldn’t tell from the docs)? Also, any suggested workarounds would be appreciated. Aside from manually overriding the qs property on FilterSet, I'm not seeing any better solutions. -
Django: Fixing an error in the payment view
I am trying to know the reason for getting an error which arises as a result of an exception in the views after making a payment. Noting the payment goes through with a successful message that the order has been placed but along with it comes another message saying that A serious Error Occured. We have been notified. which is related to the very last exception in the payment view Here is the views.py: class PaymentView(View): def get(self, *args, **kwargs): # order order = Order.objects.get(user=self.request.user, ordered=False) if order.billing_address: context = { 'order': order, 'DISPLAY_COUPON_FORM': False } return render(self.request, "payment.html", context) else: messages.warning( self.request, "You have not added a billing address") return redirect("core:checkout") # `source` is obtained with Stripe.js; see https://stripe.com/docs/payments/accept-a-payment-charges#web-create # -token def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.grand_total() * 100) try: charge = stripe.Charge.create( amount=amount, # cents currency="usd", source=token, ) # create payment payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.grand_total() payment.save() # assign the payment to the order order_items = order.items.all() order_items.update(ordered=True) for item in order_items: item.save() order.ordered = True order.payment = payment order.ref_code = create_ref_code() order.save() messages.success(self.request, "Your Order was Successful ! ") # Email when … -
template shows markup and not the page when combining context and forms
I am fairly new to Django. I am trying to display a dictionary and form on the same page. However, it only vies the Html markup and not the actual page. Here is my code: home/views.py: from django.shortcuts import render from recruit.forms import RecruitForm articles = [ { 'author': 'Glenn', 'title':'title 1', 'content': 'first content', 'date_posted': 'January 12' }, { 'author': 'batman', 'title':'title 2', 'content': 'second content', 'date_posted': 'January 12' }, { 'author': 'batgirl', 'title':'title 3', 'content': ' Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas ratione eaque nam totam! Labore consectetur nostrum dicta magnam ex expedita facilis illum odit quibusdam vitae?', 'date_posted': 'January 12' } ] # Create your views here. def index(request): form = RecruitForm() context = { 'articles': articles } return render(request, 'home/index.html', context, {'form':form}) recruit/forms.py: from django import forms from phonenumber_field.modelfields import PhoneNumberField from .models import Recruit class RecruitForm(forms.ModelForm): email = forms.EmailField() phone = PhoneNumberField() class Meta: model = Recruit fields = ['firstname', 'lastname', 'email', 'phone', 'city', 'contact_preference'] widgets = {'contact_preference': forms.RadioSelect } When I don't pass context the entire page renders. The same with form. I know how to validate forms, I just wanted to make this question as generic as possible. So either … -
df.to_sql results in server 502 bad gateway (not because of file size)
within a django form, I am importing the data from one postgresql table. I am modifying this data through pandas and I want to replace the existing data in the db by the modified data. Important to mention that the size of the df is about 100k rows and 4 columns. histo2db = histo2.to_sql('uploadfiles_historical_data', engine, if_exists='replace', method='multi',chunksize='10000') running that results in a 502 bad gateway error after 5 minutes (my nginx time out limit) I am pretty confused about why this is happening, I have verified that the datatype of the dataframe matches the postgresql table datatype. the logs are very not helpful, beside this one from postgresql where I can read this: 2020-08-22 23:09:14.339 GMT [24053] LOG: skipping missing configuration file "/rdsdbdata/config/recovery.conf" 2020-08-22 23:09:14 UTC::@:[24053]:LOG: database system is shut down Postgres Shared Memory Value: 515883008 bytes could it be something related with postgresql settings? -
Django Pythonanywhere, model field default=timezone.now() repeats the same time multiple times
I am hosting a web app on pythonanywhere. In one of my models I have this field, capturing the datetime when the user performs a certain action (submits a form in this case), which subsequently gets recorded in the database. from django.utils import timezone upload_datetime = models.DateTimeField('date uploaded', default=timezone.now()) However, seen in the image below, most of the rows in the database display the exact same time. This should under normal circumstances be a very rare case, so I am assuming a bug here. Can I get any help on where to start looking? Database entries of upload_datetime -
Django admin, how select several fields and edit at once
Good time. How to do following in Django admin: For example, I have model called Events. I have some events created. I have fields like event name, .... and also field "planning Date" I need set the same date in "planning Date" field for 5 events. I am selecting 5 events in checkbox and need in one action do it. I mean something like delete action for selected objects. -
ERROR: Exception in ASGI application Django to 3rd party python app
Trying to send payload data from the frontend via axios to django then via restapi to 3rd party python app I get a status code of 200 to django but then I get an internal server error to 3rd party after django with the following The 3rd party service error INFO: ::1:51365 - "POST / HTTP/1.1" 500 Internal Server Error ERROR: Exception in ASGI application Traceback (most recent call last): File "E:\projects\SethDash\django-vue\venv\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 388, in run_asgi result = await app(self.scope, self.receive, self.send) File "E:\projects\SethDash\django-vue\venv\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 45, in __call__ return await self.app(scope, receive, send) File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\applications.py", line 111, in __call__ await self.middleware_stack(scope, receive, send) File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\middleware\errors.py", line 181, in __call__ raise exc from None File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\middleware\errors.py", line 159, in __call__ await self.app(scope, receive, _send) File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\exceptions.py", line 82, in __call__ raise exc from None File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\exceptions.py", line 71, in __call__ await self.app(scope, receive, sender) File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\routing.py", line 566, in __call__ await route.handle(scope, receive, send) File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\routing.py", line 227, in handle await self.app(scope, receive, send) File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\routing.py", line 41, in app response = await func(request) File "app.py", line 30, in homepage params = await request.json() File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\requests.py", line 227, in json self._json = json.loads(body) File "c:\users\admins\appdata\local\programs\python\python36\lib\json\__init__.py", line 354, in loads return _default_decoder.decode(s) … -
Everything crashed after install lib in django
Sorry for bothering, I am running Django 3.0.1 $ python -m django --version 3.0.1 After installed: pip install git+https://github.com/jhuapl-boss/boss-oidc.git Django was uninstalled automatically without asking (django 3.0.1 is not supported with that lib, I noted that late) First question: If I do a mistake installing no compatible libs the whole framework is uninstalled? So, I reinstalled django 3.0.1, uninstalled the boss-oidc lib, actually python too from scratch, virtualenv, and who knows what else. So, from that moment, after I apply makemigrations, nothing works. I tried cloning a github repo, going to a old commit, it does not work (at the end the log). If I create a new empty project and add some models, it does the migrations without problems. I am new in Django, I would like to know if this is so unstable or It is just me learning from scratch. I can not recover my whole work from the last 20 days. The log: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/mariano/Code/Python/Django3.1/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/mariano/Code/Python/Django3.1/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/mariano/Code/Python/Django3.1/lib/python3.8/site-packages/django/core/management/base.py", line 341, in run_from_argv connections.close_all() File "/Users/mariano/Code/Python/Django3.1/lib/python3.8/site-packages/django/db/utils.py", line … -
How to use rest_framework token authentication with frontend pages django?
I'm working with a vue-django project, so I create a rest api for user authentication using django_rest_framework token authentication, now I want to use tokens to authenticate frontend pages. those are urls & views code lines def login_page(request): if not request.user.is_authenticated: return render(request, "login.html") else: return render(request, "home.html") def home_page(request): if request.user.is_authenticated: return render(request, "home.html") else: return redirect("login/") urlpatterns = [ re_path('^$', home_page), path('admin/', admin.site.urls), path('login/', login_page), path('api/', include("server.rest_api.urls")) ] so I create a backend to get a cookie from requests like this: class RestTokenBackend(ModelBackend): supports_object_permissions = True supports_anonymous_user = False supports_inactive_user = False def authenticate(self, request, username=None, password=None, **kwargs): print("inside", file=sys.stderr) token: str = request.COOKIES.get('token') if token and not token.isspace(): try: u = Token.objects.get(key=token) return u except: return None return super().authenticate(request, username, password, **kwargs) then I set the settings variables to: AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'server.rest_token_backend.RestTokenBackend' ] but it doesn't work ,as you can see , I put a print command to check in the console but nothing was printed, so what went wrong ? I followed the documentation and some others questions nothing worked out for me -
How to disable get by id or retrieve api in django rest framework using model viewset?
I am using Django Rest Framework 3.11.0 and Django 3.0.8 I have a very simple Hello World API and I am using it via model viewset. Therefore I need only GET method which is achieved by list function. I need to disable GET BY ID or retrieve API but not able to do this. Views.py from django.shortcuts import render from rest_framework.permissions import IsAuthenticated from rest_framework import viewsets from .serializer import DemoSerializer from rest_framework.response import Response from rest_framework import status # Create your views here. class DemoViewSet(viewsets.ModelViewSet): serializer_class=DemoSerializer http_method_names = ['get'] def get_queryset(): pass def list(self,request): """ WELCOME TO SUNFLOWER BACKEND HELLO WORLD API """ return Response(data={"message":"WELCOME TO SUNFLOWER BACKEND"},status=status.HTTP_200_OK) serializer.py from rest_framework import serializers class DemoSerializer(serializers.Serializer): pass urls.py from django.urls import path,include from .views import DemoViewSet #Router from rest_framework.routers import DefaultRouter router=DefaultRouter() router.register('',DemoViewSet,basename='demo') urlpatterns = [ path('',include(router.urls)), ] Still I am able to see in my swagger GET BY ID or retrieve api Please help me to disable GET BY ID or Retrieve API in model view set and I just want only one get API. -
GeoDjango admin map draws point at wrong location
I have a model like from django.contrib.gis.db import models class Letter(models.Model): """Letter Model""" class Meta: db_table = 'Letter' center = models.PointField(geography=True) and the model has a data as follows: a = models.Letter.objects.get(id='699c49db-1db7-41cf-90a9-a173f9352805') print(a.center) >>SRID=4326;POINT (40.7128 74.0) It should show data around NewYork, but django admin map points to uncorrect location: it points to Barents sea which is located on North of the finland. When I change the Point value, it locates to the different places. Please also note that I'm using django rest framework package for serializer and django_extensions package for inputting Point field. Could somebody help me find the cause and solution for this? -
How to implement multithreading or is it already implemented in Django?
I'm new to Django and I'm not even sure if the thing I want is called multithreading so sorry if I'm mistaken. I'm currently making an app in Django that users can upload files to etc. I'm still at the start and wanted to know if the file upload process will be different for all users i.e. if 2 users are uploading a file at the same time, will this be resolved automatically or do I need to implement something? -
Adding inline fields depending on another model's field value
I have a Survey model that defines the length of a survey. I want to make it so that in the admin page, when adding questions to a survey, there are automatically enough fields listed equal to the length of the survey, rather than adding the questions one at a time. I am unsure how to do this. Any help would be appreciated! models.py class Survey(models.Model): title = models.CharField(max_length=100, default='Nursing Survey') length = models.IntegerField(null=False) # e.g: If length = 10, I want 10 question fields when adding questions is_taken = models.BooleanField(default=False) def __str__(self): return self.title admin.py from django.contrib import admin from .models import Survey, Question, UserScore admin.site.site_url = "/survey" admin.site.register(Survey) admin.site.register(Question) admin.site.register(UserScore) -
Changed the relationship of a Foreign Key | Django model
my buyer field from the Sell model had relationship with the Buyer model like this: class Buyer(models.Model): name = models.CharField(max_length=200, blank=True) description = models.CharField(max_length=200, blank=True) class Sell(models.Model): item = models.OneToOneField(Buy, related_name='sell', on_delete=models.CASCADE) buyer = models.ForeignKey(**Buyer**, related_name='sell', on_delete=models.CASCADE) But now, it's set to 'User' model as you can see below: class Sell(models.Model): item = models.OneToOneField(Buy, related_name='sell', on_delete=models.CASCADE) buyer = models.ForeignKey(**User**, related_name='sell', on_delete=models.CASCADE) When I go to Django admin, it shows me all the available users from the User model but if I try to save, I got an error like this: insert or update on table "dma_sell" violates foreign key constraint "dma_sell_buyer_id_4d165f92_fk_dma_buyer_id" DETAIL: Key (buyer_id)=(13) is not present in table "dma_buyer". I'm wondering I should NOT have changed this but what is the best way to correct that? I really need to relate the buyer field with User model! Thank you! -
Adding a Django constraint based on data in model
Say I have a simple model like this: class Country: name = models.CharField(max_length=200, unique=True) class City: name = models.CharField(max_length=200, unique=True) country = models.ForeignField('Country', on_delete=models.PROTECT) class Person: name = models.CharField(max_length=200, unique=True) country = models.ForeignField('Country', on_delete=models.PROTECT) city = models.ForeignField('City', on_delete=models.PROTECT) Obviously, I'd like to constrain Person to have be able to refer to cities in the same country as the person. I can't see any easy way of doing this with limit_choices_to in the city field, as it can't reference the current data values. What's the best way of going about this - ideally that would also work with the admin console? -
How to get the ID of row from DataTables and insert in the url thru Ajax?
Following is my code that giving me Loading error when I add the company_id in the url "http://127.0.0.1:8000/api/"'+company_id+'"/edit_company" like that. <script> $(function() { var oTable = $('#sodmzs').DataTable({ "ajax": function (data, callback, settings) { $.ajax({ url: "http://127.0.0.1:8000/api/company/", dataType: "json", type: 'GET', success: function(data) { const data_format = {"data": data}; callback(data_format); } }); }, "columns": [ { "data": "company_id" }, { "data": "name" }, { "data": null, "render": function (data, type, row, meta) { // you can even get the data from other columns here // and render whatever you want on these cells return '<td><a href="http://127.0.0.1:8000/api/"'+company_id+'"/edit_company" class="btn ink-reaction btn-floating-action btn-warning"><i class="md md-edit"></i></a></td>' } } ] }); }); </script> PLease let me know is that the proper way of doing ? -
Django keeps reporting the same error after I already edited views.py
I am editing a Django 2.2 application and I received an Exception: TypeError at /myappname/myurl 'RelatedManager' object is not iterable Exception Location: /myprojectlocation/myappname/views.py in myview, line 41 Whoops, I accidentally typed .objects instead of .objects.all(). Easy fix. But now, no matter how I edit views.py, I keep receiving the exact same exception, always pointing at line 41. I even commented line 41 out entirely, and still get the same exception. The exception Traceback shows the updated line 41, so I know I am definitely editing the right file and the changes are being saved, but the actual exception itself just keeps complaining about that RelatedManager no matter what I edit. I've restarted the webserver and I've cleared all my browsing data. So what on earth is still "remembering" the old code that I've edited many times since? -
How to sync local host with docker host?
I have a hello world Django project and i want to dockerize it. My OS is windows 8.1 and I'm using docker toolbox. using volumes I could persist data in docker container but the code in docker is not sync with the code in my local host. Here is my docker-compose.yml: version: '3.7' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - myvol1:/code ports: - 8000:8000 volumes: myvol1: I don't know how should I use volume for this purpose. I have tried this. without using volumes I can run the local development server but when using volume I got that error. I'd be grateful for your help. -
Heroku with Docker release failed - ModuleNotFoundError: No module named 'users.apps'
I've been following a book tutorial that uses docker with Django. When I used the command 'git push heroku master', I get the following output: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/usr/local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.7/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'users.apps' I have also been having issues through this project installing with pipenv, which required a workaround. I'm thinking it could be related. Regardless, here is my heroku.yml file: setup: addons: - plan: heroku-postgresql build: docker: web: Dockerfile release: image: web command: - python manage.py collectstatic --noinput run: web: gunicorn bookstore_project.wsgi And my docker-compose.prod.yml: version: '3.7' services: web: build: . command: gunicorn bookstore_project.wsgi -b 0.0.0.0:8000 environment: - ENVIRONMENT=production - SECRET_KEY=[removed] - DEBUG=0 - STRIPE_TEST_PUBLISHABLE_KEY= [removed] - STRIPE_TEST_SECRET_KEY= [removed] ports: - 8000:8000 depends_on: … -
Django given URL path name get URL
I am trying to create a view which will list the URLs available on the server. given a url path like so: path(r'reindex_search', views.IndexView.as_view(), name='reindex') How can I, from within views.py, get the full path (eg 'http://localhost:8000/reindex_search'), given the name 'reindex'? I have tried using rest_framework.reverse and it works for some of my endpoints but fails on the urls that have variables in the path. Here is my attempt so far: urls.py api_root_dict = OrderedDict() ... api_root_dict['reindex_search'] = 'reindex' ... urlpatterns = [ ... path(r'reindex_search', views.IndexView.as_view(), name='reindex'), path('api/', views.HomeView.as_view(api_root_dict=api_root_dict), name='home'), ... views.py class HomeView(APIView): api_root_dict = None def get(self, request, *args, **kwargs): ret = OrderedDict() namespace = request.resolver_match.namespace for key, url_name in self.api_root_dict.items(): if namespace: url_name = namespace + ":" + url_name try: ret[key] = { 'href': reverse( url_name, args=args, kwargs=kwargs, request=request, format=kwargs.get('format', None) ) } except NoReverseMatch: continue home_url = reverse(viewname='home', request=request) obj = { '_links': { 'self': {"href": home_url}, **ret } } return Response(obj) This fails for example for the following path in my app's urls.py: path('<str:endpoint>/schema', views.schema, name='schema') with this in added to the root dict: api_root_dict['schema'] = 'schema' (by fail I mean NoReverseMatch exception) There must be a better way. How does Django templates do it … -
Server error (500) when I try to search in any language other than English
i want support search with all language in search bar , but when i write an Arabic word for example , it says Server error (500) my code | Models.py : class Homepage(models.Model): name = models.CharField(max_length=50,default="") app_contect = models.CharField(max_length=240,default="") page_url = models.URLField(max_length=250,default="") app_image = models.ImageField(upload_to='images/',null=True, blank=True) def get_image(self): if self.app_image and hasattr(self.app_image, 'url'): return self.app_image.url else: return '/path/to/default/image' def __str__(self): return self.name class PCprogram(models.Model): name = models.CharField(max_length=50,default="") app_contect = models.CharField(max_length=240,default="") page_url = models.URLField(max_length=250,default="") app_image = models.ImageField(upload_to='images/',null=True, blank=True) post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True) def get_image(self): if self.app_image and hasattr(self.app_image, 'url'): return self.app_image.url else: return '/path/to/default/image' def __str__(self): return self.name class Meta: ordering = ('-post_date',) views.py : def search(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: home_database= Homepage.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcprograms_database= PCprogram.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) results = list( sorted( chain(pcprograms_database,home_database), key=attrgetter('name'), reverse=True # Optional )) paginator = Paginator(results,6) page = request.GET.get('page') results = paginator.get_page(page) context={'results': results, 'submitbutton': submitbutton} return render(request, 'html_file/search.html', context) else: return render(request, 'html_file/search.html') else: return render(request, 'html_file/search.html') search form in html page : <form id="search_form" action="{% url 'search' %}" method="GET" value="{{request.GET.q}}" class="form-inline"> <input id="search_box" type="text" name="q" placeholder=" Search For ... " style="color:black" class="form-control mr-sm-2"/> <input class="btn … -
django - AttributeError: 'list' object has no attribute 'apppend' [closed]
I am following Vitor's tutorial on simpleisbetterthancomplex.com and using the same logic on my own program. In my Views.py my for loop is running into an error. The traceback in Line 37 (comment below) says that the 'list' object has no attribute 'append', when the list has a few rows as CharField. Views.py def visuals(request): data = [] labels = [] queryset = Arrest.objects.order_by('number') for arrest in queryset: data.append(arrest.number) labels.apppend(arrest.charge) # This is the error line according to traceback. return render(request, "data/visuals.html", { 'labels': labels, 'data': data, }) Models.py class Arrest(models.Model): number = models.IntegerField() charge = models.CharField(max_length=64) Traceback AttributeError at /visuals 'list' object has no attribute 'apppend' Request Method: GET Request URL: http://127.0.0.1:8000/visuals Django Version: 3.0.8 Exception Type: AttributeError Exception Value: 'list' object has no attribute 'apppend' Exception Location: C:\Users\(removed)\data\views.py in visuals, line 37 Python Executable: C:\Users\(removed)Python\Python38-32\python.exe Python Version: 3.8.1 -
Catching a 413 Request Entity Too Large in Django
When uploading a file, how can I catch the 413 Request Entity Too Large error so I can reload the form with a message saying the file is too large? I've already increased the limit in NGINX with client_max_body_size so this is a fallback in case someone still does exceed the limit. -
Redirecting multiple times to come on a page in django
I am sorry for the title not being descriptive coz I couldnt think of a good one. My concern is that I am having a django website in which I have a product view page. In that If a user is not logged in and clicks on add to cart then he is redirected to login page and and after he logs in he comes back to the product view page that was opened earlier(Using the next)This is my login view: def login(request): if request.user.is_authenticated: return redirect('/') else: if request.method == "POST": email=request.POST['email'] password=request.POST['password'] user=auth.authenticate(email=email,password=password) if user is not None: auth.login(request, user) next_page = request.POST['next'] if next_page != '': return redirect(next_page) else: return redirect('/') else: messages.info(request,"Email Password didn't match") return redirect('login') else: return render(request,"login.html") Now the problem arises when a person is not already a user of my site.In that case the person is redirected to login but and he then chooses to signup and after signup he is redirected back to login page and after logging in he is redirected to index and not to the product view page. So is there any way that for a website user who doesnt have an account when clicks on add to …