Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I execute ModelAdmin.save_model asynchronously?
A Django-based website I'm building may occasionally need to run shell commands when initiated by an administrative user. Anticipating this, I decided it would be a good idea to write these processes to be asynchronous considering asyncio supports shells right out-of-the-box. I am executing these processes from the save_model() function of ModelAdmin, not an async view. My issue is when long-running processes are executed, the supposedly 'async' server gets completely hung-up on them and doesn't answer any other requests from clients until they are finished. I'm 100% certain this is because I'm running these processes in a sync function, albeit asynchronously (see below). I need to be able to tell the administrative user if the process they are running has succeeded or failed. I'm currently doing this through the messages API provided by Django. Here is the function executing the shell commands (Linux): import asyncio import sys async def run_subprocess(cmd: str) -> Tuple[int, bytes, bytes]: """Run a subprocess command asynchronously. Notes: This will execute the subprocess in a shell under the current user. Args: cmd (`str`): The command to run. Returns: exec_info (`tuple`): `(retcode, stdout, stderr)` from the subprocess for processing. """ # Create an execute the future try: proc … -
my form cannot receive request.files. I have a problem that user profile photo cannot be uploaded. img is sent trough request method properly
** views.py ** def create_user(request): if request.method == 'POST': form = UserProfile(request.POST) user_photo = PhotoUser(request.FILES,request.POST) #instance=request.user.userphoto print(request.FILES) * here i can see my image went trough * if form.is_valid(): form.save() else: form = UserProfile() user_photo = PhotoUser() return render(request,'user/user.html',{'form':form,'user_photo':user_photo}) ** urls.py** urlpatterns = [ path('admin/', admin.site.urls), path('', views.exe,name='exe'), path('books/', include('books.urls')), path('user/', include('user.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ** signals.py** @receiver(post_save,sender=User) def create_profile(sender, instance, created, **kwargs): if created: UserPhoto.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.userphoto.save() ** models.py ** class UserPhoto(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) img = models.ImageField(upload_to=image_directory_path,default='avatar.png',blank=True,null=True) def __str__(self): return self.user.username ** html** <form method="post" enctype="multipart/form-data" action="."> {% csrf_token %} {{form}} {{user_photo}} <input type="file" name="img" accept="image/*" id="id_img"> <input type="submit" value="Submit"> </form> forms.py class PhotoUser(forms.ModelForm): class Meta: model = UserPhoto fields = ['img'] MEDIA_ROOT = (BASE_DIR / 'media') MEDIA_URL = '/media/' so everything works ok but users profile images are not getting uploaded. signals are executed properly and 2 models are conected and my avatar.png is uploaded to every user and user is saved. if i upload user photo via admin it works properly -
Django-Storages with SFTP: GET-requests fail
I a trying to use django-storages to access my "Hetzner" Storage Box (https://www.hetzner.com/storage/storage-box) using SFTP which should hold media data, i.e. image files which users of my website can upload dynamically. The corresponding part of my settings.py file looks like: DEFAULT_FILE_STORAGE = 'storages.backends.sftpstorage.SFTPStorage' SFTP_STORAGE_HOST = 'username.your-storagebox.de' SFTP_STORAGE_ROOT = '/media' SFTP_STORAGE_PARAMS = { 'username': 'username', 'password': 'password', 'allow_agent': False, 'look_for_keys': False, } The strange thing is that, when the user uploads an Image, it is placed on the storage space as I can confirm using SFTP. But getting the images from the storage box fails, no Image is displayed. An excerpt from the console: [03/Sep/2021 22:34:01] "GET /media/filename.jpg HTTP/1.1" 404 1962 I could figure out that Django is still looking inside my MEDIA_DIR for the files. Againg, the corresponding part of my settings: MEDIA_DIR = 'media' MEDIA_ROOT = os.path.join(BASE_DIR, MEDIA_DIR) MEDIA_URL = '/media/' So in a nutshell: Using SFTP seems to be working for putting files into storage, but getting them again somehow fails. I am hoping for some help. Thanks in advance! -
Django Celery broken after moving secret key to environment variable
I'm working on a Django project that uses Celery for periodic tasks. For improved security, I moved Django's SECRET_KEY into an environment variable. The app ran fine, so Django was certainly able to find the environment variable and set the SECRET_KEY. But an unexpected side effect was that all the regularly occurring Periodic Tasks stopped triggering. I was able to run the tasks manually from Django Admin, so the Celery workers were still alive and well, but the tasks wouldn't trigger themselves like they usually do. The app settings and Celery config are both located in a directory called server. Here's the file structure: -server -__init__.py -celery.py -settings.py Before moving the secret key, it was in settings.py like this: SECRET_KEY = "secret" After moving to an environment variable, the line in settings.py was like this: SECRET_KEY = os.environ.get("SECRET_KEY") And here's the contents of celery.py, in case that's relevant: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") app = Celery("server") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() As soon as I moved the secret key out of the environment variable and back into settings.py, the tasks started firing again. I'm hoping to figure out why moving the secret key broke the periodic tasks so I can move the secret key back … -
Django Migrations stuck after executing in incorrect order
I made two changes to different models in my database. The first operations = [ migrations.DeleteModel( name='Settlement', ), ] And the second: operations = [ migrations.RemoveField( model_name='invoice', name='settlement_deducted', ), migrations.RemoveField( model_name='invoice', name='settlement_supporting', ), ] The issue is that they ran in this order, and the second one failed. The field being removed in the second migration uses the "Settlement" model, but since that model was deleted in the first migration it throws this error: ValueError: The field invoices.Invoice.settlement_deducted was declared with a lazy reference to 'accounting.settlement', but app 'accounting' doesn't provide model 'settlement'. The field invoices.Invoice.settlement_supporting was declared with a lazy reference to 'accounting.settlement', but app 'accounting' doesn't provide model 'settlement' Now when I try to do anything to fix it, it seems to just be stuck in that error state and continuously throws that same error. I have tried reverting the first migration to the previous migration on that model, adding that model back in and running makemigrations and then migrate so that the Settlement model exists again, and deleting the second migration (though it was never run anyway). All of these options are still throwing the same error. I am surprised that Django didn't catch this dependency issue … -
Reportlab in Django Application error - Forbidden (CSRF token missing or incorrect.)
I come from more of a data science background, but for fun I have been building a web application. I am new to django, javascript, and HTML, and it's a lot to wrap my head around - so if my coding appears unconventional I apologize. Feel free to offer any feedback. Within my application, I am trying to create a button on a webpage that does the following: Reads data input from an HTML table entered by the user in JavaScript (as an array). Using ajax, sends the data to a Python view. There, a function will be performed on the array, and the output will be returned to the user as a PDF generated by the reportlab library. Unfortunately, I continue to get the following error: Forbidden (CSRF token missing or incorrect.): /get_custom_bingo Here is the full error: Forbidden (CSRF token missing or incorrect.): /get_custom_bingo [03/Sep/2021 16:07:17] "POST /get_custom_bingo HTTP/1.1" 403 2513 [03/Sep/2021 16:07:17] "POST /pages/custom_bingo.html HTTP/1.1" 200 4320 [03/Sep/2021 16:07:17] "GET /static/JS/scripts.js HTTP/1.1" 304 0 I have tried to get it to go away, but nothing I can find online seems to be helping my current scenario. Does anybody know how to resolve this? (See the relevant sections … -
How to use 3 seperate filters on 1 page?
I have a page on which are 3 separate forms. With form 1 I can filter on name (typed in by user) with form method Post With form 2 I can filter on level (from list) with form method Get With form 3 I want to filter on school (from list) also with form method Get <!-- ### Filters ### --> <form method="POST" action="{% url 'spells' %}"> {% csrf_token %} <h1>Filter Options</h1> <div class="container ftable"> <div class="row"> <div class="input-group ml-5 col-md-4"> <label for="filter-search-name" class="form-labelz"><strong>Spell Name:&nbsp;&nbsp;&nbsp;&nbsp;</strong></label> <input class="form-control py-2 border-right-0 border" type="search" name="filter-search-name" id="filter-search-name" value autocomplete="off" placeholder="Give Spell Name or leave blank for all spells" spellcheck="false"> </div> <div class="col-12"> <button type="submit" class="btn btn-secondary">Filter</button> </div> </div> </div> </form> <form method="GET" action="{% url 'spells' %}"> <div class="container ftable"> <div class="input-group ml-5 mt-5 col-md-4"> <label for="filter-search-level" class="form-label"><strong>Spell Level: &nbsp;&nbsp;&nbsp;&nbsp;</strong></label> <select id="filter-search-level" name="filter-search-level" class="form-select"> <option selected value='Cantrip'>Cantrip</option> <option value='1st'>1st</option> <option value='2nd'>2nd</option> <option value='3rd'>3rd</option> <option value='4th'>4th</option> <option value='5th'>5th</option> <option value='6th'>6th</option> <option value='7th'>7th</option> <option value='8th'>8th</option> <option value='9th'>9th</option> </select> <div class="col-12"> <button type="submit" class="btn btn-secondary">Filter</button> </div> </div> </div> </form> <form method="GET" action="{% url 'spells' %}"> <div class="container ftable"> <div class=" input-group ml-5 mt-5 col-md-4"> <label for="filter-search-school" class="form-label"><strong>Spell School: &nbsp;&nbsp;</strong></label> <select id="filter-search-school" name="filter-search-school" class="form-select"> <option selected value='Abjuration'>Abjuration</option> <option value= … -
I have the problem: get() takes 1 positional argument but 2 were given, on django [closed]
class GetyPost(View): def get(request): informacion = NameUrl.objects.all() if len(informacion) > 0: datos = {'mensaje':'Conseguido', 'informacion':informacion} else: datos = {'mensaje':'No sonseguido'} return JsonResponse(datos) I don't know why the error TypeError at /api/todo/ get() takes 1 positional argument but 2 were given [1]: https://i.stack.imgur.com/dkDoa.png My url: from django.urls import path from .views import GetyPost urlpatterns = [ path('todo/', GetyPost.as_view(), name = 'GetyPost') ] -
Invalid block tag on line 29: 'endfor', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?
Something wrong with my .html template. Can't figure the error on line 29. Says Invalid block tag on line 29: 'endfor', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? {%extends 'mtunes/basic.html'%} {% block title%}Search{% endblock %} {% block body %} {% load static %} {% if query %} <h1 style="color: rgb(158, 60, 60); text-align: center;">Search Results for {{ query_str }}</h1> {% for i in query %} <div class="container"> <div class="card mb-3" style="max-width: 940px; padding-top: 0%;"> <div class="row no-gutters"> <div class="col-md-4"> <img src="/media/{{i.image}}" class="card-img" alt="..."> </div> <div class="col-md-8"> <div class="card-body"> <h5 class="card-title" style="color: green; font-weight: 550;">{{i.name}}</h5> <p class="card-text">Singer Name: {{i.singer}}</p> <p class="card-text">Tags: {{i.tags}}</p> <p class="card-text">Movie: {{i.movie}}</p> {% if user.is_authenticated %} <a href="/mtunes/songs/{{i.song_id}}"><button class="btn btn-outline-danger">Listen Song</button></a> </div> </div> </div> </div> {% endfor %} {% elif notfound %} <div class="row pt-3"> <!-- you can do a lot more here --> <h1> This song is not Available</h1> <span style='font-size:100px;'>&#128514;</span> </div> </div> </div> {% endif %} {% endblock %} -
Custom Django form validator doesnt render validation error on the frontend
I have a custom validator which should raise an error on the frontend for the user if the validation fails. However, I am not sure where and how to return this to the frontend. Right now it only shows in the terminal/Django error site on dev server: The view: def raise_poller(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = PollersForm(request.POST) # check whether it's valid: if form.is_valid(): # Make Validation of Choices Fields poller_choice_one = form.cleaned_data['poller_choice_one'] poller_choice_two = form.cleaned_data['poller_choice_two'] if ' ' in poller_choice_one or ' ' in poller_choice_two: raise ValidationError('Limit your choice to one word', code='invalid') return poller_choice_two # !! IDE says this is unreachable else: # process the remaining data in form.cleaned_data as required poller_nature = form.cleaned_data['poller_nature'] poller_text = form.cleaned_data['poller_text'] poller_categories = form.cleaned_data['poller_categories'] # Get the user created_by = request.user # Save the poller to the database p = Pollers(poller_nature=poller_nature, poller_text=poller_text, poller_choice_one=poller_choice_one, poller_choice_two=poller_choice_two, created_by=created_by) p.save() p.poller_categories.set(poller_categories) # redirect to a new URL: return HttpResponseRedirect('/') # if a GET (or any other method) we'll create a blank form else: form = PollersForm() return render(request, … -
Checkmarx Reflected XSS
I have a Django based API. After scanning my application with CheckMarx if showed that I have Reflected XSS volnurability here: user_input_data = json.loads(request.GET.get('user_input_data')) What I already tried: Used django.utils.html.escpae Used django.utils.html.strip_tags Used html.escape Used escapejson package Every time I run scanning, it finds stored XSS at exactly this location -
Validating string for possible space returns error in Django form even though there's no space
I have two fields in my Django form where I want the user to insert exactly one word. So to have some validation in the view i created the following validator (idea is to search for spaces): Views.py [..] if ' ' in poller_choice_one or poller_choice_two: raise ValidationError(('Limit your choice to one word'), code='invalid') else: [..] To make it more robust I added the strip option to the FormFields to be validated: # Poller Choices poller_choice_one = forms.CharField(label='Choice one', max_length=20, strip=True) poller_choice_two = forms.CharField(label='Choice two', max_length=20, strip=True) I tried like a bunch of inputs from single digits to single chars etc., it always raises the validation error -
Custom Functions in Django Model
I am building a FedEx API in django and currently have a Shipment class which has methods such as create_shipment(), delete_shipment()... I have stored this shipment class in a separate file. I created a Shipment model inside my models.py and I noticed that it seems inefficient to have two different Shipment classes (one for the django model and the other defined in a separate file). I want to know if it would be considered bad practice to define the functions of the API inside the same model class. I want process_shipment() to be called by the model and then insert the instance into the database. Note that to do this I'd need to overwrite the init method of the parent model class which I hope will be ok. -
Django Rest Framework + Serializers + Vue.js, Reset Password Functionality
I am trying to create a reset password functionality, but I can't find a good tutorial that explains how to do that with DRF and Vue.js. I am using serializers to pass the data, so there are no html views involved. What is the most efficient way of creating that Reset Password Functionality? I am creating new users via /api/v1/users/. Any ideas are very appretiated. Thank you! -
I have problem with Pylance when my VSCode update
"authenticate" is not accessed Pylance ?? Photo pylance extencion is installed -
"detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)"
I created a simple Django REST framework and I am able to GET. However, when trying to POST I receive the following: "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" I have attached my models, urls, views and serializers below. My Models.py from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()]) class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) class Meta: ordering = ['created'] serializers.py class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = '__all__' #fields = ['id', 'title', 'code', 'linenos', 'language', 'style'] urls.py urlpatterns = [ path('snippets/', views.snippet_list), path('snippets/<int:pk>/', views.snippet_detail), ] urlpatterns = format_suffix_patterns(urlpatterns) Views.py from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from snippets.models import Snippet from snippets.serializers import SnippetSerializer from rest_framework.decorators import api_view from rest_framework import status from rest_framework.response import Response @api_view(['GET','POST']) @csrf_exempt def snippet_list(request,format=None): """ List all code snippets, or create a new snippet. """ if … -
i dont knw why it cant reflect admin.py if there is not any mistake in setting.py?
https://github.com/Angelheartha/tera this is my github i dont have idea why after writting at admin.py it cant reflect as if i didnt write any code when i do http://127.0.0.1:8000/admin ? i thought because i missed something at setting.py but it seems not the case... i dont know what is the problem here i did python manage.py migrate but not change -
Django mysql (mariadb Server version: 5.5.68) database not working with wsgi.py
I have a working django application that works fine in the development server. As soon as I try to use it as a production server application using Apache and wsgi.py it gives me errors. With MYSQL I get the following errors: [Fri Sep 03 13:27:22.424881 2021] [wsgi:error] [pid 15424] [remote 172.30.0.54:49967] import MySQLdb as Database [Fri Sep 03 13:27:22.424920 2021] [wsgi:error] [pid 15424] [remote 172.30.0.54:49967] File "/home/bakert/.local/share/virtualenvs/trackx_proj_master-nygxcPTP/lib/python3.9/site-packages/MySQLdb/__init__.py", line 24, in <module> [Fri Sep 03 13:27:22.424952 2021] [wsgi:error] [pid 15424] [remote 172.30.0.54:49967] version_info, _mysql.version_info, _mysql.__file__ [Fri Sep 03 13:27:22.424982 2021] [wsgi:error] [pid 15424] [remote 172.30.0.54:49967] NameError: name '_mysql' is not defined When I do a pip freeze - My requirements file looks like this: asgiref==3.3.4 dj-database-url==0.5.0 dj-email-url==1.0.2 Django==3.1.12 django-cache-url==3.2.3 django-crispy-forms==1.9.2 django-ranged-response==0.2.0 django-simple-captcha==0.5.14 environs==8.0.0 marshmallow==3.12.1 mod-wsgi-httpd==2.4.48.1 mysqlclient==2.0.1 pathlib==1.0.1 Pillow==8.1.0 python-dotenv==0.17.1 pytz==2021.1 six==1.15.0 sqlparse==0.4.1 So - it seems like the virtual environment should know about mysql - but it doesn't seem to find it. I tried reverting back to sqlite - just to try it - and it complained about sqlite version... so it seems something's not right in the virtual environment that wsgi.py is trying to use. My wsgi.py looks like this: import os,sys sys.path.append('/var/www/trackx_proj/trackx_root') sys.path.append('/usr/lib64/mysql') sys.path.append('/home/bakert/.local/share/virtualenvs/trackx_proj_master- nygxcPTP/lib/python3.9/site-packages/MySQLdb') sys.path.append('/home/bakert/.local/share/virtualenvs/trackx_proj_master- nygxcPTP/lib/python3.9/site-packages') from django.core.wsgi … -
Modal content not updating
I have a pretty basic JS modal right now, but the content is not loading from the modal.html call. Here is my function: var modal = $('#userModal') var button = $('submit') button.on('click', function(event) { var str = "Testing content" $("#modal_body").html(str) modal.modal("show") The modal_body is a paragraph with the ID "modal_body". The modal is opening but the variable "str" content is not populating. Am a beginner to Ajax working in a Django Jinja2 template. Thank you! -
Django fails to process ManyToMany form field within view to create and save new model instance
I have two Models with a ManyToMany relationship. In my view I want to process the user input of the MultipleChoicesField and assign the selected choices to the Poller object. It raises the following error: Direct assignment to the forward side of a many-to-many set is prohibited. Use poller_categories.set() instead. Models.py class Categories(models.Model): poller_category = models.CharField(max_length=30) poller_category_id = models.IntegerField(default=0) def __str__(self): return str(self.poller_category) class Pollers(models.Model): [..] # Poller Category poller_categories = models.ManyToManyField(Categories) def __str__(self): return str(self.poller_id) Forms.py class PollersForm(forms.Form): [..] # Poller Tags poller_categories = forms.ModelMultipleChoiceField(queryset=Categories.objects.all()) views.py def raise_poller(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = PollersForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required poller_nature = form.cleaned_data['poller_nature'] poller_text = form.cleaned_data['poller_text'] poller_choice_one = form.cleaned_data['poller_choice_one'] poller_choice_two = form.cleaned_data['poller_choice_two'] poller_categories = form.cleaned_data['poller_categories'] # Get the user created_by = request.user # Save the poller to the database p = Pollers(poller_nature = poller_nature, poller_text = poller_text, poller_choice_one = poller_choice_one, poller_choice_two = poller_choice_two, poller_categories = poller_categories, # here seems to be my issue? created_by = created_by) p.save() # redirect to a new … -
Datetime field interfering with Django order_by in annotate query
I'm currently working with three models, Routes, Attendances and Containers. Each route has two attendances and each attendance has one container, so I'm annotating on the number of routes for each container. I managed to almost get the result I want but I also need the created_at field in my Routes model, however if I call it, the sorting does not work anymore. Models class Container(models.Model): license_plate = models.CharField(max_length=255) container_number = models.IntegerField(default=-1) container_type = models.BooleanField(default=True) # True para calientes, False para fríos created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.license_plate class Meta: db_table = "trucks_containers" class Attendance(models.Model): IN = 'in' OUT = 'out' CHECKIN_TYPES = [ (IN, 'in'), (OUT, 'out') ] type = models.CharField(max_length=10, choices=CHECKIN_TYPES) closed = models.BooleanField(default=False) damaged = models.BooleanField(default=False) datetime = models.DateTimeField() is_crashed_container = models.BooleanField(default=False) is_crashed_truck = models.BooleanField(default=False) has_solar_panel = models.BooleanField(default=False) truck = models.ForeignKey(Truck, on_delete=models.CASCADE, null=True) container = models.ForeignKey(Container, on_delete=models.CASCADE) gate = models.ForeignKey(Gate, on_delete=models.CASCADE) snapshot = models.ForeignKey( general_models.Snapshot, on_delete=models.SET_NULL, null=True ) created_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = "trucks_attendances" class Route(models.Model): start_attendance = models.ForeignKey( Attendance, related_name='start_attendance', on_delete=models.CASCADE ) end_attendance = models.ForeignKey( Attendance, related_name='end_attendance', on_delete=models.CASCADE ) created_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = "trucks_routes" Almost correct result Query used: containers_routes = truck_models.Route.objects\ .values('end_attendance__container__id', 'end_attendance__container__container_number', 'end_attendance__container__license_plate')\ .annotate(completed_routes=Count('end_attendance__container__id'))\ .order_by('-completed_routes') Result: <QuerySet [{'end_attendance__container__id': … -
How to pass in the user in the request for Auth0? (React Frontend and Django Backend)
I am creating a web application and trying to use Auth0 for my user authentication. I want to secure some endpoints where the user must be logged in to be able to successfully access an endpoint. I followed this tutorial on setting up Django with Auth0 and it went perfectly. (https://auth0.com/docs/quickstart/webapp/django/01-login) However though I want to be able to signin from the frontend (React) to be able to access the secured endpoints on my Django backend. This is what I have for my endpoint that I'm testing. views.py from django.http import JsonResponse def test(request): user = request.user if user.is_authenticated: return JsonResponse({ 'outcome': 'success'}) else: return JsonResponse({ 'outcome': 'failure'}) This endpoint is called path('test/', views.test), in my urls.py. When I login using the templates and then try to access the endpoint it works perfectly. templates/index.html <div class="login-box auth0-box before"> <img src="https://i.cloudup.com/StzWWrY34s.png" /> <h3>Auth0 Example</h3> <p>Zero friction identity infrastructure, built for developers</p> <a class="btn btn-primary btn-lg btn-login btn-block" href="/login/auth0">Log In</a> </div> However though the issue is when I try logging through the my React frontend. I can't seem to get the JsonResponse to be 'success' and keep on getting 'failure'. fetch('test/') .then(response => response.json()) .then(data => console.log(data)); I can see that from … -
Filter output items of reverse relations in Django
I have these models: class Author(models.Model): name = models.CharField(max_length=50) class Book(models.Model): name = models.CharField(max_length=150) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books") published_at = models.DateField() And this is my query: Author.objects.filter(books__published_at__ragne=[date_from, date_to]).annotate(books_count=Count('books')) The query's output will be sent to below serializer(inherit django rest framework serializer): class AuthorSerializer(serializers.ModelSerializer): books_count= serializers.IntegerField(read_only=True) books = serializers.StringRelatedField(many=True) class Meta: model = Author fields = ['id', 'name', 'books_count', 'books'] The AuthorSerializer output will be all authors who have at least one book published in specified range, with the number of books published by each author, and also the string representation of all books of each author. The books__published_at__ragne filter affect output authors and books count, but it won't affect books of authors. I mean for each author, all books are returned, not only books which are published in specified range. How can i also filter books with that specified parameters? -
How to also ignore warnings in pytest about removal in Django41?
https://docs.pytest.org/en/6.2.x/warnings.html#deprecationwarning-and-pendingdeprecationwarning teaches me to use this in my pytest.ini filterwarnings = ignore:.*U.*mode is deprecated:DeprecationWarning but i still get warnings that are like this: ../usr/local/lib/python3.8/dist-packages/django/apps/registry.py:91 /usr/local/lib/python3.8/dist-packages/django/apps/registry.py:91: RemovedInDjango41Warning: 'pattern_library' defines default_app_config = 'pattern_library.apps.PatternLibraryAppConfig'. Django now detects this configuration automatically. You can remove default_app_config. app_config = AppConfig.create(entry) I would like to suppress this as well, as this is also a third party library of which I have no control over even though i have laready submitted a PR to update it. What should i add to my pytest.ini? -
add serializer methid field to a generics.ListAPIView
class PermitListSerializer(serializers.ModelSerializer): def __init__(self,page=None, *args, **kwargs): self.page = page super().__init__(*args, **kwargs) page_number = serializers.SerializerMethodField() userfullname = serializers.SerializerMethodField() show_subsystem = serializers.SerializerMethodField() def get_show_subsystem(self,obj): return obj.subsystem.name def get_userfullname(self, obj): return obj.issuer.get_full_name() if obj.issuer.get_full_name() else 'Unknown' def get_page_number(self, obj): return self.page class Meta: model = Permit fields = '__all__' my view: class c_receive_tm(generics.ListAPIView): serializer_class = PermitListSerializer filter_backends=(filters.SearchFilter,) search_fields=('name', 'description') def get_queryset(self): return Permit.objects.all().order_by('-id') by I get an error: Object of type Permit is not JSON serializable if i remove all SerializerMethodField its works I need this additional fiels