Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
a technique for live updates other than firebase push notification fro my mobile flutter app
I was using the fcm push notification to get the real time updates(the update in my device,ie. whether the lights are manually off or on in the device etc..)get happen in the mobile application.But the push notifications are sometimes found missing and my app started showing sync issues to the real time. It could be very helpfull for me if anyone can suggest a better method to implement this process. I had heard about enabling a socket connection but dont know much about that. Thankyou -
Django Which model field to add an text editor when clicking on it?
I have my Django model and would like to add a text editor field. This text editor is representing like an Icon and when clicking on it, user must see it open and write any comment. I am not talking about django text input field where user can directly add comment in the form. I want something like that (in red circle). -
Why the login_requried decorator doesn't work after I log out from the account?
Working on a project using Django 3.2, I have been added new features to the project by adding a login/register page for the user. To do that, I used which I used this library provided by Django from django.contrib.auth.models import User, and as well in the views I used from django.contrib.auth import authenticate, login, logout library. After I finished the login/register successfully I decided to do the authenticate the home page for the reason that the user without an account can't have access to the home page. To do that I used the decorators from django.contrib.auth.decorators import login_required, and I used it on every view that I want to authenticate for the unregistered user. To understand it better will show the code below: views.py from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.utils import timezone from django.db.models import Count from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.contrib import messages from .models import * from .models import __str__ from .forms import CreateUserForm # Create your views here. @login_required(login_url='login/') def home(request): count_item = todo.objects.count() all_items = todo.objects.all().order_by("created") context = {'all_items': all_items, 'count_item':count_item} return render(request, 'html/home.html', context) @login_required(login_url='login/') def … -
Django nested serializers not returning what I want
I'm relatively new to Django and I'm working on an application that has me scratching my head. I have two models defined as follows: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) name = models.CharField(_('name'), max_length=50, blank=False) surname = models.CharField(_('surname'), blank=True, max_length=50) phone_number = models.CharField(validators=[phone_validator], max_length=16, blank=True) class History(models.Model): hist_id = models.AutoField(primary_key=True) user = models.ForeignKey( User, on_delete=models.CASCADE ) timestamp = models.DateTimeField(auto_now=False, auto_now_add=False) actions = models.JSONField(default=dict) traces = models.JSONField(default=dict) I would like to obtain a list of all users, and for each user I want all the History objects as a list. Here is the View I've created: class HistoryQuery(ListAPIView): serializer_class = HistorySerializer def get_queryset(self): return User.objects.all() and here is the serializer that I'm trying to use: class HistorySerializer(serializers.Serializer): class HistorySummarySerializer(serializers.Serializer): class Meta: model = History fields = ['hist_id', 'user'] history = HistorySummarySerializer(many=True, read_only=True) class Meta: model = User fields = ['history'] With this setup, I'm getting an array with length equal to the number of users that I have in my database, but each of its elements is empty. I cannot figure out what I'm doing wrong, so any help is appreciated. Should I reverse my logic and query the History model instead? If it is relevant, there are around … -
How to reverse filter based on latest entry in Django
I have a customer table and customer order table as below class Customer(models.Model): name = models.CharField() class CustomerOder(models.Model): customer = models.ForiengKey(Customer) item = models.CharField() datetime_of_purchase = models.DateField() Sample database entry Table: Customer id name 1 A 2 B 3 C Table: CustomerOder id customer item datetime_of_purchase 1 A item_3 2021-11-10 10:00:00 2 A item_2 2021-11-11 10:00:00 3 B item_1 2021-11-11 10:00:00 4 A item_1 2021-11-12 10:00:00 5 B item_2 2021-11-12 10:00:00 6 C item_1 2021-11-13 10:00:00 Suppose i need to filter customer whose latest purchase is 'items_1' so the sample after filtering should get only Customer 'A' and 'C' whose latest purchase is 'item_1' Sample: <QuerySet [<Customer: A>, <Customer: C>]> -
Django Rest Framework NoReverseMatch not a valid view function or pattern name
First some context : Models class : class Property(models.Model, AbstractUsagesLinked, AbstractErrorsFinder, InsurableMixin): type = models.ForeignKey(PropertyType, verbose_name=_('type de lot'), null=True, blank=True, related_name='properties_set', on_delete=models.CASCADE) # other fields Serializers class : class PropertySerializer(serializers.HyperlinkedModelSerializer, FlexFieldsModelSerializer): type = serializers.HyperlinkedRelatedField(view_name="api:propertytype-detail", read_only=True) # add hyperlink reference # others fields class Meta: model = Property fields = [field.name for field in model._meta.fields] expandable_fields = { 'type': (PropertyTypeSerializer, {'many': False}), # others fields } class PropertyTypeSerializer(serializers.HyperlinkedModelSerializer, FlexFieldsModelSerializer): class Meta: model = PropertyType fields = [field.name for field in model._meta.fields] Views class : @permission_classes((Check_API_KEY_Auth, )) class PropertyDetail(RetrieveAPIView): queryset = Property.objects.all() serializer_class = PropertySerializer pagination_class = CustomPagination @permission_classes((Check_API_KEY_Auth, )) class PropertyTypeDetail(RetrieveAPIView): queryset = PropertyType.objects.all() serializer_class = PropertyTypeSerializer pagination_class = CustomPagination Urls : api.urls.py : urlpatterns = [ # lots of path path('property/', views.PropertyList.as_view(), name="property-list"), path('property/<int:pk>/', views.PropertyDetail.as_view(), name="property-detail"), path('propertytype/', views.PropertyTypeList.as_view(), name="propertytype-list"), path('propertytype/<int:pk>/', views.PropertyTypeDetail.as_view(), name="propertytype-detail"), main.urls.py : urlpatterns = [ # lots of path url(r'^api/', include((api.urls, 'api'), namespace='api')), ] When i request property i get : django.urls.exceptions.NoReverseMatch: Reverse for 'propertytype-detail' not found. 'propertytype-detail' is not a valid view function or pattern name. django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "propertytype-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on … -
Populate single dropdown from two tables in django python sqlite
I am new to Django, Please provide me any method to do this. Thanx in Advance. -
Missing Django core translations
I am trying to translate django core strings which for my language are untranslated in the original .po file. When I add them to my own .po file and translate them, the system works fine. The problem comes every time I use the makemessages command, since the generator interprets that those text strings have been deleted and comments them in the .po file. Can I hand generate a file that contains the translations and is not affected by the makemessages command? On the other hand, is it possible to tell him not to comment on the deleted lines? -
Django ORM: How to filter on many-to-many relation without filtering related objects
I have some Django models like following: class Film: genre = models.ManyToManyField("Genre", blank=True) class Genre(TimeStampedModel): name = models.CharField(max_length=50, blank=False) slug = AutoSlugField(max_length=55, unique=True, populate_from="name") Now, I want to select all films which are associated with the genre "Theatre" and get a list of all their associated genres: In [1]: from apps.base.models import Film, Genre In [2]: qs = Film.objects.filter(genre__slug='theatre') In [3]: set(qs.values_list("genre__slug", flat=True)) Out[3]: {'theatre'} However, this is not the result that I want. Looking at the genres of the first film returned as part of the queryset, we can see more genres: In [4]: set(qs[0].genre.all().values_list("slug", flat=True)) Out[4]: {'dance', 'education', 'theatre', 'video-recording'} How can I efficiently filter the films to those associated with the genre "Theatre" and retrieve their associated genres? -
What is the best way to embed videos with Google amp-story player in django
Am currently working on an app that i would want to add google Amp-story player to embed videos, but somehow the google amp play wont render the video or images from the database but rather when i pass a link to the video source which is not from my data base it works. I have tried writing custom template tag and filter to handle the the images but still I find it a challenge to get it to work. Is there a possible way to go out this. {% load ampimage_tag %} <head> <script async src="https://cdn.ampproject.org/amp-story-player-v0.js" onload="initializePlayer()" ></script> <link href="https://cdn.ampproject.org/amp-story-player-v0.css" rel="stylesheet" type="text/css" /> <script> // JS let player; function events() { console.log( "iframes", document .querySelector("amp-story-player") .shadowRoot.querySelectorAll("iframe") ); player.addEventListener("storyEnd", (data) => console.log("storyEnd", data) ); player.addEventListener("amp-story-player-close", () => { console.log("Close button clicked"); }); } function initializePlayer() { player = window.document.querySelector("amp-story-player"); if (player.isReady) { // Player loaded. Run e.g. animation. console.log("isready"); events(); return; } player.addEventListener("ready", () => { // Player loaded. Run e.g. animation. console.log("ready"); events(); }); } function show(story) { player.show(story); } function nextStory() { player.go(1); } </script> </head> <body> <button onclick="console.log( 'iframes', document.querySelectorAll('amp-story-player iframe') );" > add story </button> <button onclick="show('https://merci-handy.my.join-stories.com/collection-la-bouche-avis-kQoT9uov/',false)" > First story </button> <button onclick="show('https://webstoriesinteractivity-beta.web.app/arts-quizzes.html',false)" > Second story </button> … -
Integrate OAuth 2.0 prompt property with Django MS Graph
I'm using Microsoft Graph to manage Azure authentication on my django app. The thing is that it automatically logs the user if he previously used an account in his browser, so I want to use the property "prompt=select_account" from OAuth 2.0 but didn't find any doc on how to integrate this. Currently the app works with a slightly modified version of MS Graph tutorial with the following yml settings file: app_id: "xxxxxx" app_secret: "xxxxxx" redirect: "http://localhost/callback" scopes: - user.read authority: "https://login.microsoftonline.com/xxxx-xxxx-xxxx-xxxx-xxx" I tried to add it as an option in this yml file : prompt: "select_account" Also tried in the authority url : authority: "https://login.microsoftonline.com/xxxx-xxxx-xxxx-xxxx-xxx&prompt=select_account" Any link to follow or direct answer would be greatly appreciated, Thanks ! -
How to solve problem with admin panel when using gunicorn
How I can solve problem with django admin panel when using gunicorn. My admin panel doesn't support static files Here what i have in terminal web_1 | Not Found: /static/admin/css/base.css web_1 | Not Found: /static/admin/css/nav_sidebar.css web_1 | Not Found: /static/admin/js/nav_sidebar.js web_1 | Not Found: /static/admin/css/dashboard.css web_1 | Not Found: /static/admin/css/responsive.css web_1 | Not Found: /static/admin/css/fonts.css web_1 | Not Found: /static/admin/css/base.css web_1 | Not Found: /static/admin/css/nav_sidebar.css web_1 | Not Found: /static/admin/css/dashboard.css web_1 | Not Found: /static/admin/css/responsive.css web_1 | Not Found: /static/admin/js/nav_sidebar.js web_1 | Not Found: /static/admin/css/base.css web_1 | Not Found: /static/admin/css/nav_sidebar.css web_1 | Not Found: /static/admin/css/dashboard.css web_1 | Not Found: /static/admin/css/responsive.css web_1 | Not Found: /static/admin/js/nav_sidebar.js web_1 | Not Found: /static/admin/css/base.css web_1 | Not Found: /static/admin/css/nav_sidebar.css web_1 | Not Found: /static/admin/css/dashboard.css web_1 | Not Found: /static/admin/css/responsive.css web_1 | Not Found: /static/admin/js/nav_sidebar.js web_1 | Not Found: /static/admin/css/base.css web_1 | Not Found: /static/admin/css/nav_sidebar.css web_1 | Not Found: /static/admin/css/dashboard.css web_1 | Not Found: /static/admin/css/responsive.css web_1 | Not Found: /static/admin/js/nav_sidebar.js -
Django Rest Api - Password does not change
I use the built-in methods to change the Password of a user via a POST from the frontend, but the password does not update when calling the view. I do get an http 200 back though. Any advice ? views.py from rest_framework import status from rest_framework import generics from rest_framework.response import Response from django.contrib.auth.models import User from .serializers import ChangePasswordSerializer from rest_framework.permissions import IsAuthenticated class ChangePasswordView(generics.UpdateAPIView): serializer_class = ChangePasswordSerializer model = User permission_classes = (IsAuthenticated,) def get_object(self, queryset=None): obj = self.request.user return obj def update(self, request, *args, **kwargs): self.object = self.get_object() serializer = self.get_serializer(data=request.data) if serializer.is_valid(): # Check old password if not self.object.check_password(serializer.data.get("old_password")): return Response({"old_password": ["Wrong password."]}, status=status.HTTP_400_BAD_REQUEST) # set_password also hashes the password that the user will get self.object.set_password(serializer.data.get("new_password")) self.object.save() response = { 'status': 'success', 'code': status.HTTP_200_OK, 'message': 'Password updated successfully', 'data': [] } return Response(response) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # Create your views here. serializers.py from rest_framework import serializers from django.contrib.auth.models import User class ChangePasswordSerializer(serializers.Serializer): model = User old_password = serializers.CharField(required = True) new_password = serializers.CharField(required = True) -
"post_save_user_model_receiver" is not defined
"post_save_user_model_receiver" is not defined I'm un able to use post_save_user_model_receiver do help me to solve the below problem -
Guys, there is a problem with template. My task is create a fliter in dropdown menu and last problem in templates
My models: class Category(ModelWithSlugMixin): class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' slugifying_field_name = 'title' title = models.CharField(verbose_name='Наименование', null=True, max_length=255) slug = models.SlugField(verbose_name='Slug', unique=True, null=True, blank=True, unique_for_date='publish') publish = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('article:category', kwargs={'category_slug': self.slug}) class Article(ModelWithSlugMixin): class Meta: verbose_name = 'Статья' verbose_name_plural = 'Статьи' slugifying_field_name = 'title' category = models.ForeignKey(Category, on_delete=models.SET_NULL, related_name='category', blank=False, null=True) title = models.CharField(verbose_name='Заголовок', max_length=255, null=True) slug = models.SlugField(verbose_name='Slug', unique=True, null=True, blank=True, unique_for_date='publish') text = RichTextUploadingField(verbose_name='Текст', null=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='articles') publish = models.DateTimeField(default=timezone.now) created_at = models.DateField(auto_now_add=True) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('article:article-detail', kwargs={'slug': self.slug} My view: class ArticleView(ListView): model = Article template_name = 'pages/analysis.html' context_object_name = 'articles' queryset = Article.objects.all() def get_context_data(self, **kwargs): context = super(ArticleView, self).get_context_data(**kwargs) # context['category'] = Category.objects.all() context['article_image'] = Photo.objects.all() context['article_pictures'] = Collage.objects.all() context['article_videos'] = Video.objects.all() return context class ArticleCategoryView(ListView): model = Article template_name = 'pages/analysis.html' context_object_name = 'articles' def get_queryset(self): return Article.objects.filter(category__slug=self.kwargs['category_slug']) def get_context_data(self, **kwargs): context = super(ArticleCategoryView, self).get_context_data(**kwargs) context['cat_selected'] = context['articles'][0].category_id return context Mu url: path('category/<slug:category_slug>/', ArticleCategoryView.as_view(), name='category'), And finally my template structure: <h3 class="widget-title">Categories</h3> <div class="form-group select-group"> <label for="category" class="sr-only">Select Category</label> <select id="category" name="category" class="choice empty form-control"> <option value="" disabled="" selected="" data-default="">Выбери категорию </option> <option>First category</option> <option>Second category</option> <option>Third category</option> … -
query set in django
i really need help with this: I have 3 models say User,Item and Comment where User is a foreign key in Item and Item is a foreign key in Comment. i want to get all comment belonging to a particular user in my view, how do i achieve it. bellow is are my model class User(models.Model): name= models.CharField(max_length=200,null=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Item(models.Model): user = models.ForeignKey(User, on_delete=CASCADE) name= models.CharField(max_length=200,null=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Comment(models.Model): user = models.ForeignKey(Item, on_delete=CASCADE) name= models.CharField(max_length=200,null=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name -
Why the login_requried decorator doesn't work after I login to an account?
Working on a project using Django 3.2, I have been added new features to the project by adding a login/register page for the user. To do that, I used which I used this library provided by Django from django.contrib.auth.models import User, and as well in the views I used from django.contrib.auth import authenticate, login, logout library. After I finished the login/register successfully I decided to do the authenticate the home page for the reason that the user without an account can't have access to the home page. To do that I used the decorators from django.contrib.auth.decorators import login_required, and I used it on every view that I want to authenticate for the unregistered user. To understand it better will show the code below: views.py from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.utils import timezone from django.db.models import Count from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.contrib import messages from .models import * from .models import __str__ from .forms import CreateUserForm # Create your views here. @login_required(login_url='login/') def home(request): count_item = todo.objects.count() all_items = todo.objects.all().order_by("created") context = {'all_items': all_items, 'count_item':count_item} return render(request, 'html/home.html', context) @login_required(login_url='login/') def … -
django-cloudinary-storage must supply api_key
I'm using django-3.2.6, django-cloudinary-storage-0.3.0 and python-3.9.7 earlier the cloudinary was detecting API_KEY, but I don't know what happened now. settings.py DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' CLOUDINARY_STORAGE = { 'CLOUD_NAME': os.environ.get("CLOUD_NAME"), 'API_KEY' : os.environ.get("CLOUDINARY_API_KEY"), 'API_SECRET': os.environ.get("CLOUDINARY_API_SECRET"), } I tried to print the values i passed on CLOUDINARY_STORAGE, and it loads all .env succesfully, but django_cloudinary_storage isn't detecting these variables logs Environment: Request Method: POST Request URL: http://localhost:8000/admin/api/news/add/ Django Version: 3.2.6 Python Version: 3.9.7 Installed Applications: ['whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'api.accounts', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'django_filters', 'taggit', 'drf_yasg2', 'corsheaders', 'cloudinary', 'cloudinary_storage'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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'] Traceback (most recent call last): File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/contrib/admin/options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 232, in inner return view(request, *args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1657, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/joker/Desktop/Codes/Web/trendinganime/new/env/lib/python3.9/site-packages/django/contrib/admin/options.py", … -
i am getting a hard time to impement two factor authentication using the totp ,i want the user after normal login to be prompted the token login page
the function bellow is the one i was trying to implement the logic behind the two factor authentication ''' def login_view(request): if request.user.is_authenticated: return redirect('/dashboard') if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] cache.set('email',email) fact = User.objects.filter(email=email).values('username') username = fact[0]['username'] username = username.encode(encoding='utf-8') password = password.encode(encoding='utf-8) username = username.strip(b"b'") print(username) print(str(password)) user = authenticate(request, username=username, password=password) cache.set('user',user) if user is None: context = {'error':'incorrect username or password'} return render(request, 'index.html' , context) print(username) is_enrolled = enrolled(request) if not is_enrolled.json(): login(request, user) return redirect('/dashboard') return render(request, 'tokenlogin.html') return render(request, 'index.html') ''' also the function below i wrote to check if the user has enrolled for two factor authentication ''' def isenrolled(request): email = request.user.email res = requests.post( 'http://0.0.0.0:8000/api/users/email/', data={ 'account_name': email, }, headers={ 'Authorization': 'Bearer {0}'.format(ACCESS_TOKEN), 'Content-Type': 'application/x-www-form-urlencoded' } ) return res #This function to check MFA enabled when user before login def enrolled(request): email = request.POST['email'] res = requests.post( 'http://0.0.0.0:8000/api/users/email/', data={ 'account_name': email, }, headers={ 'Authorization': 'Bearer {0}'.format(ACCESS_TOKEN), 'Content-Type': 'application/x-www-form-urlencoded' } ) ''' the error am getting is due to username and password being of type byte instead of string ,so if there is the way of converting them into string ''' Quit the server with CONTROL-C. b'jdv' … -
Django - Serializer throwing "Invalid pk - object does not exist" when setting ManyToMany attribute where foreign keyed object does exist
So below I have some code that tests the functionality where someone creates a post and that post has a hash_tag which is "#video" in this case. The code takes the Post body and uses regex to find any word that starts with "#". If it does then it creates or gets that HashTag from the HashTag table. Then sets that list of HashTag to the hash_tags attribute under Post. For some reason the CreatePostSerializer serializer is throwing an exception that doesn't make sense. The serializer is throwing the exception ValidationError({'hash_tags': [ErrorDetail(string='Invalid pk "[\'video\']" - object does not exist.', code='does_not_exist')]}). The reason this doesn't make sense is because when I debug and set a breakpoint right after except Exception as e under views.py this is what I get >>>e ValidationError({'hash_tags': [ErrorDetail(string='Invalid pk "[\'video\']" - object does not exist.', code='does_not_exist')]}) >>>HashTag.objects.get(pk='video') <HashTag: HashTag object (video)> >>>request.data['hash_tags'] ['video'] So the >>> represents what I input into the debugger. I'm essentially stopped at the line return Response... and we can see e is the ValidationError I mentioned, but we can see that the object it claims doesn't exist does indeed exist. Why is the serializer throwing a "ValidationError - object does not exist" … -
Django Inner join Parent model with child model
I have this tables class OtherTable(models.Model): #some attributes class Parent(models.Model): #some attributes class Child1(models.Model): group = models.ForeignKey(Parent) #more attributes class Child2(models.Model): group = models.ForeignKey(Parent) #more attributes class Child3(models.Model): group = models.ForeignKey(Parent) other_table = models.ForeignKey(OtherTable) #more attributes how can join all tables? I want to perform the equivalent SQL query using django's ORM: select * from parent inner join child1 on parent.id = child1.parent_id inner join child2 on parent.id = child2.parent_id inner join child3 on parent.id = child3.parent_id inner join othertable on other.id = child3.other_table_id -
How to filter query by multiple values using DRF, djagno-filters and HyperlinkedIdentityField values
Main target is to get query set based on multiple values in query. Business logic is to get all contracts for multiple drivers. Example: request url: /api/contract/?driver=http://localhost:8000/api/driver/1,http://localhost:8000/api/driver/2 Response should be all contracts for these two drivers. Driver Serializer: class DriverSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='driver-detail', read_only=True ) class Meta: model = Driver fields = [ 'url', 'id', 'first_name', 'last_name', ] Contract serializer: class ContractSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='contract-detail', read_only=True ) driver = serializers.StringRelatedField(many=False) class Meta: model = Contract fields = [ 'url', 'id', 'contract_detail_fields', 'driver', ] Contract View class ContractViewSet(viewsets.ModelViewSet): serializer_class = serializers.ContractSerializer queryset = Contract.objects.all() permission_classes = (IsAuthenticated,) filter_backends = [DjangoFilterBackend] filterset_class = ContractFilter ContractFilter: class ContractFilter(FilterSet): driver = CustomHyperlinkedIdentityFilterList('driver') What I have tried is to make custom filterField based on answer by Sherpa class CustomHyperlinkedIdentityFilterList(django_filters.BaseCSVFilter, django_filters.CharFilter): def filter(self, qs, value): values = value or [] for value in values: qs = super(CustomHyperlinkedIdentityFilterList, self).filter(qs, value) return qs Answer is ValueError: Field 'id' expected a number but got 'http://localhost:8000/api/drivers/driver/3/'. Then I am trying to modify to filter by id not urlField and changing this line qs = super(CustomHyperlinkedIdentityFilterList, self).filter(qs, value) to this: qs = super(CustomHyperlinkedIdentityFilterList, self).filter(qs, get_id_from_url(value)) where get_id_from_url is: def get_id_from_url(url): return int(resolve(urlparse(unquote(url)).path).kwargs.get('pk')) But it return me only contracts for … -
Speed up order_by and pagination in Django
Currently I have this result: That's not bad (I guess), but I'm wondering if I can speed things up a little bit. I've looked at penultimate query and don't really know how to speed it up, I guess I should get rid off join, but don't know how: I'm already using prefetch_related in my viewset, my viewset is: class GameViewSet(viewsets.ModelViewSet): queryset = Game.objects.prefetch_related( "timestamp", "fighters", "score", "coefs", "rounds", "rounds_view", "rounds_view_f", "finishes", "rounds_time", "round_time", "time_coef", "totals", ).all() serializer_class = GameSerializer permission_classes = [AllowAny] pagination_class = StandardResultsSetPagination @silk_profile(name="Get Games") def list(self, request): qs = self.get_queryset().order_by("-timestamp__ts") page = self.paginate_queryset(qs) if page is not None: serializer = GameSerializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(qs, many=True) return Response(serializer.data) Join is happening because I'm ordering on a related field? My models looks like: class Game(models.Model): id = models.AutoField(primary_key=True) ... class Timestamp(models.Model): id = models.AutoField(primary_key=True) game = models.ForeignKey(Game, related_name="timestamp", on_delete=models.CASCADE) ts = models.DateTimeField(db_index=True) time_of_day = models.TimeField() And my serializers: class TimestampSerializer(serializers.Serializer): ts = serializers.DateTimeField(read_only=True) time_of_day = serializers.TimeField(read_only=True) class GameSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) timestamp = TimestampSerializer(many=True) fighters = FighterSerializer(many=True) score = ScoreSerializer(many=True) coefs = CoefsSerializer(many=True) rounds = RoundsSerializer(many=True) rounds_view = RoundsViewSerializer(many=True) rounds_view_f = RoundsViewFinishSerializer(many=True) finishes = FinishesSerializer(many=True) rounds_time = RoundTimesSerializer(many=True) round_time = RoundTimeSerializer(many=True) time_coef = TimeCoefsSerializer(many=True) totals = … -
Trouble displaying inline forms of a ModelAdmin
I am encountering what seems to me a weird bug when rendering Inline forms on the "Add" view of a ModelAdmin. Here is a minimum example with Django version 2.2.4. in models.py: class MyModel(models.Model): text = models.CharField(max_length=100) class RelatedModel(models.Model): parent = models.ForeignKey(MyModel, null=False, on_delete=models.CASCADE) number = models.DecimalField(decimal_places=2, max_digits=10, null=False, blank=False) in admin.py: class RelatedModelInlineTabular(admin.TabularInline): model = RelatedModel show_change_link = False fields = ("number", ) class TestMyModelCreate(admin.ModelAdmin): fields = ['text', ] inlines = [RelatedModelInlineTabular] admin.site.register(MyModel, TestMyModelCreate) Steps to replicate Login to django admin website open the "add" view for MyModel (i.e. navigate to the list of Models and click on the "Add new" button) Expected result The form displays an empty text field. Below that, an Inline form is displayed with 3 empty rows for potential related instances of RelatedModel Actual result The Inline form is displayed twice, each instance with its own 3 empty rows, as if I had specified it twice. I attach a screenshot below of the actual page (Discount is the name of the related Model). I tried and I get the same result with both StackedInline and TabularInline. Am I making some trivial error here that could explain what's happening? Or is this is a known … -
404 Error on TextArea in Admin interface, Django Summernote
For texteditor i use Summernote Django, but i got error 404 on admin interface. summernote editor id doesn't find. that's urls.py urlpatterns = [ path('admin/', admin.site.urls), path('summernote/', include('django_summernote.urls')), ]