Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Authentication Login returns nothing
I'm trying to log users in with django authenticate. It returns nothing even when the email and password are correct. It just reloads the page and doesn't do anything. I have checked and the email and password I used are stored in the database, so the account exist but login doesn't do anything. I am using django 2. Views: def signup(request): if request.method == "POST": firstname = request.POST.get('firstname') lastname = request.POST.get('lastname') email = request.POST.get('email') password = request.POST.get('password') passwordagain = request.POST.get('passwordagain') areacode = request.POST.get('areacode') number = request.POST.get('number') userdetails = CustomUser(firstname=firstname,lastname=lastname,email=email,password=password, areacode=areacode, number=number) userdetails.save() return render(request, 'main/accountconfirmationpage.html') else: return render(request,'main/signup.html') def login(request): email=request.POST.get('email') password=request.POST.get('password') user = authenticate(request, email=email, password=password) if user is not None: if user.is_active: login(request, user) return render(request,'main/dashboard.html') else: return render(request, 'main/login.html') from django.db import models Models: # Create your models here. class CustomUser(models.Model): firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) email = models.EmailField(max_length=30) password = models.CharField(max_length=100) areacode = models.CharField(max_length=4) number = models.CharField(max_length=30) -
optimise django sql query
I'm using Django 2.x. I have two models class AmountGiven(models.Model): contact = models.ForeignKey(Contact, on_delete=models.PROTECT) amount = models.FloatField(help_text='Amount given to the contact') interest_rate = models.FloatField(blank=True, default=None, null=True) given_date = models.DateField(default=timezone.now) total_due = models.FloatField(blank=True, default=0.0, editable=False) class AmountReturned(models.Model): amount_given = models.ForeignKey(AmountGiven, on_delete=models.CASCADE, blank=True) amount = models.FloatField() return_date = models.DateField(default=date.today) Use case There can be multiple records of the amount given to a contact There can be multiple records of the returned amount for an amount given Now, I want to get total_due amount for a particular contact. This includes total_payable = total_given + interest total_due = total_payable - total_returned To calculate total_due and interest, I have defined few property methods in the AmountGiven model. @property def interest_to_pay(self): if self.interest_rate: simple_interest_amount = ... return simple_interest_amount return 0 @property def total_payable(self): return self.amount + self.interest_to_pay @property def amount_due(self): total_due = self.total_payable - self.total_returned self.total_due = total_due self.save() return total_due @property def total_returned(self): returned_amount = self.amountreturned_set.aggregate(total_returned=Sum('amount'))['total_returned'] if not returned_amount: returned_amount = 0 return returned_amount In Contact model, there is a property method to get the total due amount for the contact. @property def amount_due(self): total_due = 0 for due in self.amountgiven_set.all(): total_due += due.amount_due return total_due Query ContactSerializer class ContactMinSerializer(serializers.ModelSerializer): class Meta: model = Contact … -
django: ValueError: invalid literal for int() with base 10. for UpdateView ModelForm
I have a Django application containing a basic Profile model which extends the User model using the OneToOneField class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, ) And this is the url pattern for /updateProfile path('updateProfile/<pk>', views.UpdateProfileView.as_view(), name='update_profile'), which is being called from the navigation bar of the website as follows: <a href="{% url 'update_profile' request.user %}">UpdateProfile</a> I have utilised the ModelForm class in forms.py as follows: class update_profile_form(forms.ModelForm): class Meta: model = Profile fields = ('phone_number', 'profile_picture') And in Views.py the following UpdateView class-based view is invoked: @method_decorator(login_required, 'dispatch') class UpdateProfileView(UpdateView): model = Profile success_url = reverse_lazy('home') form_class = update_profile_form template_name = 'update_profile.html' # this is where the error occurs def get_queryset(self): return Profile.objects.filter(user=self.request.user) I am unable to determine what combination of user field to use above to render the form in the update_profile.html template. Please help! Thanks -
Django: How do I show images to select in forms?
I have a Car model and each car object has a photo. I want to create a form where the photos of every car are displayed. When user clicks on a photo and then clicks Submit, the id of the car associated with the photo gets transferred to a next form. How do I create such a form? Can I transfer the id from one form to a field on another form? -
Localization: django-admin compilemessages skip venv
I am using localization in Django 1.11 application. I can exclude the virtual environment folder and node_modules folder while adding the messages in message file using -i option like: django-admin makemessages -l 'no' -i venv django-admin makemessages -d djangojs --locale no -i venv -i node_modules After adding the translations I am compiling messages using: django-admin compilemessages It processes django.po files of all installed packages located in virtual environment folder. Thus it takes longer time to finish compiling translations. I did not find any argument parameter to skip a specific path from compilemessages command in documentation. Is there any option to skip the venv or specific path from compilemessages? -
How to show column name on admin site in django?
I'm extending my admin table on django default admin table. After adding a column, when I go to the admin site, I can only see the username column name on the user section. But when click it, it shows the column name and ready to put some fields. All I want is to show all the column name when visiting to the user table. Im just a newbie in Django Framework, I read some documents and ways to extend my admin table. All I want is to add column name on existing admin table. #models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): contact_number = models.CharField(max_length=250, blank=True) #views.py from django.shortcuts import render from .models import User from django.urls import reverse_lazy from django.views import generic from .forms import NewUserCreationForm from django.http import HttpResponseRedirect class SignUp(generic.CreateView): form_class = NewUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' def userView(request): users = User.objects.all() return render(request,'registration/view_users.html', {"all_users":users}) #admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User from .forms import NewUserCreationForm, NewUserChangeForm class NewUserAdmin(UserAdmin): add_form = NewUserCreationForm form = NewUserChangeForm model = User list_display = ['username','first_name','last_name','contact_number'] admin.site.register(User,NewUserAdmin) I want to show all the column on the admin site. -
Why css isn't loading in my Fastcomet Django website?
Static files don't load to the django website deployed on fastcomet, with cpanel The site is deployed and seemly works well in the other regards, loads from the database, redirects to pages but it doesn't not load any css, javascript or images, it's bare html, I have tried changing {% load static %} to {% load staticfiles %} in all pages, and vice-versa and setting direct directory to the staticfiles folder in the settings file, it works perfectly fine in my localhost, I don't know what could be the problem static and media files in settings.py file: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' wsgi.py file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'aida_ganaderia_luz_y_sombra.settings') application = get_wsgi_application() passenger_wsgi.py import os import sys sys.path.insert(0, os.path.dirname(__file__)) wsgi = imp.load_source('wsgi', 'aida_ganaderia_luz_y_sombra/wsgi.py') application = wsgi.application current state http://aidaganaderialuzysombra.tryfcomet.com/ bare html -
Customise django-activity-stream Action’s content
I’m using it for the first time and it just took a few minutes to set it up and running. However, I wanted to have below pattern for the final notification: [Date/time of comment][User Role][Username] commented on [Target]. However, I can only see this fixed syntax: action.send(User, verb='commented on', target=myObject) I can’t figure out how to customize it. -
how to set parameter in json in django?
I am newbie to dJango and javascript. I am trying to pass the variable into the parameter in my function so that the function is called using the variable. Below are codes. view.py def plot_graph(request,column): data = Data.objects.all() \ .extra(select={'data': connections[Data.objects.db].ops.date_trunc_sql('data', column)}) \ .values(column) return JsonResponse(list(data),safe=False) urls.py urlpatterns = [ url(r'^form/$', views.Form), url(r'^api/plot_graph/(?P<column>[\w-]+)', views.plot_graph, name='plot_graph'), ] form.html var c = {{column_json | safe}} d3.json("{% url "plot_graph" column=c %}", function(error, data) { data.forEach(function(d){ d.c5 = d.c5; }); What I want to do is that variable c is passed into the d3.json so that function plot_graph is used according to the variable c. However, below code gives me an error saying that Reverse for 'plot_graph' with keyword arguments '{'column': ''}' not found. 1 pattern(s) tried: ['index/api/plot_graph/(?P<column>[\\w-]+)'] How to resolve this issue? -
when set gid, uwsgi aborted
below was my uwsgi.ini file: [uwsgi] module = myblog.wsgi #socket = 127.0.0.1:8000 chdir = /opt/python3/myblog buffer-size = 32768 home = /root/.pyenv/versions/3.7.1/envs/blog/ env = DJANGO_SETTINGS_MODULE=myblog.settings socket = /opt/python3/myblog/myblog.sock pidfile2 = /var/run/uwsgi/uwsgi.pid daemonize2 = /var/log/uwsgi/uwsgi.log log-format = %(addr) - %(user) [%(ltime)] "%(method) %(uri) %(proto)" %(status) %(size) "%(referer)" "%(uagent)" process = 4 threads = 2 uid = 1000 gid = 1000 master = true chmod-socket = 664 chown-socket = nginx:nginx # clear envirnment to exit vacuum = true when I set the uid and gid, and I tried to start uwsgi, it abortd. The error info was below. uWSGI running as root, you can use --uid/--gid/--chroot options setgid() to 1000 setuid() to 1000 Python version: 3.7.1 (default, Dec 18 2018, 07:21:59) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] !!! Python Home is not a directory: /root/.pyenv/versions/3.7.1/envs/blog/ !!! Set PythonHome to /root/.pyenv/versions/3.7.1/envs/blog/ Fatal Python error: initfsencoding: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' Current thread 0x00007fc575d01840 (most recent call first): Aborted but if I only set the uid and annotate gid. It works fine. I don't know why. It's really make me confused. -
Django filter sub elements in single query
I have a django DRF project tracking students in classes at a school. There are teachers, students, administration, and school_classes. Not all students are verified, but administration should see all students while teachers should only see verified students. It's simple enough to make a queryset so when teachers query for students, they only get back verified students. But the problem comes when a teacher queries a class and goes to access school_class.students. Here it will list out all the students, whether or not they are verified. How can I have the students list filtered in the same query that fetches the class? -
How does this work? {now:%Y/%m/%Y%m%d%H%M%S}{ext}"
I am reading Django Cookbook 2 and I came across an image upload form that doesn't work as expected. When the user uploads an image it names the image as the date and time at that moment in time. What I can't figure out is when the form saves, it doesn't actually render to have numbers in it and stays with the %Y/%m characters. return f"profile/{now:%Y/%m/%Y%m%d%H%M%S}{ext}" Secondly, why is there an "f", because it keeps throwing an error if I don't remove it. Views.py from django.utils.timezome inport now as timezone_now def upload_to(instance, filename): now = timezone_now() base, ext = os.path.splitext(filename) ext = ext.lower() return f"profile/{now:%Y/%m/%Y%m%d%H%M%S}{ext}" -
Django Image Uploading Via ModelForm Error 400 Bad Request, While Using Channels and ASGI
i am creating a Django Chatting application, using Django Channels but if i want to upload file or Image ajax or http then django return error 400 (Bad Request) also Django Default Admin not Uploading File. When i upload a file using Admin App i also found error 400, please help with that if i remove Channels library then its all working fine, Server only Give error 400 while ASGI, with WSGI server everything Working Fine Django Channels ASGI File Uploading (Profile Image) i have tries to solve, but no solution found Thanks -
Middleware not executed by Django
I am trying to include a middleware in a Django project, but it seems the middleware is not being executed by Django. The idea is to impersonate another user account when having app-administrator privileges. The MIDDLEWARE section of my settings.py file looks like this: 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', 'mird_project.monitor.middleware.impersonateMiddleware.ImpersonateMiddleware', ] The middleware class looks like this: from .models import Usuario class ImpersonateMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_request(self, request): us_obj = Usuario.objects.all().filter(id_usuario=request.user.username).first() tipo = us_obj.tipo.id_tipo if tipo == "AD" and "__impersonate" in request.GET: request.session['impersonate_id'] = request.GET["__impersonate"] elif "__unimpersonate" in request.GET: del request.session['impersonate_id'] if tipo == "AD" and 'impersonate_id' in request.session: request.user = Usuario.objects.get(id_usuario=request.session['impersonate_id']) return None I inserted an assert False, request inside the process_request method so that it would abort execution with an exception and show me what request contained. It never even got executed, so I assume the middleware never gets executed. It doesn't throw any kind of error and the impersonation mechanism just displays the same administrator user in the site. Any ideas why the middleware isn't being called? -
Django celery trigger manage.py cmd @periodic_task
i want to run a manage.py cmd from celery as a periodic task every x Minutes but every time i try to accomplish that as show below i get the following error: [2019-01-17 01:36:00,006: INFO/MainProcess] Received task: Delete unused media file(s)[3dd2b93b-e32a-4736-8b24-028b9ad8da35] [2019-01-17 01:36:00,007: WARNING/ForkPoolWorker-3] Scanning for unused media files [2019-01-17 01:36:00,008: WARNING/ForkPoolWorker-3] Unknown command: 'cleanup_unused_media --noinput --remove-empty-dirs' [2019-01-17 01:36:00,008: INFO/ForkPoolWorker-3] Task Delete unused media file(s)[3dd2b93b-e32a-4736-8b24-028b9ad8da35] succeeded in 0.0008139749998008483s: None @periodic_task(run_every=(crontab(minute='*/90')), name="Delete unused media file(s)", ignore_result=True) def delete_unused_media(): try: print("Scanning for unused media files") management.call_command('cleanup_unused_media --noinput --remove-empty-dirs') return "success, old media files have been deleted" except Exception as e: print(e) that management cmd comes from the following project: https://github.com/akolpakov/django-unused-media is my management call simply wrong or whats the deal? thanks in advance -
Celery with Redis broker in Django: tasks successfully execute, but too many persistent Redis keys and connections remain
Our Python server (Django 1.11.17) uses Celery 4.2.1 with Redis as the broker (the pip redis package we're using is 3.0.1). The Django app is deployed to Heroku, and the Celery broker was set up using Heroku's Redis Cloud add-on. The Celery tasks we have should definitely complete within a minute (median completion task is ~100 ms), but in Heroku's provided Redis viewer (powered by Redis Labs), we're seeing that Redis keys and connections are persisting for much, much longer than that (minutes and hours). Otherwise, tasks are being executed correctly. What can be happening that's causing these persisting keys and connections? How can we ensure that they are cleared when Celery tasks conclude? Here's a Redis Labs screenshot of this happening (all tasks should have completed, so we'd expect zero keys and zero connections): -
How to get data from a HTML table into DJango
I'm relatively new to web development so I'm not sure that I'm taking the correct route with this. I have a web app for home buyers to submit their information (address and such). With such a purchase, you can have multiple buyers (such as you could have with a business). I've included a table and some text boxes where when filled out, a new buyer is added as a row in the table using java script. I'm not sure exactly how to get this information back into DJango, although I have read where it might involve AJAX calls. Does anyone have any pointers? Thank you. -
Impossible to run the gunicorn because of the import error
I have had a django==2.1 project with virualenv. Then to solve some package problems I created another virtualenv for my project and activated it. However whenever I run gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application I am receiving the following problem. Traceback (most recent call last): File "/home/root/uzagro_4/agrosenv/lib/python3.5/site- packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/root/uzagro_4/agrosenv/lib/python3.5/site- packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/home/root/uzagro_4/agrosenv/lib/python3.5/site- packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/home/root/uzagro_4/agrosenv/lib/python3.5/site- packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/root/uzagro_4/agrosenv/lib/python3.5/site- packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/home/root/uzagro_4/agrosenv/lib/python3.5/site- packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/home/root/uzagro_4/agrosenv/lib/python3.5/site- packages/gunicorn/util.py", line 350, in import_app __import__(module) ImportError: No module named 'myproject' [2019-01-17 04:16:14 +0500] [21107] [INFO] Worker exiting (pid: 21107) [2019-01-17 04:16:14 +0500] [21104] [INFO] Shutting down: Master [2019-01-17 04:16:14 +0500] [21104] [INFO] Reason: Worker failed to boot. I have no idea how to solve this problem. This is my gunicorn.service file: [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=nginx WorkingDirectory=/home/root/uzagro_4 ExecStart=/home/root/uzagro_4/agrosenv/bin/gunicorn --workers 3 --bind unix:/home/root/uzagro_4/myproject.sock uzagro_4.wsgi:application [Install] WantedBy=multi-user.target And the nginx.conf file: server { listen 80; server_name agros.uz www.agros.uz; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/root/uzagro_4/; } location / { proxy_set_header Host $http_host; proxy_set_header … -
Django Form field not appearing
I am receiving a This field is required error using a form view that django is generating. I have a Scan model that looks like: class Scan(models.Model): device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL) created_at = models.DateTimeField('Created', auto_now=True) data = models.FileField(upload_to='uploads/') def __str__(self): return str("{}-{}".format(self.device, self.created_at)) I have a CreateView defined: class ScanCreate(LoginRequiredMixin, CreateView): model = Scan fields = '__all__' My url route is urlpatterns = [ ... path('scan/create/', views.ScanCreate.as_view(), name='scan-create'), ... ] and finally a scan_form.html template {% block content %} <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> </form> {% endblock %} On submitting the form, I get the 'This field is required.' error and the request fails: I note that the created_at field does not appear in the form and I believe the error is related to this missing field. Should this field not appear populated within the create view? -
Django filter based on joined model
Let's say I have the following design database table A track has a song and a song has a singer. I would like the track allows filtering based on singer name too. So, I need the track model extract the singer name. I got stuck with the filters. I receive the following error message: File ".../lib/python3.6/site-packages/django_filters/filterset.py", line 352, in get_filters "%s" % ', '.join(undefined) TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: singer I have heard from this to use __ but I have no idea how to apply that. Here is the code class TrackSerializer(MyModelSerializer): singer = serializers.SerializerMethodField() def get_singer(self, track): # Is there any shortcut? song = Song.objects.get(id=track.song_id) if song is not None: return Channel.objects.get(id=song.singer_id).name else: return '' class TrackFilterSet(MyFilterSet): singer = CharFilter(method='singer_filter') song = RefineModelChoiceFilter( queryset=Song.objects.all(), refine_choices=lambda qs, keywords, request: qs.filter(name__icontains=keywords) ) def singer_filter(self, queryset, name, value): # print('queryset:', TrackSerializer(queryset, many=True)) return queryset.filter(**{ name: value, # ??????????? }) class Meta: model = Track fields = ( 'singer', 'song', ) class TrackViewSet(MyViewSet): queryset = Track.objects.all() serializer_class = TrackSerializer filterset_fields = ('singer', 'song') def filter_refine_choices_singer(self, qs, keywords, request): return qs.filter(name__icontains=keywords) def filter_refine_choices_song(self, qs, keywords, request): return qs.filter(name__icontains=keywords) -
Django rest framework retrieving lists in serializers
Take the following example into account. I have two models, one Author and one Article. They look like so: # author.py from django.db import models class Author(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): return self.first_name # article.py from django.db import models from authors.models import Author class Article(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) text = models.TextField() def __str__(self): return self.text My serializers look like so: from rest_framework import serializers from .models import Article from authors.serializers import AuthorSerializer class ArticleSerializer(serializers.ModelSerializer): author = AuthorSerializer() class Meta: model = Article fields = '__all__' from rest_framework import serializers from .models import Author class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = '__all__' Now, if I wish to get articles from my API, that's simple. Getting articles attaches the author and that's all well and good -- but how do I get the inverse? For instance, if I want to get authors with the latest 5 articles that they have written? So the intended output would be something like: { "first_name": "Sethen", "last_name": "Maleno", "articles": [ { "text": "some article" }, { "text": "another article" } ] } -
Sending image and JSON simultaneously
I want to pass JSON object and image at the same time from react to my django rest api. I've tried some solutions from this forum and tutorials but nothing worked in my case. Previously I have been using JSON.stringify on state fields and that worked but i couldn't pass image and now i ended up on something like this. postData.js let formData = new FormData(); const { title, description, image, ingredient, step } = this.state; formData.append('image', image); formData.append('title', title); formData.append('description', description); formData.append('ingredient', ingredient); formData.append('step', step); let conf = { method: 'post', body: formData, headers: new Headers({ 'Content-Type': 'multipart/form-data', 'Accept': 'application/json' }) }; fetch('http://127.0.0.1:8000/api/', conf) .then(res => { this.props.history.push('/'); }) .catch(err=>{console.log(err)}) serializers.py class RecipeSerializer(serializers.ModelSerializer): ingredient = IngredientSerializer(many=True, required=False) step = StepSerializer(many=True, required=False) class Meta: model=models.Recipe fields=('id', 'title', 'description', 'image', 'ingredient', 'step', ) def create(self, validated_data): ingredient_data = validated_data.pop('ingredient') step_data = validated_data.pop('step') recipe = models.Recipe.objects.create(**validated_data) for ingredient in ingredient_data: models.Ingredient.objects.create(recipe=recipe, **ingredient) for step in step_data: models.Step.objects.create(recipe=recipe, **step) return recipe views.py class ListRecipes(generics.ListCreateAPIView): queryset = Recipe.objects.all() serializer_class = RecipeSerializer class DetailRecipe(generics.RetrieveUpdateDestroyAPIView): queryset = Recipe.objects.all() serializer_class = RecipeSerializer I always get POST http://127.0.0.1:8000/api/ 400 (Bad Request) error. -
'auth.User' has been swapped for
I'm following the official Django documentation : https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#substituting-a-custom-user-model My Django version is 2.1. The goal is to extend the default auth.User Django Model. I have exactly the same code that is in the example. I got an app, "user", and my AUTH_USER_MODEL in settings.py is "user.User". But I get this error : AttributeError: Manager isn't available; 'auth.User' has been swapped for 'user.User' I can't find informations... Thank you ! -
django double left join + django rest framework serializers
I have these models: class Item(models.Model): name = models.CharField(max_length=100) class Group(models.Model): name = models.CharField(max_length=100) class ItemGroup(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) Means an item can be in multiple groups. I want to query all items, and for each item return his groups as a nested list (or an empty list if the item does not appear in a group). This is what I would do with sql: SELECT item.id, item.name, group.name FROM items LEFT JOIN item_group ON item.id = item_group.id LEFT JOIN group ON group.id = item_group.group_id (I might add an ORDER BY too, for paging, but nevermind for now). This query would give me every item X number of groups the item is connected too, and at least one row for an item that does not appear in any group (with group set to null). Then, I'll need to convert it to a nested list manually. The question: 1. How to do the same joins with django ORM? This is the closest question I've found: django left join But the answer isn't actually a left join, but a prefetch_related, which I want to avoid. 2. If I would create a nested dict of models like this: … -
Django HyperlinkedSerializer slug instead of PK for field
Dog model has a field "cat' class Dog(models.Model): ... cat = models.ForeignKey(Cat) ... Cat rest_views work fine. Dog rest_views work fine if I remove the 'cat' field from fields class CatSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Cat # Replace ID with SLUG in urls lookup_field = 'slug' fields = ('url', 'slug') extra_kwargs = { 'url': {'lookup_field': 'slug'} } class DogSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Dog fields = ('url', 'slug', 'cat') lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } class CatViewSet(viewsets.ModelViewSet): def get_serializer_context(self): context = super().get_serializer_context() context['slug'] = self.kwargs.get('slug') return context queryset = Cat.objects.all() serializer_class = CatSerializer lookup_field = 'slug' class DogViewSet(viewsets.ModelViewSet): queryset = Dog.objects.all() lookup_field = 'slug' serializer_class = DogSerializer router = routers.DefaultRouter() router.register(r'cats', rest_views.CatViewSet) router.register(r'dogs', rest_views.DogViewSet) The error I get when I add the cat in dog serializer fields: Could not resolve URL for hyperlinked relationship using view name "cat-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.