Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to programmatically choose a parent on page creation using Wagtail admin?
I have two models, one of which is an index page for the other: class FooIndexPage(Page): category = models.IntegerField(unique=True) subpage_types = ['foo.fooPage'] class FooPage(Page): category = models.IntegerField() I obviously left out most of the fields because they are irrelevant to my question. The category field of FooPage is actually derived from other fields; I just put it that way for the sake of simplicity. What I want to achieve: Each FooPage should eventually be a child of a certain FooIndexPage in the tree structure. However, before the page is created, it is not yet clear which page is exactly the appropriate FooIndexPage (since the category is derived from the other fields, as mentioned above). There is also the possibility that it does not yet exist and must be created first. The whole thing should happen automatically when a user creates a FooPage (the user creates the page in the admin interface as a child of the home page). As soon as the user saves the page, it should be moved to the corresponding FooIndexPage, which may have to be created first. I have attempted to solve it by overriding the save method of FooPage and moving the page accordingly after … -
How can I detect third party package translations
I’ve made a Django third party app, which I’m using in a Django project, running in Docker Compose. I want to translate ValidationError messages from the app inside the project, but the makemessages command doesn’t detect them. I thought, I’ll just add them manually, but when I call makemessages after that, my manually added translations are commented out. I’ve looked for solutions, and found those SO-posts Django translations of third party apps Django's I18N with third-party apps The posts explain that I should be using symlinks, but I have had no success of doing it (same results as above), see an example below: docker-compose exec web ln -s /usr/local/lib/python3.8/site-packages/mypackage ./ docker-compose exec web python manage.py makemessages --locale=da --symlinks So I’m looking for help, what am I doing wrong or could I do something else? Maybe translate the messages inside the third party app itself like Django Rest Framework does? I hope you can help, very much looking forward for anything that can point me in the right direction. -
Add several pictures in a model from the admin page
Hi I am creating a site where I can add pictures of several events together. Hovever with the method that I am doing I feel like I am going to duplicate several lines of code, which would be efficient. My current models.py is class Csr (models.Model): title = models.CharField(max_length=80) main_image = models.ImageField(upload_to="CSR") content = models.TextField() date_of_occurence = models.DateField() def save(self, *args, **kwargs): super().save() img = Image.open(self.main_image.path) width, height = img.size # Get dimensions if width > 200 and height > 200: img.thumbnail((width, height)) # check which one is smaller if height < width: # make square by cutting off equal amounts left and right left = (width - height) / 2 right = (width + height) / 2 top = 0 bottom = height img = img.crop((left, top, right, bottom)) elif width < height: # make square by cutting off bottom left = 0 right = width top = 0 bottom = width img = img.crop((left, top, right, bottom)) if width > 200 and height > 200: img.thumbnail((200, 200)) img.save(self.main_image.path) def __str__(self): return f"{self.title}" but I want the models.py to be something like this... class Csr (models.Model): title = models.CharField(max_length=80) main_image = models.ImageField(upload_to="CSR") content = models.TextField() date_of_occurence = models.DateField() image_event1 … -
How do I perform logic in one model on integer fields from a different model?
In making an online shop, I have two models, one for customer information and another for customer settings, simplistically displayed below. My goal is to perform basic logic in the Customer model based on the 'number_input' from the MySettings model. I can easily pass the 'newsletter' into the Customer model via the foreign key, but am getting stuck when I try to pass in a second, int value. How do I perform logic in one model on integer fields from a different model? Model 1 - Customer class Customer(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) settings = models.ForeignKey('MySettings', verbose_name="Settings", on_delete=models.SET_NULL, null=True) def __str__(self): return f"{self.last_name.title()}, {self.first_name.title()}" Model 2 - MySettings: class MySettings(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) YES = 'Y' NO = 'N' NEWSLETTER_CHOICES = [ (YES, 'Yes'), (NO, 'No'), ] newsletter = models.CharField( max_length=1, choices=NEWSLETTERCHOICES, default=YES, null=True, ) number_input = models.PositiveSmallIntegerField(null=True) def __str__(self): return self.newsletter Thanks! -
How to use celery with multiple databases
I have the following celery.py file in my django project: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.default_settings") app = Celery('myproject', broker='amqp://celeryuser:someuser@example.com:5672/celeryvhost', backend='amqp://celeryuser:someuser@example.com:5672/celeryvhost', include=['tracking.tasks',] ) # Optional configuration, see the application user guide. app.conf.update( CELERY_TASK_RESULT_EXPIRES=7500, ) if __name__ == '__main__': app.start() I implement the sites framework and so I have a settings file per site which means I would also have another entry like: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.site2_settings") How can I set the settings and backend per django site in the same project? -
How to optimize DRF number queries when using properties in serializers fields?
I am working on a DRF API and I am not completely familiar with django properties. The DB relationships are classic. Companies have different jobs to which candidates can apply. Each job has several matches, match being a joined table between a job and a candidate. Matches have different statuses representing different phases of an application process. So here is the deal: I am using a drf viewset to get data from the api. This viewset uses a serializer to get specific fields, specifically the number of matches per status for a job. The simplified version of the serializer looks something like this. class Team2AmBackofficeSerializer(Normal2JobSerializer): class Meta: model = Job fields = ( 'pk', 'name', 'company', 'company_name', 'job__nb_matches_proposition', 'job__nb_matches_preselection', 'job__nb_matches_valides', 'job__nb_matches_pitches', 'job__nb_matches_entretiens', 'job__nb_matches_offre', ) The job__xxx fields are using the decorator @property, for instance: @property def job__nb_matches_offre(self): return self.matches.filter(current_status__step_name='Offre').count() The problem is each time I add one of these properties to my serializer's fields, the number of DB queries increases significantly. This is of course due to the fact that each property calls the DB multiple times. So here is my question: Is there a way to optimize the number of queries made to the DB, either by changing something … -
'NoneType' object has no attribute 'group' xhtml2pdf
Im trying to convert html to pdf using xhtml2pdf which has images encode using base64. which results in "'NoneType' object has no attribute 'group'" error thrown at self.mimetype = m.group("mime") . It seems to be caused by the regex matching done by xhtml2pdf. Any help is appreciated. Below is the html tag : <p style="text-align:middle;"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy86wFpkAAAACXBIWXMAAA9hAAAPYQGoP6dpAAAOhElEQVR4nO2deXRU1R3HP5NM9hAIQSYkISwKCMGgJIpYLXh6jJAaq6XYnloWawVLFUrEcxSXnlbbHi0iBwHRFohasS4orQoWLAcpS4uTMKSYSCJkIesQspFtkknSP14SZuY95r1582bm0c7nnPlj7lvufe/77v67v2vo7+8niH4ICXQCgjgTFERnBAXRGUFBdEZQEJ0RFERnBAXRGUFBdEZQEJ0RFERnBAXRGUFBdIYx0AlQgQnIGPilA8OByIGfEega+HUCFUD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q242R3hzXxhd4TTVm0tHiOMBu6ZnsDSy++OMMinwHL8uDtCoPcPSUbwwuZ28eCXlRc5Ut5KQVU7+VVtfG3tkF3x60h8lJGZDvuH3KFs/5BfIvSj/PqCAi0ICLnlfoRdbaYouaDd1oulRhCnstlGZ08fnT192Hv7iQoLITIshOGRoaSPEUSQGOq4HIM77DxFgLY+0oMgg4QgOJF8nMDsQbUVYeo1oBMzehLEkesQ6phF+G6Xtn4u7dL2IcFd2hQxuI/hLC7tY5ii8l42BOPnwX0M9xPcx1ATRnNJnBkIzjeldvrsAsq5tNNnEVfATp9XoiD/0wQ3J9YZQUF0RlAQnREURGcEBdEZQUF0RlAQnREURGcEBdEZQUF0RlAQnfFfYCzsGjq5tFAAAAAASUVORK5CYII= " style="vertical-align:middle" /></p> Code : from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def pdf(htmlfile, context_dict={}): template = get_template(htmlfile) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None def download(request): pdf = render_to_pdf('somehtml.html') If i remove the encoded image it works fine. This is the regex used by xhtml2pdf : "^data:(?P<mime>[a-z]+/[a-z]+);base64,(?P<data>.*)$", re.M | re.DOTALL) -
Django Django_private_chat Chat Server Deployment
I tried to deploy my chat server on digitalocean. In testing mode I normally started the server by "python manage.py run_chat_server". I recently deployed my app on digitalocean and I cannot figure out, why my chat server is not responding, if I click the “send” button. The command “python manage.py run_chat_server” works perfectly without any error: 2020-08-12 15:47:50,657:INFO:Chat server started 12.08.20 15:47:50:INFO:Chat server started The configuration in my app settings.py file looks as the following: CHAT_WS_SERVER_HOST = [‘249.79.63.412’] CHAT_WS_SERVER_PORT = 5002 CHAT_WS_SERVER_PROTOCOL = 'ws' Since I use gunicorn and psycopg2, I configured Nginx to proxy pass Gunicorn by adding a new listen=5002 to the file (and restarted nginx afterwords): server { listen 80; listen 5002; server_name 249.79.63.412; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/christian/myapp/myapp; } location /media/ { root /home/christian/myapp/myapp; } location / { include proxy_params; proxy_pass http://unix:/home/christian/myapp.sock; } } I believe there are some other configuration to be done as well on digitalocean. I use an Ubuntu 20.x server and django 2.2. Thanks a lot. -
Cant save extra data in serializer - Django rest
I have this api view where i create a post, by having javascript make a fetch POST request. Thing is, i cant get the serialized data to be valid. I looked my issue up, but i cant get get it fixed. What am i doing wrong? models.py: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) ## content = models.TextField(max_length=400, blank=False) date_posted = models.DateTimeField(auto_now_add=True) def __int__(self): return self.id serializers.py: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' def save(self): author = self.context['request'].user views.py: @api_view(['POST']) def postCreate(request): data = request.data #i tried adding it from here but invalid still #data["author"] = request.user.username serializer = PostSerializer(data=data, context={'request': request}) #it is invalid everytime if serializer.is_valid(): serializer.save() else: print(data) return Response(serializer.data) javascript code making the request: const csrftoken = Cookies.get('csrftoken'); fetch('api/post-create/', { method: 'POST', headers: { "X-CSRFToken": csrftoken, 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ content: content.value }) }) .then(response => response.json()) .then(result => { // Print result console.log("RESULT:", result); }); Im guessing i cant get the data to be validated and saved in db, because the author isnt being added somehow. Date_posted is supposed to be added automatically based on the model, right? So no need to get it from the context. Not sure … -
django: update a model value on websocket recieve
So I extend my user model to this class ProfileImage(models.Model): """ Profile model """ user = models.OneToOneField( verbose_name=_('User'), #to=settings.AUTH_USER_MODEL, to = User, related_name='profile', on_delete=models.CASCADE ) avatar = models.ImageField(upload_to='profile_image') notifications = models.FloatField(default='0') the notifications value is 0, but what I want is to give +1 to the notifications when a websocket is recieve, so How can I do that when a message is recieve? here is my consumers.py class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) other_user = self.scope['url_route']['kwargs']['username'] me = self.scope['user'] # print(other_user, me) thread_obj = await self.get_thread(me, other_user) self.thread_obj = thread_obj chat_room = f"thread_{thread_obj.id}" self.chat_room = chat_room await self.channel_layer.group_add( chat_room, self.channel_name ) await self.send({ "type": "websocket.accept" }) # await asyncio.sleep(10) async def websocket_receive(self, event): # when a message is received from the websocket print("receive", event) front_text = event.get('text', None) if front_text is not None: loaded_dict_data = json.loads(front_text) msg = loaded_dict_data.get('message') user = self.scope['user'] username = 'default' if user.is_authenticated: username = user.username myResponse = { 'message': msg, 'username': username, } await self.create_chat_message(user, msg) # broadcast the message event to be send await self.channel_layer.group_send( self.chat_room, { "type": "chat_message", "text": json.dumps(myResponse) } ) async def chat_message(self, event): # sends the actual message await self.send({ "type": "websocket.send", "text": event['text'] }) async def websocket_disconnect(self, … -
Django regroup by upper and lower case
I have a project in django, where I have to display clients in alphabetical order but names of companies can start from upper or lower case. For now my solution below display names starts from lower case in one section and name starts from the same letter, but uppercase in another section. {% regroup clients by title.0 as clients_list %} {% for client in clients_list %} {{ client.grouper }} {% for item in client.list %} {% if item.client_link %} <a href="{{ item.client_link }}">{{ item.title }}</a> {% else %} {{ item.title }} {% endif %} {% endfor %} {% endfor %} How to display name starts from upper and lower case under one section? -
django choice list (it is possible to exclude a value from the list)
TITLE_CHOICES = [ ('MR', 'Mr.'), ('MRS', 'Mrs.'), ('MS', 'Ms.'), ] class Author(models.Model): title = models.CharField(max_length=3, choices=TITLE_CHOICES) class AuthorForm(ModelForm): class Meta: model = Author fields = ['title'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.queryset = Author.objects.exclude(title='Mr.') I want to use the model in two different forms, in one it will have a default title = 'Mr.', and on the other hide or delete the Mr. value -
Show soft warning from clean method of Django Formset for Model Form
I've got a model form and a formset that I'm using successfully without issue. In my clean method of the formset I perform some logic - but one of the requirements that previously caused a ValidationError is now being changed and should just be a simple warning to the user in the template. My model form and formset look like this: class AlignmentForm(forms.ModelForm): def __init__(self, *args, employee, **kwargs): self.person = person super().__init__(*args, **kwargs) class Meta: model = Alignment fields = [ "alignment", "start_date", "end_date", ] class AlignmentFormSet(forms.BaseModelFormSet): def clean(self): if any(self.errors): return # I've trimmed out additional logic and checks # This is the area of concern alignment_error = {} for i, form in enumerate(self.forms): if not end_date: if alignment == "Wrong": alignment_error = { "alignment": alignment, "added_message": "Corrected", } if alignment_error: raise forms.ValidationError( f""" The alignment is ({alignment_error['alignment']}) and must be ({alignment_error['added_message']}). """ ) return form The current ValidationError needs to become just a message that is presented to the user in the template - but does not stop the form from validating and saving. I've tried doing something like this: if alignment_error: messages.warning( request, f""" The alignment is ({alignment_error['alignment']}) and must be ({alignment_error['added_message']}). """, ) But that didn't … -
Tensorflow on Elastic Beanstalk and Django
import tensorflow as tf with tf.Graph().as_default(): sentences = tf.placeholder(tf.string) import tensorflow_hub as hub embed = hub.Module('/tmp/module') embeddings = embed(sentences) This is from my views.py file in my django app. the execution fails at the import and shows the following error. End of script output before headers: wsgi.py child pid 29409 exit signal Segmentation fault (11) While it works fine on my local machine. I am currently using a t3 medium instance. Any tips on how to fix this ? -
how to save data without using database?
hello guys so i made this website that intergrate with my router to manage the user inside it,but i have this question i want to ask so my website only visualise the data that it got from the router and i have this voucher system to give out voucher to the user to access the network as right now i save this voucher in my database but due to each of the voucher data that it i save to the database and from the database it display to the web, it all from data that it got from the router<-- and here come the problem is that the data is not valid because if the admin access the router and delete one of the voucher profile it will cause and error,because the voucher in database is been deleted from the router, is there any way i can do this so that i dont need to use database to save this? thanks -
got unexpected result in post data using ajax
when I post data to the database using ajax code I got an unexpected result. I can post data but output showing is wrong. My ajax code not execute properly views.py def notification(request): user = request.user if request.method == 'POST': property_id = request.POST['property_id'] owner = request.POST['owner_id'] property_object = Property.objects.get(id=property_id) owner_object =User.objects.all().get(username=owner) notification = "Hi {}, {} \n have interested in your property '{}'".format(property_object.owner, user.first_name, property_object.headline) property_object.notify.add(user) notifications = Notifications.objects.create(notification=notification, property=property_object, owner=owner_object) notifications.save() return JsonResponse({"msg":"success"}) ajax code $(document).ready(function(e){ $(document).on('submit','#request-btn',function(e){ e.preventDefault(); var property_id = $this.attr('value'); var owner_id = $this.attr('value'); $.ajax({ type:'POST', url:"{% url 'notification' %}", data:$('#notify_form').serialize(), dataType:'Json', success:function(data){ if(data.msg == "success"){ alert('data submitted') } } }); }); }); I'm expecting a success alert box, but got {"msg": "success"} in a white window like 'httpResponse' -
ValidationError: "value must be a decimal number"
I have the following Model: class Listing(models.Model): product = models.CharField(max_length=64) description = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Listings") category = models.CharField(max_length=64, blank=True) created = models.DateField() starting_price = models.DecimalField(max_digits=6, decimal_places=2, default=decimal.Decimal(0)) current_price = models.DecimalField(max_digits=6, decimal_places=2, default=starting_price) In my views.py I use an instance of a Django Form class to ask the user for the input. I get the following error ['“auctions.Listing.starting_price” value must be a decimal number.'] However, when I check the Local Vars on the error page I can see the the value of starting_price = Decimal('10.00') So clearly the value of auctions.Listing.starting_price is a decimal! There are no other entries which could cause this problem. The Form I use looks like that: class NewListingForm(forms.Form): product = forms.CharField(max_length=64) description = forms.CharField(widget=forms.Textarea) category = forms.CharField(max_length=64, required=False) starting_price = forms.DecimalField(max_digits=6, decimal_places=2) When Posting I evalute the data like so: if entry_form.is_valid(): product = entry_form.cleaned_data["product"] description = entry_form.cleaned_data["description"] category = entry_form.cleaned_data["category"] starting_price = entry_form.cleaned_data["starting_price"] And I save the model entry via: listing = Listing(product=product, description=description, user=user, category=category, created=created, starting_price=starting_price) listing.save() I'd really appreciate any ideas on that. -
How can we pass the context dictionary in redirect function in django
I want to pass that 'liked' variable as a context dictionary through the redirect function. Please help me to do so. def likepost(request, post_id): user = request.user post_connected = post.objects.get(id=post_id) mypost = like_post.objects.filter(user=user, liked=post_connected) if mypost.exists(): mypost.delete() liked = False else: mylike = like_post.objects.create(user=user, liked=post_connected) mylike.save() liked = True return redirect('/') -
Detect change in default values of a table ( Django )
Scenario : I am using django to render a form, the form contains a table with multiple values. Now I want to detect if the user has changed the default values ( sent from the back-end ) and trigger an event (that changes the value of a variable say x to True or False). Questions: Is there a way to handle this via the frontend exclusively? If yes,what should I look into ? Already looked up : jquery 'change' detection ( does not work for my case as changing back to default values cant be detected ) looping and comparison of values ( this is possible but gets ugly as the size of the table increases ) form.changed_data ( as the data being transferred is large in size, re rendering the page with an exception will not be a choice ) -
How to output the value of the foreign key without using Django Rest Framework
I have a problem with the Json values that are released by the Django. After I serialize my object from the views.py the user outputs a the id of the primary key not the value of the primary key. I tried the Natural keys technique in models.py. How can I get the value output instead of id? views.py def load_post(request): serials = serialize('json', Post.objects.all().order_by( "-id")) return JsonResponse(serials, safe=False) models.py from django.contrib.auth.models import AbstractUser from django.db import models #Natural Key technique class UserManager(models.Manager): def get_by_natural_key(self, username): return self.get(username=username) class User(AbstractUser): objects = UserManager() class Post(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey( 'User', on_delete=models.CASCADE, related_name='user') post = models.TextField(max_length=280, blank=True) timestamp = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(default=0) def __str__(self): return f"id: {self.id}, username: {self.user}, post: {self.post}, datetime: {self.timestamp}, likes: {self.likes}" Json output [ { "model":"network.post", "pk":3, "fields":{ "user":1, #This should be a username "post":"afefawfawefawf", "timestamp":"2020-08-07T14:38:54.444Z", "likes":0 } }, { "model":"network.post", "pk":2, "fields":{ "user":1, #This should be a username "post":"afefawfawefawf", "timestamp":"2020-08-07T14:38:18.687Z", "likes":0 } }, { "model":"network.post", "pk":1, "fields":{ "user":2, #This should be a username "post":"sfoawefoawemfowf", "timestamp":"2020-08-07T14:28:09.784Z", "likes":0 } } ] -
Django model with many ownership
I have write this model: class Customer(models.Model): name = models.CharField(max_length=255) surname = models.CharField(max_length=255,) owners = models.ManyToManyField(User) I would like to add current user into owners field on save. I don't want declare this in a form but in model, overriding save method. As follow: def save(self, *args, **kwargs): self.owners = request.user super(Customer, self).save(*args, **kwargs) but obviously request doesn't exist... what I can define this in model? -
How to upload image to django app by using request and json
I wan to use some code for uploading some data to my django app. Im using this code: r = requests.post( 'http://127.0.0.1:8000/api/object/', json=data, ) It's working great. I have just added image (model.ImageField) to my model and I want to use above code to update it. I still have some problem with encoding my image. Im trying to read image and add to my previous dict with some data (data is dict with a few fields): with open('image.JPG', 'rb') as imageFile: my_image = base64.b64encode(imageFile.read()).decode() data.update({"image":my_image}) I got the same error: "The submitted data was not a file. Check the encoding type on the form." Is it possible to convert image to format which will be ok with request and json? Could you give me some advice? -
multiple scheduler object django
Is there way to add two or more jobs into scheduler object. When the server runs, i need to download from two different databases on mssql server. I have this piece of code: schedulers.py from apscheduler.schedulers.background import BackgroundScheduler SCHEDULER_POOL = {"background_scheduler": BackgroundScheduler()} and my model.pulling_scheduler.py class PullingScheduler: # pylint: disable=too-few-public-methods TIMEOUT = 60 def __init__(self): self.scheduler = SCHEDULER_POOL['background_scheduler'] self.db_sync = DatabaseSynchronizator() def start_pulling(self): self.scheduler.add_job(self.db_sync.pull_for_each_event, 'interval', seconds=self.TIMEOUT) self.scheduler.start() For this single job it works, but i want to add another job, for another model, which have to pull records form different DB, on mssql -
Output a pandas DataFrame in Django with dynamic shape
I have a pandas DataFrame that has different columns based on a query that generate this DataFrame in the backend. To output it in Django, an easy approach is to use .to_html() method, but it wouldn't work for my use case as I need to make multiple adjustments to the table properties in the template. Is there a way to output it dynamically? I thought I can send two copies to Template, one with .to_dict() method to use for generating headers and one with to_dict(orient='records') to use for generating the table, but it doesn't work as expected. df = pd.DataFrame({ 'col1': [1,2,3,4], 'col2': ['A','B', 'C', 'D'] }) context = { 'df_dict': df.to_dict(), 'df_rec': df.to_dict(orient='records') } And in the HTML template: <table> <thead> <tr> {% for key, value in df_dict.items %} <th>{{ key }}</th> {% endfor %} </tr> </thead> {% for rec in df_rec %} <tr> {% for ii in rec %} <td>{{ rec.ii }}</td> {% endfor %} </tr> {% endfor %} </table> Table renders with correct number of rows, but nothing in the table renders correctly. -
Django filters: custom filter methods with different lookup expressions
I'm using Django filters along with Django Rest Framework to create filters for API views. They have a nice syntax that I show in the age field filter below defined in the class meta fields = {'age': ['exact', 'gte', 'lte', 'lt', 'gt', 'in']} which allows the creation of all these greater than or equal to, less than or equal to, less than, greater than etc filters for the field all at once... With a custom field like the artworks_count I also show below, however, it seems I need to add different methods for each lookup expression, which is quite repetitive. I'm just wondering if there isn't a better way to do this? (perhaps using something other than the NumberFilter?) that would take a lookup_expression as an argument and allow me to construct a single method using it class UserFilter(django_rest_filters.FilterSet): artworks_count__gte = django_rest_filters.NumberFilter(method="filter_artworks_count__gte") class Meta: model = User fields = {'age': ['exact', 'gte', 'lte', 'lt', 'gt', 'in']} def filter_artwork_count__gte(self, qs, name, value): return qs.annotate(art_count=Count('artworks')).filter(art_count__gte=value)