Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check if there is any yet not executed tasks in Celery
I need to check whether Celery has any yet not executed tasks. I'm writing tests and need to make sure a Celery task is already finished. I don't want to query the broker or do any system calls.. I just want to achieve this using Celery API. My application is Django-based and containerized using Docker. -
How to obtain content_type from a Django Model Class?
I am trying to obtain the ContentType for a django models.Model. Not trying to get the model from a ContentType, which is all I can find in the docs. For example: model_name = 'FooBar' MyModel = apps.get_model('app_xyz', model_name) MyModel <class 'apps.app_xyz.models.FooBar'> How do I get the ContentType of MyModel? The only thing I can figure out to do is set the model_name string to lower and directly query ContentTypes: ct = ContentType.objects.get(model=model_name.lower()) That seems really fragile, and using lower() has a code smell I don't like. I've looked through FooBar's methods, _methods, and __methods to no avail. Thanks! -
i want to make an app that wright and send pdf to my email
I want to make a form that clients can entre they info and I will receive the information in my email in pdf format . -
js function won't run after an uploading process
i know this is a silly question but i cant seems to figure it out, im new in js and i have been trying to implement a tutorial on my website to program a upload progress bar using js and bootstrap the progress bar is working fine but after the process completed the browser supposed to refresh but its not doing anything this is my form <form method="POST" action="." class="needs-validation" enctype='multipart/form-data'> {% csrf_token %} <div class="c_details_img"> <img class="img-fluid" src="{% static 'img/courses/course-details.jpg'%}" alt=""> </div> <div class="shadow-sm p-3 mb-5 mt-4 bg-white rounded"> <div id="videoinput" class=""> {{form.video}} </div> <div id="progressdiv" class="progress d-none" style="height: 2rem;"> <div id="progressbar" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">0%</div> </div> </div> </div> <div class="col-lg-4"> <div class="c_details_list shadow-sm p-3 mb-5 bg-white rounded"> <div class="form-group"> <label for="exampleInputEmail1">Title:</label> {{ form.title}} <small id="emailHelp" class="form-text text-muted">(Enter a title that covers the course content comprehensively)</small> </div> <div class="form-group"> <label for="exampleInputEmail1">Description:</label> {{ form.description}} <small id="emailHelp" class="form-text text-muted"> (Be sure to describe the course content briefly)</small> </div> <button id="save_btn" style="width: 100%;height: 3rem;" class="main_btn" type="submit">Save the Course</button> <button id="loading_btn" style="width: 100%;height: 3rem;" class="btn btn-success d-none" type="button" disabled>Uploading...</button> </form> and this is my uploader.js : $(document).ready(function () { $("form").on("submit", function (event) { event.preventDefault(); var formData = new … -
ERROR: No matching distribution found for ipython==7.18.1
I uploaded a Python app to Heroku. In my requirements.txt file I have a line for ipython==7.18.1 but Heroku seems unable to retrieve it, I don't understand whether the problem is with the versions of python and ipython and which version i should use,so they match The complete error thrown is: ERROR: Could not find a version that satisfies the requirement ipython==7.17.0 (from -r /tmp/build_76afe907/requirements.txt (line 32)) (from versions: 0.10, 0.10.1, 0.10.2, 0.11, 0.12, 0.12.1, 0.13, 0.13.1, 0.13.2, 1.0.0, 1.1.0, 1.2.0, 1.2.1, 2.0.0, 2.1.0, 2.2.0, 2.3.0, 2.3.1, 2.4.0, 2.4.1, 3.0.0, 3.1.0, 3.2.0, 3.2.1, 3.2.2, 3.2.3, 4.0.0b1, 4.0.0, 4.0.1, 4.0.2, 4.0.3, 4.1.0rc1, 4.1.0rc2, 4.1.0, 4.1.1, 4.1.2, 4.2.0, 4.2.1, 5.0.0b1, 5.0.0b2, 5.0.0b3, 5.0.0b4, 5.0.0rc1, 5.0.0, 5.1.0, 5.2.0, 5.2.1, 5.2.2, 5.3.0, 5.4.0, 5.4.1, 5.5.0, 5.6.0, 5.7.0, 5.8.0, 5.9.0, 5.10.0, 6.0.0rc1, 6.0.0, 6.1.0, 6.2.0, 6.2.1, 6.3.0, 6.3.1, 6.4.0, 6.5.0, 7.0.0b1, 7.0.0rc1, 7.0.0, 7.0.1, 7.1.0, 7.1.1, 7.2.0, 7.3.0, 7.4.0, 7.5.0, 7.6.0, 7.6.1, 7.7.0, 7.8.0, 7.9.0, 7.10.0, 7.10.1, 7.10.2, 7.11.0, 7.11.1, 7.12.0, 7.13.0, 7.14.0, 7.15.0, 7.16.0, 7.16.1) ERROR: No matching distribution found for ipython==7.17.0 (from -r /tmp/build_76afe907/requirements.txt (line 32)) -
search field in Django returning blank page?
I'm doing an encyclopedia project with different entries linked on the homepage. I'm also trying to add a search bar to the homepage so if someone searches up an entry that has already been created then they are taken directly to that entry page. Alternatively, if they partially enter the entry name then they will be taken to a search page with a list of close results. views.py def search(request): value = request.GET.get('q','') if(util.get_entry(value) is not None): return HttpResponseRedirect(reverse("entry", kwargs={'entry': value })) else: subStringEntries = [] for entry in util.list_entries(): if value.upper() in entry.upper(): subStringEntries.append(entry) return render(request, "encyclopedia/index.html", { "entries": subStringEntries, "search": True, "value": value }) urls.py path("search/", views.search, name="search") layout.html <form action = "{% url 'search' %}" method="GET"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia" autocomplete="off"> </form><br> For some reason, anytime I enter anything in the search bar it takes me to a blank page and I do not understand why? The annoying thing is, it was working yesterday. When I entered the name of an entry that was already part of the encyclopedia then it would take me to the already existing entry page but it wasn't doing exactly what I wanted it to so I was trying to … -
Can't find .po file after running django-admin.py makemessages -l de command
I ran django-admin.py makemessages -l de but I can't find any .po file in my project directory. I want to translate the registration form to Persian so I went step by step from django book chapter 19 (https://django-book.readthedocs.io/en/latest/chapter19.html). but I got stuck at this step!! this is my models.py from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as __ class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='basic_app/profile_pics',blank=True) def __str__(self): return self.user.username this is my forms.py from django import forms from django.contrib.auth.models import User from .models import UserProfileInfo from django.utils.translation import ugettext_lazy as __ class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = (__('username'),__('email'),__('password')) class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('portfolio_site','profile_pic') and this is my template {% extends "basic_app/base.html" %} {% load staticfiles %} {% block body_block %} <div class="container"> <div class="jumbotron"> {% if registered %} <h1>Thank you for registering!</h1> {% else %} <h1>Register Here</h1> <h3>Just fill out the form.</h3> <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ trans user_form.as_p }} {{ trans profile_form.as_p }} <input type="submit" name="" value="Register"> </form> {% endif %} </div> </div> {% endblock %} what should I do?? -
How to get the difference of two values of same column in django
So I have table T in the Postgres database which has day to day values of the users. From that table, I need to find the difference between yesterday's value and today's value of an attribute C of all the users and return the IDs of the users' for which the difference is greater than 10. Can this whole thing be done in one or two queries? The solutions I have in my mind are naive and will need separate queries for each user. -
Django form-wizard: What happens when i omit required template tag
Django Form Wizard docs state that Note that {{ wizard.management_form }} must be used for the wizard to work properly. I know that if i omit it, the request.POST will be missing something along the lines of 'domain-current_step': [0]. Is there anything else that will be missing? -
No data is being returned when I use an inherited Django Rest Framework serializer? It just returns an empty dictionary
I have a serializer that is meant to act as a template for other ModelSerializers. class CountryBasedModelSerializer(ModelSerializer): def __init__(self, data, context): assert 'country' in self.Meta.fields class Meta: model = Country fields = () I want to use it with this, which is the actual serializer which will be called. class CountryBasedProjectSerializer(CountryBasedModelSerializer): class Meta: model = Project fields = ('id', 'country', 'name') I want to use it with this inherited viewset: class CountryBasedViewset(viewsets.ModelViewSet): queryset = None serializer_class = CountryBasedModelSerializer def get_queryset(self): return self.queryset.filter(country_pk=self.request.data["country"]) And this is the actual viewset that will be called: class CountryProjectBasedViewset(CountryBasedViewset): queryset = Project.objects.all() Is there anything that I am clearly doing incorrectly? -
provide large responses to python requests_mock
I am using python requests to to access some apis, recently I learned requests_mock for mocking http responses for testing. The responses from api that I am using are quire large adapter.register_uri('GET', 'http://api.gateway/payment/, text='VERY LARGE TEXT') What is the proper way of passing large response text? -
Passing static path to included template
Is it possible to pass a static path as a variable to an included template? I need to repeatedly include a template on my page but its always with different logos. For example: {% with img={% static 'img/dashboards/belgium_flag.svg' %} %} {% include 'dashboards/charts/country_block.html' %} {% endwith %} {% with img={% static 'img/dashboards/netherlands_flag.svg' %} %} {% include 'dashboards/charts/country_block.html' %} {% endwith %} This doesn't work.. Is there any workaround to this besides creating a model to support an image attribute to each Country instance? -
sending an email manually in Django admin panel, and show a successful alert instead of redirect
this my view.py: from django.contrib import messages from django.core.mail import send_mail from django.shortcuts import redirect from django.http import HttpResponse def sendmail(request): if request.method == 'GET': send_mail('this is subject', 'Hello alex', "mysite.com <orders@mysite.com>", ['reciver_email@gmail.com'], fail_silently=False) return HttpResponse('ok') this my app.url.py: from django.urls import path from . import views urlpatterns = [ path('/redirect/' , views.sendmail, name='sendmail'), ] this my url.py: urlpatterns = [ path('', include('register.urls')), path('admin/', admin.site.urls), ] this is my change_form.html that override admin templates: {% extends "admin/change_form.html" %} {% load i18n %} {% block submit_buttons_bottom %} <a href="{% url 'sendmail'%}"> <input type="button" value="Click" name="mybtn" /></a> {% if messages %} <ul class="messagelist">{% for message in messages %}<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>{% endfor %}</ul> {% endif %} {{ block.super }} {% endblock %} and this my app image: my app when I click on the button the email was sent. look at this but, I want when the email was sent, just show an alert that email sent successfully. my problem is, I don't want to redirect to another page. what should I do? -
Django GraphQL Test: How to test addition of new model fields?
I have a simple model as, class Person(models.Model): first_name = models.CharField(max_length=20) and I have setup the GraphQL to query the data, import graphene import graphene_django from .models import Person class PersonType(graphene_django.DjangoObjectType): class Meta: model = Person fields = '__all__' class PersonQuery(graphene.ObjectType): persons = graphene.List(PersonType) def resolve_persons(*args, **kwargs): return Person.objects.all() So far so good. Later I decided to write unittests for querying the persons data from django.test import TestCase from .models import Person from .schema import schema class TestGraphQLQuery(TestCase): @classmethod def setUpTestData(cls): cls.person = Person.objects.create(first_name="Jack") def test_person_query(self): query = """ query{ persons { id firstName } } """ result = schema.execute(query).data expected = {'persons': [{'id': f'{self.person.pk}', 'firstName': self.person.first_name}]} self.assertEqual(result, expected) and this too working. Later, my model got updated with one additional field, age and hence the model updated to class Person(models.Model): first_name = models.CharField(max_length=20) age = models.IntegerField(default=0) After the changes, I ran the unittests. As expected, it passes. Question How can I create the test case so that, the test should fail upon addition or removal of any fields? -
ModuleNotFoundError: No module named 'encodings'; rhel8; python3; apache2.4; mod_wsgi; django 3.1
Am trying to setup my django application (virtual environment) using apache and mod_wsgi. the application is running on RHEL8 machine and the only python running is python 3. RHEL version == Red Hat Enterprise Linux release 8.2 (Ootpa) python version == Python 3.6.8. apache version == Apache/2.4.37 (Red Hat Enterprise Linux). mod_wsgi version == 4.7.1. django version == 3.1. My Python virtual environment home is: python-home using sys.prefix i have created the mod_wsgi.so using CMMI method. below is the library detail ldd mod_wsgi.so details below is my virtual host conf file for apache. i have also tried adding python-path (like below), although not written in conf file details below. WSGIDaemonProcess sohail python-home=/home/ilearn/webapps/sohail python-path=/home/ilearn/webapps/sohail/src webapptest.conf: <VirtualHost *:80> WSGIScriptAlias /webapptest /home/ilearn/webapps/sohail/src/webapptraining/wsgi.py WSGIDaemonProcess sohail python-home=/home/ilearn/webapps/sohail WSGIProcessGroup sohail WSGIApplicationGroup %{GLOBAL} <Directory /home/ilearn/webapps/sohail/src/webapptraining> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> As soon as i startup my apache server i see the error ModuleNotFoundError: No module named 'encodings' in error logs. [core:notice] [pid 4576:tid 139861315184960] AH00052: child pid 4893 exit signal Aborted (6) Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' appreciate any help or advise to resolve the problem. thanks. -
django - How can I prefill formset forms data using database query result?
I am creating a student attendance form where need to get details of student name, student class and Id from student model based on teacher selecting student class in one form. I have tried using initial by using for loop on query data to prefill the form in formset, however it populates data for one record only. Below is the code for forms.py, models and views.py. Can someone help on this forms.py class student(models.Model): studentid = models.AutoField(primary_key=True) Gender = models.CharField(max_length=6, choices=gender, null=True) Name = models.CharField(max_length=100, null=True) DOB = models.DateField(null=True) Image = models.ImageField(null=True, upload_to='images') Status = models.CharField(max_length=10, choices=statchoice, null=True) Father_name = models.CharField(max_length=100, null=True) Mother_name = models.CharField(max_length=100, null=True) Address = models.CharField(max_length=200, null=True) Contact_no = models.IntegerField(null=True) Email = models.EmailField(null=True) Admission_class = models.CharField(max_length=40, null=True, choices=grade) Admission_date = models.DateField(null=True) Current_class = models.CharField(max_length=40, null=True, choices=grade) Leaving_date = models.DateField(null=True, blank=True) objects = models.Manager() def __str__(self): return str(self.studentid) class student_attendance(models.Model): Student_ID = models.CharField(max_length=100, null=True) Student_Name = models.CharField(max_length=100, null=True) Student_class = models.CharField(max_length=100, null=True, choices=grade) Attendance_date = models.DateField(null=True, auto_now_add=True, blank=True) Attendance_status = models.CharField(choices=attendance, null=True, max_length=10) objects = models.Manager() Views.py def student_attend(request): if request.method == 'POST': data = request.POST.get('studentGrade') formset_data = student.objects.filter(Current_class=data) AttendanceFormSet = formset_factory(std_attendance, extra=(len(formset_data))-1) for element in formset_data: formset = AttendanceFormSet(initial=[ {'Student_ID': element.studentid, 'Student_Name':element.Name, 'Student_class':element.Current_class, 'Attendance_status':"Present"} ]) param = … -
ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/tmp/build/80754af9/asgiref_1594338739818/work'
While deploying my website on heroku. I also updated my requirements.txt file still there is this issue. git push heroku master Enumerating objects: 98, done. Counting objects: 100% (98/98), done. Delta compression using up to 4 threads Compressing objects: 100% (87/87), done. Writing objects: 100% (98/98), 1.31 MiB | 29.00 KiB/s, done. Total 98 (delta 35), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.12 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting alabaster==0.7.12 remote: Downloading alabaster-0.7.12-py2.py3-none-any.whl (14 kB) remote: Collecting appdirs==1.4.4 remote: Downloading appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB) remote: Collecting argh==0.26.2 remote: Downloading argh-0.26.2-py2.py3-none-any.whl (30 kB) remote: Processing /tmp/build/80754af9/asgiref_1594338739818/work remote: ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/tmp/build/80754af9/asgiref_1594338739818/work' remote: remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 9782a444fca0b0d09e0566b33ecbffce4eb90d89 remote: ! remote: ! We have detected that you have triggered a build from source code with version 9782a444fca0b0d09e0566b33ecbffce4eb90d89 remote: ! at … -
Django still refreshing the page after integrating AJAX
In index.js: $("#weather_form").on("submit", function(event){ event.preventDefault(); $.ajax({ url: "/weather/", type: "POST", data: {...:..., ...:..., ...}, success: function (data){ alert("success") }, error: function(xhr,errmsg,err) { alert("error") } }); }); In views.py: class weather(base.TemplateView): ... @staticmethod def post(request, *args, **kwargs): ... if request.is_ajax and request.method == "POST": ... if form.is_valid(): ... return http.JsonResponse({"results_matrix": results_matrix.tolist()}, status=200) else: return http.JsonResponse({"error": form.errors}, status=400) What's happening now is when I click submit, Django clears the entire page and then print the correct results_matrix on a blank page in string format. alert("success") does not appear or alert("error"). I don't know why the post function is doing this since I'm not returning a render of anything. -
Kubernetes: Django and Postgres Containers don't communicate
I have created a Django-Python application with a postgres database. Its working fine in my PC as well as in any other windows based systems. I am trying to use K8s to host the application. I have setup the postgres container successfully. But when I am trying to create the Django-Python container and tryong to start it, it shows me this kind of error: Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? The Deployment and service yaml for the postgres container: --- # Deployment for the PostgreSQL container apiVersion: apps/v1 kind: Deployment metadata: name: postgresql namespace: trojanwall labels: app: postgres-db spec: replicas: 1 selector: matchLabels: app: postgres-db strategy: type: Recreate template: metadata: labels: app: postgres-db tier: postgreSQL spec: containers: - name: postgresql image: postgres:10.3 ports: - containerPort: 5432 env: - name: POSTGRES_USER valueFrom: secretKeyRef: name: postgres-db-credentials key: user - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: postgres-db-credentials key: password - name: POSTGRES_DB value: 'postgres' volumeMounts: - mountPath: /var/lib/postgresql/data name: postgresql-volume-mount resources: requests: memory: "64Mi" cpu: "250m" limits: memory: "128Mi" cpu: "500m" volumes: - name: postgresql-volume-mount persistentVolumeClaim: claimName: postgres-pv-claim --- # Service for the PostgreSQL container apiVersion: v1 kind: Service metadata: name: postgresql namespace: trojanwall labels: app: … -
Get Data from foreign key in django
I have created two tables in Sqlite one have the main experience data and other have the details of the data as class experience(models.Model): e_name = models.CharField(max_length=30) e_post = models.CharField(max_length=50) e_startdate = models.CharField(max_length=30) e_enddate = models.CharField(max_length=30) def __str__(self): return self.e_name class experiencedetail(models.Model): e_name = models.ForeignKey(experience,on_delete=models.DO_NOTHING) e_detail = models.CharField(max_length=100) i am trying to shoe the details as shown in this image my Html code is {% for exp in experience %} <div id="{{exp.e_name}}" class="tabcontent"> <h2 class="hf">{{exp.e_post}} @ <span>{{ exp.e_name }}</span></h2> <p>{{exp.e_startdate}} - {{exp.e_enddate}}- {{exp.id}}</p> <div class="exp-description"> <h4> <ul style="list-style: square;"> {% for expd in exp_detail %} {% if 'expd.e_name' == 'exp.e_name' %} <li>{{ expd.e_detail }}</li> {% endif %} {% endfor %} </ul> </h4> </div> </div> {% endfor %} but this expd.details does not show any data. The data is present in the database. -
PyQt based desktop application which has a subscription based model
I have developed a desktop application in python using PyQt5 which acts as a UI for the hardware I am trying to sell. I want to convert this desktop application into a SaaS(software as a service) where people will buy the hardware and then subscribe to the software to be able to use the hardware. My question is how do I add this functionality. I don't have much of an experience with web servers. Although I do understand that I will have have a server which will handle the requests from the PyQt app and also a database to store the information about the subscription. I am ready to learn Django or flask. How will I make the software secure, in the sense people won't be able to bypass the subscription and use the app indefinitely. I also do understand that there will be some piece of code written in python (probably using Django) running in the backend of the web server. How will the Django backend interact with a database. I also don't understand how will the PyQt app connect to the server. How will the PyQt app check for the subscription? Obviously there will be a login page. … -
How to follow a link without creating templates in Django
I want to create a small online store on Django. I have a model of books that are sold in a store class Book(models.Model): title = models.CharField("Name", max_length=100) Views def BooksView(request): books = Book.objects.all() return render(request, "main/books_list.html", {"books": books}) Books page template {% extends 'main/base.html' %} {% block title %} Books_list {% endblock %} {% block content %} <h1>Books_list</h1> {% for el in movies %} <div> <h3>{{ el.title }}</h3> <img src="{{ el.poster.url }}" class ="img-fluid"> </div> {% endfor %} {% endblock %} I have created several books, how can I make it so that I can click on {{el.title}} and go to the link of each book? -
Django: Performing a raw sql query with count()
I want to make a query to get the number of rows in the model MyTable that have the field expire (datetime) be a date in the current week. In MySQL I execute the following query: select count(expire) from MyTable where yearweek(expire) = yearweek(now()); So I can get the rows that belongs to the current week starting from Sunday. I tried replicate that using queryset in my view like this: now = datetime.now() myquery = MyTable.objects.filter(expire__year=now.year).filter(expire__week=now.isocalendar()[1]) But the thing is, Django method of querying starts from Monday, I want it for Sunday. So I though in doing a raw sql query Like this: myquery = MyTabel.objects.raw('select count(expire) from MyTable where yearweek(expire) = yearweek(now());') But it doesnt work, it doesnt output a value. How can I make this query? I'm using mysql 5.7, python 3.7 and django 2.1.11 I know these are all old versions but I can't update. -
Django/Docker: error in path for serving templates
I try to "dockerize" a Django project. I've already dockerized a Django project ; I've tried to use the exactly same project architecture. I have first config dev environnement. I buil/run the 2 containers (web and db): OK. I migrate: OK When I try to collectstatic I got an error FileNotFoundError: [Errno 2] No such file or directory: '/usr/src/app/core/static' and that right, static folder is at the same level as core app. As I config dev environnement, with Django web server, I don't have to care about serving static files. So I've try to acces localhost:8000 and got an error: That means I have an error in path config but I can find where as I replicate the same structure... project architecture - my_project |_ app |_ core |_ wsqi.py |_ settings |_ base.py |_ dev.py |_ prod.py |_ urls.py |_ requirements |_ base.txt |_ dev.txt |_ prod.txt |_ static |_ templates |_ layout |_ _footer.html |_ _nav.html |_ base.html |_ home.html |_ 404.html |_ 500.html |_ Dockerfile |_ Dockerfile.prod |_ entrypoint.sh |_ entrypoint.prod.sh |_ manage.py |_ .dockerignore |_ nginx |_ .env.dev |_ .env.prod |_ .gitignore |_ docker-compose.yml |_ docker-compose.prod.yml base.py import os from django.utils.translation import ugettext_lazy as _ BASE_DIR … -
How to use Relay's pagination feature with filterset_class from django-filter when using graphene-django
I've a Django project where I'm using django-graphene to create a GraphQL API. There's an issue when trying to use DjangoFilterConnectionField together with the relay.Connection (which is the core of pagination's feature) My model is too large and has many relationships, but let's keep things simple... class Pattern(models.Model): code = models.CharField( max_length=15 ) name = models.CharField( max_length=50 ) slug = AutoSlugField( populate_from='name', max_length=150 ) ... My node looks like: class PatternNode(DjangoObjectType): # Many fields here... ... class Meta: model = Pattern interfaces = (relay.Node,) filterset_class = PatternFilterSet As you can see, I've setup the filterset_class attribute in the Meta of my Node. So, here's that filter set: class PatternFilterSet(FilterSet): order_by = OrderingFilter( fields=( ('date', 'date'), ('name', 'name'), ) ) productcategorization__design__contains = CharFilter(method="product_categorization_design_filter") products__predominant_colors__contains = CharFilter(method="products_predominant_colors_filter") class Meta: model = Pattern fields = { 'name': ['exact', 'icontains', 'istartswith'], 'alt_name': ['exact', 'icontains', 'istartswith'], 'slug': ['exact'], 'pattern_class': ['exact'], 'sectors': ['exact', 'in'], 'products__instances': ['exact'], 'productcategorization__business': ['exact'], 'productcategorization__market_segment': ['exact', 'in'], } @staticmethod def product_categorization_design_filter(queryset, name, value): """ Does a productcategorization__design__contains filter "manually" because adding it in the Meta.fields does not work for ArrayField. Args: queryset (patterns.managers.PatternQuerySet) name (str) value (Array) comma delimited list of designs Returns: filtered_queryset (QuerySet) """ return queryset.filter(productcategorization__design__contains=value.split(",")) @staticmethod def products_predominant_colors_filter(queryset, name, …