Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get PDF from HTML form view template with xhtml2pdf Django
I get a problem with my function letting to get a PDF file from my HTML form view. It generate all choices to pdf from the form, and I would like to generate only chosen options from the forms.ChoiceField in forms.py. My view.py: from django.shortcuts import render from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from django.views import View from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1", 'ignore')), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None form = Formularz context = { 'form': form, } class ViewPDF(View): def get(self, request, *args, **kwargs): pdf = render_to_pdf('PLK/pdf_template.html', context) return HttpResponse(pdf, content_type='application/pdf') class DownloadPDF(View): def get(self, request, *args, **kwargs): pdf = render_to_pdf('PLK/pdf_template.html', context) response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" % ("12341231") content = "attachment; filename='%s'" % (filename) response['Content-Disposition'] = content return response def FormularzView(request): template_name = 'PLK/PLK.html' form = Formularz context = { 'form': form, } return render(request, template_name, context) on template I have got 2 buutons, first to view PDF, second to donwload. -
Pytest: how to mock django management command class method variable
There is a django manager command that handles the csv file. app/my_app/my_command.py class Command(BaseCommand): def handle(self, *args, **options): path = (os.path.join(os.path.abspath(os.path.dirname(__name__)), 'data.csv')) # other logic with file I am writing a test for it in pytest, the problem is that I can not understand how to mock the variable path to test accessed not the real data.csv but a temporary test.csv file @pytest.fixture def create_test_csv_file(tmpdir_factory): path = tmpdir_factory.mktemp('data').join('test.csv') # other logic return str(path) @pytest.mark.django_db def test_function(mocker, create_test_csv_file): # smth like mock_path = create_test_csv_file <- NEW CODE HERE call_command('my_command') -
Django custom exception to return 503 and ignore sending admin mail
I want to raise a custom exception that will: return 503 status don't send django admin email I can do one of them, but not both together return 503: using drf ApiException, or custom exception handler to handle response, but I won't get the exception type in the email record to filter don't send email: checking exception type in a custom email handler class, but this returns 500 -
How to create alert from view model
I want to validate file. While file is invalid, i want to refresh my page and inform user that he did not upload proper file. So i have this in my views/campaign.py try: wb = load_workbook(mp_file) except BadZipfile: return redirect('campaign_add', client_id) The only way i know how to do it is add another attribute to client class which will be is_error(models.BooleanField()) And then change views/campaign to try: client.is_error = False wb = load_workbook(mp_file) client.save() except BadZipfile: client.is_error = True client.save() return redirect('campaign_add', client) And with another attribute i can add in my campaign.html file some kind of if is.error is true i'm adding some kind of windows with information about bad file after reloading page. But is there any way to do it without adding another attribute? -
How do I prevent the Django admin delete confirmation view to display all the objects to be deleted?
I have a object that has several thousand related objects. How can I make the confirmation view in the Django administration only display the Yes/No buttons without the list of all the objects to be deleted. The problem is that displaying the whole list of objects takes way too much time. I am using Django 3.0.3. -
Error during execution: docker-compose run --rm api python3 manage.py migrate
I install saleor on Linux Mint according to the instructions https://docs.saleor.io/docs/3.0/developer/installation When executing the command "docker-compose run --rm api python3 manage.py migrate", an error appears, tell me how to fix it? $docker-compose run --rm api python3 manage.py migrate Starting saleor-platform_db_1 ... Starting saleor-platform_jaeger_1 ... done Starting saleor-platform_redis_1 ... done ERROR: for saleor-platform_db_1 a bytes-like object is required, not 'str' ERROR: for db a bytes-like object is required, not 'str' Traceback (most recent call last): File "/usr/lib/python3/dist-packages/docker/api/client.py", line 261, in _raise_for_status response.raise_for_status() File "/usr/lib/python3/dist-packages/requests/models.py", line 940, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 500 Server Error: Internal Server Error for url: http+docker://localhost/v1.22/containers/c015b9d2a6e0ba06c8cc393147db2a4eb1a0fc72d1ae2805e177b409bb8212db/start During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/compose/service.py", line 625, in start_container container.start() File "/usr/lib/python3/dist-packages/compose/container.py", line 241, in start return self.client.start(self.id, **options) File "/usr/lib/python3/dist-packages/docker/utils/decorators.py", line 19, in wrapped return f(self, resource_id, *args, **kwargs) File "/usr/lib/python3/dist-packages/docker/api/container.py", line 1095, in start self._raise_for_status(res) File "/usr/lib/python3/dist-packages/docker/api/client.py", line 263, in _raise_for_status raise create_api_error_from_http_exception(e) File "/usr/lib/python3/dist-packages/docker/errors.py", line 31, in create_api_error_from_http_exception raise cls(e, response=response, explanation=explanation) docker.errors.APIError: 500 Server Error: Internal Server Error ("b'driver failed programming external connectivity on endpoint saleor-platform_db_1 (1b57cb27e18e4e18fad1fde3f6bebb573260974514be140c7e4e0d74d663b7b0): Error starting userland proxy: listen tcp4 0.0.0.0:5432: bind: address already in use'") During handling of the above exception, … -
Use django hitcount module without a class
In the model below, I want to count the number of times an object is retrieved with hitcount module. class Stats(models.Model, HitCountMixin): user = models.ForeignKey("User", null=True, blank=True, on_delete=models.CASCADE) count = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) hit_count_generic =GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') I don't have any view function (class-based or function-based) that retrieves the objects. I only use get_or_create method to update or create the model object. So how can I use hit_count.hits_in_last to return the number of hits for today -
Which is the most commonly used way to implement user signup and login?
I'm starting out with Django development and I feel very confused and lost about all the ways you can implement the same thing. (or I may be just stupid) It all is very jumbled in my head right now (Class-based forms? Class-based views? Function-based views with Class-based forms? Custom HTML forms which are bound to Forms class and then etc etc etc...) So far these are all the intertwined options that I see and they confuse me a lot: Plain HTML forms which are then bound to the Form instance in views for validation (?). Every view is custom. (I like this one the best because I don't find any joy in using {{ form }} in templates, plus this one seem to be straightforward for me) Is forms.py not used when you implement forms that way? include('django.contrib.auth.urls') for login with custom templates (in which you when use {{ form }} and then something else for signup because there is no same built-in thing for signing up UserCreationForm but you have to extend it somehow if you want to add more fields (why are there built-in views for authentication but not for user creation btw?) Custom class-based forms if you … -
scanning qr code and display information in browser using django
I have a django web app where i have some qr code generator and now i want to create a view that can scan and open qr code in the browser.I have tried instacan but i didn't like it because i am not so good in javascript and i found this tutorial https://towardsdatascience.com/building-a-barcode-qr-code-reader-using-python-360e22dfb6e5 so my question is how can i use this tutorial to allow user to scan qr code from his device 2)open it in the browser (i mean the link) I will also appreciate any recommendation of other third app that can scan qr code.Thanks -
Django REST framework benchmarking [closed]
I want to know, how many requests can Django REST framework handle per second? And how much RAM does it use per session? -
How to change "transport" url in django celery config
I have django 3.2.7, celery 5.2.1, redis 3.5.3 I have next celery settings. (REDIS_PASSWORD) is env variable: CELERY_BROKER_URL = f'redis://:{REDIS_PASSWORD}@redis:6379/4' CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} CELERY_RESULT_BACKEND = f'redis://:{REDIS_PASSWORD}@redis:6379/1' CELERY_ACCEPT_CONTENT = ['application/json'] But when I start my docker-compose app, it shows me celery | --- ***** ----- celery | -- ******* ---- Linux-5.11.0-34-generic-x86_64-with-glibc2.31 2021-09-16 10:20:11 celery | - *** --- * --- celery | - ** ---------- [config] celery | - ** ---------- .> app: project:0x7f5cd0df0880 celery | - ** ---------- .> transport: redis://redis:6379/0 <==== NO CHANGES HERE celery | - ** ---------- .> results: redis://:**@redis:6379/1 celery | - *** --- * --- .> concurrency: 16 (prefork) celery | -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) celery | --- ***** ----- How can I set it? -
How to get user in Django forms?
Hello I have 2 different models: models.py class User(AbstractUser): class Roles(models.IntegerChoices): OWNER = 1, 'OWNER' BUYER = 2, 'BUYER' role = models.PositiveSmallIntegerField('ROLE', choices=Roles.choices, null=True, blank=True, default=None) other model class Book(core.BaseModel): book_number = models.PositiveIntegerField('Book number', validators=[ MinValueValidator(1), MaxValueValidator(MAX_TAG_NUMBER), ]) In model Book I have Book Form: forms.py class BookForm(AllBookForm): def __init__(self, user=None, *args, **kwargs): super().__init__(*args, **kwargs) self.user = user def clean(self): cleaned_data = super().clean() book_number = cleaned_data['book_number'] user = cleaned_data['user'] if self.user == User.Roles.OWNER: if book_number != None: raise forms.ValidationError(some error......) elif self.user == User.Roles.BUYER: if number == None: raise forms.ValidationError(some error.....) return cleaned_data I want to initialize User role in this form. How to initialize user Role in other model? Form. -
docker-compose with NGINX not serving Django at localhost
I'm trying to serve a simple Django app over NGINX using Docker Compose. I'm not really sure where the problem is coming from but the build was successful. Any idea why is not serving correctly? This is the setup: ├── app │ ├── templates │ ├── webapp │ │ ├── asgi.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── Dockerfile │ ├── Dockerfile.prod │ ├── entrypoint.sh │ ├── entrypoint.prod.sh │ └── requirements.txt ├── nginx │ ├── Dockerfile │ └── nginx.conf ├── .env ├── docker-compose.ci.yml ├── docker-compose.prod.yml └── docker-compose.yml app/webapp/settings.py: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = int(os.environ.get('DEBUG', default=0)) ALLOWED_HOSTS = ['localhost', '127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'webapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'webapp.wsgi.application' DATABASES = { 'default': { 'ENGINE': os.environ.get('SQL_ENGINE', 'django.db.backends.sqlite3'), 'NAME': os.environ.get('SQL_DATABASE', os.path.join(BASE_DIR, 'db.sqlite3')), 'USER': os.environ.get('SQL_USER', 'user'), 'PASSWORD': os.environ.get('SQL_PASSWORD', 'password'), 'HOST': os.environ.get('SQL_HOST', 'localhost'), 'PORT': os.environ.get('SQL_PORT', '5432'), } … -
how to get the unique result using django queryset?
I have something like this data in my DB. I want to get the result like class DateRange(models.Model): id = models.... date = models.... 1 is present from 01-01-2021 - 09-01-2021 2 is present from 01-02-2021 - 07-01-2021 1 is present from 01-03-2021 - 02-03-2021 How to achieve this using the django queryset. 01-01-2021 1 02-01-2021 1 03-01-2021 1 04-01-2021 1 05-01-2021 1 06-01-2021 1 07-01-2021 1 08-01-2021 1 09-01-2021 1 01-02-2021 2 02-02-2021 2 03-02-2021 2 04-02-2021 2 05-02-2021 2 06-02-2021 2 07-01-2021 2 01-03-2021 1 02-03-2021 1 -
Django No Reverse Match, Context is breaking my code
I've narrowed it down to when i add context to my return render(request) line is when my code breaks, but i can't figure out why. I'm not sure what errors to give or what parts of my code you need, but here you go. NoReverseMatch at /gallery/gallery Reverse for 'photo' with arguments '(2,)' not found. 1 pattern(s) tried: ['gallery/photo'] Request Method: GET Request URL: http://127.0.0.1:8000/gallery/gallery Django Version: 3.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'photo' with arguments '(2,)' not found. 1 pattern(s) tried: ['gallery/photo'] Exception Location: C:\Users\ScrillaGorilla\PycharmProjects\Mustache Website\venv\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\ScrillaGorilla\PycharmProjects\Mustache Website\venv\Scripts\python.exe Python Version: 3.8.6 Python Path: ['C:\Users\ScrillaGorilla\PycharmProjects\Mustache Website\mustache', 'C:\Users\ScrillaGorilla\AppData\Local\Programs\Python\Python38\python38.zip', 'C:\Users\ScrillaGorilla\AppData\Local\Programs\Python\Python38\DLLs', 'C:\Users\ScrillaGorilla\AppData\Local\Programs\Python\Python38\lib', 'C:\Users\ScrillaGorilla\AppData\Local\Programs\Python\Python38', 'C:\Users\ScrillaGorilla\PycharmProjects\Mustache Website\venv', 'C:\Users\ScrillaGorilla\PycharmProjects\Mustache ' 'Website\venv\lib\site-packages'] Server time: Thu, 16 Sep 2021 06:49:31 +0000 and this is my code. if that helps. this is my views.py file. from django.shortcuts import render from .models import Category, Photo from django.db import models # Create your views here. def photogallery(request): categories = Category.objects.all() photos = Photo.objects.all() context = {'categories': categories, 'photos': photos} return render(request, 'picturegallery/pictures.html', context) def viewPhoto(request, pk): photo = Photo.objects.get(id=pk) return render(request,'picturegallery/photo.html', {'photo': photo}) def addPhoto(request): return render(request,'picturegallery/ADD.html') and this is my models.py file. from django.db import models # Create your models here. class … -
Django-filter foreign key could not get in drop down
filter.py class StudentFilter(django_filters.FilterSet): # SchoolName = django_filters.ModelMultipleChoiceFilter(queryset=MasterSchool.objects.all()) class Meta: model = Student fields = ['StudentId', 'School', 'Division'] Here I have tried School__SchoolName, but it does not show the dropdown list. model.py class MasterSchool(models.Model): SchoolName=models.CharField(max_length=100, null=False, blank=False, unique=True) Active = models.BooleanField(default=True) class Meta: db_table='master_schools' class MasterDivision(models.Model): DivisionName=models.CharField(max_length=100, null=False, blank=False, unique=True) Active = models.BooleanField(default=True) class Meta: db_table='master_divisions' class Student(models.Model): StudentId=models.CharField(max_length=20, null=True, blank=True) StudentName=models.CharField(max_length=100, null=False, blank=False) Phone = models.CharField(verbose_name="Phone number", null=True, blank=True, max_length=10, validators=[validate_digit_length], default='1234567890') School = models.ForeignKey(MasterSchool, on_delete=models.CASCADE, null=True, blank=True, db_column='SchoolId') Division = models.ForeignKey(MasterDivision, on_delete=models.CASCADE, null=True, blank=True, db_column='DivisionId') StudentPhoto= models.ImageField( null=True, blank=True, default="default.png", upload_to='studentphoto/resgistred_photos/') PhotoMatrix=models.CharField(max_length=100, null=True, blank=True) class Meta: db_table='students' ordering = ['id'] view.py def StudentDetail(request): if(request.session.has_key('uid')): stud = Student.objects.all() schools = MasterSchool.objects.all() divisions = MasterDivision.objects.all() tableFilter = StudentFilter(request.GET, queryset=stud) students = tableFilter.qs page = request.GET.get('page', 1) paginator = Paginator(students, settings.PAGE_LIMIT) try: student_list = paginator.page(page) except PageNotAnInteger: student_list = paginator.page(1) except EmptyPage: student_list = paginator.page(paginator.num_pages) context = { 'student_list':student_list , 'students': students, 'tableFilter':tableFilter, 'root_url':settings.ROOT_URL, 'schools': schools, 'divisions': divisions } return render(request, 'web_api/student_details.html', context) html <form method="get" class="forms-sample" autocomplete="off" > {{tableFilter.form}} <button class="btn btn-primary" type="submit"><i class="fa fa-search" aria-hidden="true"></i> Search</button> </form> <div class="table-sorter-wrapper col-lg-12 table-responsive"> <table id="sortable-table-2" class="table table-striped"> <thead> <tr> <th>ID</th> <th>Student Name</th> <th>School Name</th> <th>Division</th> <th>Image</th> <th>Option</th> </tr> </thead> <tbody> {% for … -
i dont know why it has error with catalog/url.py?
https://github.com/Angelheartha/ruci this is my github the erroe is the below raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'catalog.urls' from 'C:\Users\user\PycharmProjects\pythonProject28\locallibrary\cat alog\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. i dont know the reazon because i already wrote in catalog/url.py path, and i wrote views.py what is the issue? -
Registration of an anonymous DRF user
I'm writing an API questionnaire on the Django Rest Framework, when passing the survey, I collect the id of an authorized user. But what about an anonymous user who has passed the survey, how do I get his unique id? -
expected str, bytes or os.PathLike object, not InMemoryUploadedFile?
I upload the excel file and insert the file in VBA_Parser of oletools but I am getting an error expected str, bytes or os.PathLike object, not InMemoryUploadedFile def upload(request): if request.method == 'POST': if request.FILES.get('document'): file = request.FILES['document'] result = [] vba_parser = VBA_Parser(file) # this is where error occur vba_modules = vba_parser.extract_all_macros() if vba_parser.detect_vba_macros(): result.append("Caution, macros has been found in your excel file.") vba_parser = VBA_Parser(file) # this is where error occur. I couldn't figure out how to solve the issue. -
How To get text editor in django frontend
In my front end of django templates i want to use a text field editor like How to achive something like this -
(Django) How to keep input values after form submit
I have the following view (truncated): def scheduler( request, year=None, month=None, event_id=None, delete_id=None, ): # Handle the event form if request.POST: event_form = EventForm(request.POST, instance=event) if event_form.is_valid(): event = event_form.save() dfkl_number = event_form.cleaned_data['dfkl_id'] Event.objects.filter( id=event.id, ).update(dfkl_number=dfkl_number) start_time = event_form.cleaned_data['start_time'] start_time = user_tz.localize(start_time.replace(tzinfo=None)) end_time = event_form.cleaned_data['end_time'] end_time = user_tz.localize(end_time.replace(tzinfo=None)) # if the end time is before the start time, try setting it to the same day if end_time < start_time: end_time = end_time.replace( year=start_time.year, month=start_time.month, day=start_time.day) # if the hour is also before, just use the start time if end_time < start_time: end_time = start_time Event.objects.filter( id=event.id, ).update(start_time=start_time) Event.objects.filter( id=event.id, ).update(end_time=end_time) return HttpResponseRedirect('/events') What I want is that whenever I submit a form (if request.POST) whether the form is valid or not, the values of the inputs do not disappear. scheduler.html: {% if event_id %} <form action="{% url 'cal:event' event_id %}" method="post" class="form needs-validation to-do-form"> {% else %} <form action="{% url 'cal:events' %}" method="post" class="form needs-validation to-do-form"> {% endif %} {% csrf_token %} {% bootstrap_form_errors event_form type='non_fields' %} {% bootstrap_field event_form.title layout='horizontal' size='small' %} {% bootstrap_field event_form.description layout='horizontal' size='small' %} {% bootstrap_field event_form.event_type layout='horizontal' size='small' %} {% bootstrap_field event_form.dfkl_id layout='horizontal' size='small'%} <!-- start time --> <div class="form-group {% if event_form.start_time.errors %}is-invalid{% … -
Django ModelForm update function returning error
I currently have a settings model for my Django app which saves a set of settings for the rest of the program to read from. I have tried to create a way to update these settings on the app, as per the below code. When the update button is clicked, however, the app returns the 'error':'Bad info' variable instead of updating the database. Does anyone know what could be causing it because I cannot seem to find any errors in the code? Views.py: def viewSettings(request, settings_pk): setting = get_object_or_404(SettingsClass, pk=settings_pk) if request.method == 'GET': form = SettingUpdateForm(instance=setting) return render(request, 'main/viewSettings.html', {'setting': setting, 'form':form}) else: try: form = SettingUpdateForm(request.POST, instance=setting) form.save() return redirect('settingsHome') except ValueError: return render(request, 'main/viewSettings.html', {'setting': setting, 'form':form, 'error':'Bad info'}) Models.py: class SettingsClass(models.Model): Complex = models.CharField(choices=complex_list , max_length = 22 ,default='1' , unique=True) #Trial Balance Year To Date Trial_balance_Year_to_date= models.BooleanField(default = False) tbytd_Include_opening_balances=models.BooleanField(default = False) tbytd_Only_use_main_accounts=models.BooleanField(default = False) tbytd_Print_null_values=models.BooleanField(default = False) tbytd_Print_description=models.BooleanField(default = True) tbytd_Print_account=models.BooleanField(default = True) tbytd_Sort_by_account_name=models.BooleanField(default = True) #Trial Balance Monthly Trial_balance_Monthly=models.BooleanField(default = False) tbm_Only_use_main_accounts=models.BooleanField(default = False) tbm_Print_null_values=models.BooleanField(default = False) tbm_Print_description=models.BooleanField(default = True) tbm_Print_account=models.BooleanField(default = True) tbm_Sort_by_account_name=models.BooleanField(default = True) #Income Statement Year To Date Income_Statement_Year_to_date=models.BooleanField(default = False) isytd_Only_use_main_accounts=models.BooleanField(default = False) isytd_Sort_by_account_name=models.BooleanField(default = True) isytd_Print_null_values=models.BooleanField(default = False) … -
how to process the return value of status=status.HTTP_400_BAD_REQUEST
In Django view, I have a view like this: @api_view(['POST']) def change_log(request): ...... return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Then call it: def post_to_change_log(): try: requests.post(INNO_API_URL + '/change_log_add/', json=log_data) except: In main, I need to check the return value of post_to_change_log(true of false) main(): if(post_to_change_log): return 200 else: return error+return value from post_to_change_log The question is, how could I process the return value in the 3 functions, then when error happened, I can return the serializer.errors, status=status.HTTP_400_BAD_REQUEST) in main? Thank you. -
Can't login to django admin page Server Error (500)
Good work everyone, I'm trying to build a website using django, nginx and gunicorn. Everything works fine on the django development server and I can also open the front page of my site using nginx. Since the project is the project of the company I work for, I had to censor some parts due to company policy. Thank you for your understanding However, repeatedly sudo systemctl restart gunicorn When I try to login to the admin page or use my own custom login page, I get a Server error (500) despite running the command. Can someone tell me what I'm doing wrong? settings.py: enter image description here nginx: enter image description here -
How to cache ClassBasedAPIViews in Django Rest Framework?
I am serving list of products in DRF and I tried to use cache in ClassBasedApiViews, urls.py path('',ProductListAPIView.as_view(), name='products') views.py: class ProductListAPIView(ListAPIView): permission_classes = [IsAuthenticated] queryset = Product.objects.all() serializer_class = ProductSerializer serializers.py: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' depth = 1 There is no function like def get() ... So I can not use conventional decorator before the function to cache. What I have tried is path('', cache_page(300)(ProductListAPIView.as_view()), name='products') this works. In case of multiple decorators path('', vary_on_headers('Authorization')(cache_page(300)(ProductListAPIView.as_view())), name='products') works as well. Is there a better way to use both decorators cache_page and vary_on_headers for ClassBasedAPIView?