Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allauth returns 500 when in production
I am having some trouble with my Django 1.8.14 application in combination with allauth 0.27. Whenever I deploy my application and try to authenticate with wrong credentials, I get a 500 error. This doesn't happen when I run my application locally. I have a django.contrib.sites.models.Site instance with id=SITE_ID so I can't really figure what is going wrong. Internal Server Error: /accounts/login/ Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.5/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py", line 34, in _wrapper return bound_func(*args, **kwargs) File "/usr/local/lib/python3.5/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py", line 30, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "/usr/local/lib/python3.5/site-packages/allauth/account/views.py", line 98, in dispatch return super(LoginView, self).dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.5/site-packages/allauth/account/views.py", line 66, in dispatch **kwargs) File "/usr/local/lib/python3.5/site-packages/django/views/generic/base.py", line 89, in dispatch return handler(request, *args, **kwargs) File "/usr/local/lib/python3.5/site-packages/allauth/account/views.py", line 81, in post if form.is_valid(): File "/usr/local/lib/python3.5/site-packages/django/forms/forms.py", line 184, in is_valid return self.is_bound and not self.errors File "/usr/local/lib/python3.5/site-packages/django/forms/forms.py", line 176, in errors self.full_clean() File "/usr/local/lib/python3.5/site-packages/django/forms/forms.py", line 393, in full_clean self._clean_form() File "/usr/local/lib/python3.5/site-packages/django/forms/forms.py", line 417, in _clean_form cleaned_data = self.clean() File "/usr/local/lib/python3.5/site-packages/allauth/account/forms.py", line 152, in clean **credentials) File "/usr/local/lib/python3.5/site-packages/allauth/account/adapter.py", line 462, in authenticate self.authentication_failed(request, … -
Get all objects from severall models that share the same foreign key - Is it possible?
I am facing a problem designing a database with Django framework that i can't seem to solve. Say i have the following models: class ModelA(models.Models): field1 = ..... field2 = ..... class ModelB(models.Model): fieldA = models.ForeignKey(ModelA) ... class ModelC(models.Model): fieldA = models.ForeignKey(ModelA) ... class ModelD(models.Model): fieldA = models.ForeignKey(ModelA) ... My question is: Is it possible to get all objects from Models B, C and D that share the same oject from ModelA? I do not wish to query each model (B, C or D) individually because in reality i have many more models. Any help is much apreciated. -
Django Rest Framework Many to Many field related to itself
I have an AngularJS project that used Django as a framework through the Django Rest Framework (DRF). I've created a Group model and set up a serializer class for it, however I want to now establish a new field on that model called related_groups, which would reference the same model (Group) as an array of primary keys. I don't know if it's possible to self-reference in the serializer, though, and I don't know how else to pass through related groups from the front-end, which can be picked and chosen by the users who own the group. class GroupSerializer(serializers.ModelSerializer): class Meta: model = mod.Group fields = ( 'group_id', 'group_name', 'category', 'related_groups', ) and the representation appears to be exactly what I want: GroupSerializer(): group_id = IntegerField(read_only=True) group_name = CharField(max_length=100) category = CharField(max_length=256, required=False) related_groups = PrimaryKeyRelatedField(many=True, queryset=Group.objects.all(), required=False) I'm not getting any errors on save, but I'm also not getting the values into my DB. Am I able to represent many-to-many relationships from a model back to itself with DRF? Or do I need to have another serializer just for the relationship table? The documentation for DRF doesn't use self-referential models, so I wonder if it's a poor design choice. -
Python Django, add label to insert information forms
I'm trying to make a form whit just one label with the possibility of add an other one. I know I can make a form referenced with a model. and I know how to make without model. My first question is about if I can use a form without use models or forms.py. The second is how if I have one row I can add an other one. Let me explain what I would like to to. I would like to show the result of a information typed in the textboox and i Already did it but le suppose I need to plus an other num. I can imagine something like this, def plus(request, *args): to plus all the numbers inserted. Let show you my code, I hope you can help me. Regards ! URLS.PY from django.conf.urls import url, include from django.contrib import admin from .import views from .views import MiVista urlpatterns = [ url(r'^hola$', views.inicio), url(r'^suma/(\d+)/(\d+)/$',views.suma), url(r'^indice/', MiVista.as_view()), url(r'^datos$', views.datos), VIEWS.PY def datos(request): if request.method == "POST": form = NameForm(request.POST) x = request.POST['your_name'] return render(request, 'info.html', {'x': x}) else: form = NameForm() #hacemos formulario en blanco return render(request, 'datos.html', {'form': form}) FORMS.PY from django import forms class NameForm(forms.Form): your_name … -
How to check {% if user.is_authenticated %} when in React?
If I'm using a Django-React stack where I'm using React instead of Django templates, how do I check on the React-frontend whether a user is logged in or not? -
In Django, how do I update a user profile if a model is added to database?
I'm creating a site where users can upload files. I have my upload form working, and it correctly associates the current user with the uploaded file. Once it's uploaded however, I would like the User Profile model to update the number of files uploaded for that specific user. I'm using django-allauth with a custom admin model. models.py (works to recognize current user) class ConfigFiles(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True) Printer = models.CharField(_('Printer Model'), max_length=100, blank=True, null=True, unique=False, help_text="Something like 'i3'") printerbrand = models.CharField(_('Printer Brand'), max_length=100, blank=True, null=True, unique=False, help_text="Something like 'Prusa'") Plastic = models.CharField(_('Plastic'), max_length=40, blank=True, null=True, unique=False, help_text="Something like 'ABS' or 'Nylon'") HDConfig = models.FileField(_('High Detail, Slow Speed'), upload_to=UploadedConfigPath, validators=[validate_file_extension], help_text="Displayed as HD on Infinity-Box") LDConfig = models.FileField(_('Fast speed, Low Detail'), upload_to=UploadedConfigLDPath, validators=[validate_file_extension], help_text="Displayed as FAST on Infinity-Box") pub_date = models.DateTimeField(_('date_joined'), default=timezone.now) And here's my custom admin models.py (doesn't auto update configuploaded) class UserProfile(models.Model): user = models.OneToOneField(DemoUser, primary_key=True, verbose_name='user', related_name='profile') avatar_url = models.CharField(max_length=256, blank=True, null=True) configuploaded = models.IntegerField(_('Number of uploaded Config files'), default=0, unique=False) filesuploaded = models.IntegerField(_('Number of uploaded STL files'), default=0, unique=False) dob=models.DateField(verbose_name="dob", blank=True, null=True) def __str__(self): return force_text(self.user.email) class Meta(): db_table = 'user_profile' Ideally, whenever the user uploads a file the configuploaded variable increase correspondingly. Is … -
Can request.user be False while request.user.is_authenticated is True?
A snippet out of Django Rest Framework: class IsAuthenticated(BasePermission): def has_permission(self, request, view): return request.user and is_authenticated(request.user) def is_authenticated(user): if django.VERSION < (1, 10): return user.is_authenticated() return user.is_authenticated Is there a practical and relevant case where my own code would return unexpected or different results from the above? class IsAuthenticated(BasePermission): def has_permission(self, request, view): return request.user.is_authenticated -
Why is a auto_now=True field designed to not update when using QuerySet.update()?
from django: The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that. Both will have to execute an update query, so what is the reason behind save.() updating the auto_now=True field and QuerySet.update() not updating the field? -
Angular Routing in Django
I am new to Angular JS and trying to implement routing in a Django App. My Html code is:- <body> <nav class="navbar navbar-inverse" ng-app="QuizRouting"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">WebSiteName</a> </div> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#/page1">Page 1</a></li> <li><a href="#">Page 2</a></li> <li><a href="#">Page 3</a></li> </ul> </div> </nav> <div ng-view></div> </body> My JS code is :- var app = angular.module('QuizRouting',['ngRoute']); app.config(function($routeProvider) { $routeProvider .when("quiz/page1", { templateUrl: "/quiz/templates/quiz/page1.html" }); }); I have included all the prerequisites for Angular and angular routing. But on clicking on the page 1 link the required template is not rendered. this is the page1.html:- <div> <h1>Its Working!</h1> </div> -
Clean method in django model not triggered
In my model my clean method limits to have only one active record So in clean method I limit only one combination for each lease where is active = True and is_terminated = false class LeaseTerm(CommonInfo): version = IntegerVersionField( ) start_period = models.ForeignKey(Period, related_name='start_period' ) end_period = models.ForeignKey(Period, related_name='end_period') lease = models.ForeignKey(Lease) increase = models.DecimalField(max_digits=7, decimal_places=2) amount = models.DecimalField(max_digits=7, decimal_places=2) is_terminated = models.BooleanField(default=False) def clean(self): model = self.__class__ if self.lease_id and (self.is_terminated == False) and model.objects.filter(lease=self.lease, is_active=True ).exclude(id=self.id).count() > 0: raise ValidationError('!Lease has a active Term , terminate existing term prior to creation of a new one'.format(self.lease)) And this is view to create a new term def term_new(request,pk,uri): lease = get_object_or_404(Lease, pk=pk) title = 'term' uri = _get_redirect_url(request, uri) if request.method == "POST": form = LeaseTermForm(request.POST) form.lease = lease if form.is_valid(): term = form.save(commit=False) #term.lease = lease term.save() messages.add_message(request, messages.SUCCESS, str(term.id) + "-SUCCESS Object created sucssefully") return redirect(uri) else: form = LeaseTermForm() return render(request, 'object_edit.html', {'form': form, 'title': title, 'extend': EXTEND}) form class LeaseTermForm(forms.ModelForm): class Meta: model = LeaseTerm fields = [ 'amount', 'start_period','end_period', 'increase','is_terminated' ] However the clean method is not triggered any more, it dosent prevent users from creating new recods under same lease with is_active= true and … -
Django - Group by column and where on a different column
Problem statement These are my django models: class Status(models.Model): status = models.CharField(max_length=20) class Project(models.Model): client = models.ForiegnKey(Client) class TicketRequest(models.Model): status = models.ForiegnKey(Status, related_name='ticket_requests') project = models.ForiegnKey(Project) created = models.DateTimeField() Required result status.value | client.id | count --------------+-------------+--------- is_assigned | 4 | 2 is_closed | 4 | 66 is_open | 4 | 7 Solutions tried 1. Querying the Status model Status.objects.filter( ticket_requests__project__client_id=4 ).values('value').annotate( count=Count('ticket_requests__project__client') ) This returns the following data: [{'count': 2, 'value': u'is_assigned'}, {'count': 66, 'value': u'is_closed'}, {'count': 7, 'value': u'is_open'}] which is perfect! But I need to filter the queryset on TicketRequest.createdwith filters such as today, this week and month. These filters need to be reused a lot, so I created a handy helper. Shortened for brevity def qs_time_range(qs, time_range, field_name): now = timezone.now() if time_range == 'month': past = now - timedelta(days=30) return qs.filter( **{field_name + '__date__range': [past, now]} ) Problem When I use the helper to filter the ticket requests, the results are not what I expect. filters.qs_time_range( Status.objects.filter(ticket_requests__project__client_id=1), 'month', 'ticket_requests__created' ).values('value').annotate( count=Count('ticket_requests__project__client') ) Result [{'count': 27, 'value': u'is_assigned'}] When instead this should be the result: value | count -------------+------- is_assigned | 3 is_closed | 3 is_open | 3 (3 rows) -
Display url variable from views.py in Django template
I want have my url come from views.py and then I can pass it as variable to href tag in template. views.py: context { 'urlLink': "{% url 'myapp:theURL' %}" ... } index.html: <a href="{{ urlLink }}" LINK 1 </a> I have the above and it is not working. I have also tried <a href="{{ urlLink|escape }}" LINK 1 </a> but no success. -
Can I disable delete() in django-rest-famework by not calling object.delete()
I have a pattern that I use: class View(generics.RetrieveUpdateDestroyAPIView): ... def delete(self, request, pk): if cantDelete(): return JsonResponse({ 'success' : False, 'message': "Can't delete this"}) self.get_object().delete() return JsonResponse({ 'success' : True, 'message': "Deleted"}) I have a reason to believe that the objects are sometimes being deleted if cantDelete() is true. Is this a bad pattern? Can't I disable delete() in this way? I will do some experiments, but it's a production back end and a bit of an emergency, so if anyone can chime in with an answer before I get a chance to post an answer myself, it would be much appreciated. -
Override django admin change_list with multiple admin sites not working
I've exposed multiple databases in the admin site using the link here: django-docs. Now, I need to override the change_list.html for one of the models exposed in the default admin website and add a button on the page. Here's the code in the file project/templates/admin/my-app/my-model/change_list.html {% extends "admin/change_list.html" %} {% load i18n %} <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { alert("Hi!"); }); </script> Somehow this javascript isn't working. I've overridden django admin html before, but with this project I'm exposing multiple databases (kind of multiple admin sites) so is there something different that needs to be done to override the admin html here? -
Django + Bootstrap + Collapse + Item.PK = Issue
My Template: {% for Entry in object_list %} <li style="list-style-type: none; margin-bottom: 2px;"> <a data-toggle="collapse" href="#{{ Entry.pk }}">+</a> <big><a style="text-decoration: none;" target="_blank" href="{{ Entry.url }}">{{ Entry.title }}</a></big> <small style="color: tomato;">[{{ Entry.tickers|upper }}] </small><small style="color: silver;">[{{ Entry.domain }}] <i>{{ Entry.timestamp|shortnaturaltime }}</i> </small> <div class="collapse" id="{{ Entry.pk }}">{{ Entry.summary }}</div></li> {% empty %} <li>No listings yet.</li> {% endfor %} If I use {{forloop.count}} or {{object.pk}} for ID and href rendering, collapse doesn't work, but if I hardcode the ID and href it works as it should. What could be the issue here? -
Make view accessible only through redirect and from only one view in Django
How do I make a view to be only accessible through redirect and from a only a particular view? urls.py: #Assuming namespace = 'myApp' url(r'^redarekt/$', views.redarekt, name='redarekt'), url(r'^reciva/$', views.reciva, name='reciva'), views.py: @login_required() def redarekt(request): if request.user.is_authenticated() and request.user.is_active: return HttpResponseRedirect(reverse('myApp:reciva')) @login_required() def reciva(request): if request.user.is_authenticated() and request.user.is_active: #CHECK IF IT IS A REDIRECT AND COMING FROM redarekt execute(request) raise Http404 raise Http404 How do I make reciva to be only accessible through redirect and from a only redarekt? -
Updating information on a webpage continually in Django framework with server side trigger
I am fairly new to the field of web application design. I am learning and using django 1.8 and I would like to know how should I update the contents of a webpage without manually refreshing the page. The contents on the webpage will display data from a database. Every time the value in the DB changes beyond a dead band, the data should be published to the web page. The server should be responsible for triggering the value update in all clients. -
Django 1.10 - Different templates for each OneToOne model
Basically, I'm trying to get the current user type, by using the OneToOne models you can see below and display different template "parts" specific for each model. I researched a bit and found out about type() and hasattr(). I was wondering if there's any way I can use them in templates or do you have any better suggestions? Thanks! models.py class Type1(models.Model): user = models.OneToOneField(User) company_name = models.CharField(max_length=100) def __unicode__(self): return self.company_name class Type2(models.Model): user = models.OneToOneField(User) first_name = models.CharField(max_length=30) second_name = models.CharField(max_length=30) def __unicode__(self): return self.first_name views.py def Type1Registration(request): if request.user.is_authenticated(): return HttpResponseRedirect('/') if request.method == 'POST': form = Type1Form(request.POST) if form.is_valid(): user = User.objects.create_user(username=form.cleaned_data['username'], email=form.cleaned_data['email'], password=form.cleaned_data['password']) user.save() type1 = Type1(user=user, company_name=form.cleaned_data['company_name']) type1.save() return HttpResponseRedirect('/') else: return render(request, 'type1_register.html', {'form': form}) else: form = Type1Form() context = {'form': form} return render(request, 'type1_register.html', context) def Type2Registration(request): if request.user.is_authenticated(): return HttpResponseRedirect('/') if request.method == 'POST': form = Type2Form(request.POST) if form.is_valid(): user = User.objects.create_user(username=form.cleaned_data['username'], email=form.cleaned_data['email'], password=form.cleaned_data['password']) user.save() type2 = Type2(user=user, first_name=form.cleaned_data['first_name'], second_name=form.cleaned_data['second_name']) type2.save() return HttpResponseRedirect('/') else: return render(request, 'type2_register.html', {'form': form}) else: form = Type2Form() context = {'form': form} return render(request, 'type2_register.html', context) -
python/django: model object has no attribute 'prefetch_related'
I have created a model 'VehicleDetails' in which a user can fill the details of a vehicle and another model 'TripStatus' in which he updates the vehicle location. I wanted to get the latest location for which i did as in my below code. I use prefetch_related in my view to returns the location values for a particular vehicle. But, when after running the server, it raises an error : "TripStatus object has no attribute 'prefetch_related'". I would appreciate helping me solve this. models.py: class VehicleDetails(models.Model): Vehicle_No = models.CharField(max_length=20) class TripStatus(models.Model): vehicledetails = models.ForeignKey(VehicleDetails, related_name='statuses') CHOICES = (('Yet to start', 'Yet to start'),('Trip starts', 'Trip starts'), ('Chennai','Chennai'), ('Vizag', 'Vizag'), ('Kolkata', 'Kolkata')) Vehicle_Status = models.CharField(choices=CHOICES, default="Yet to start", max_length=20) statustime = models.DateTimeField(auto_now=False, auto_now_add=True) views.py: def status(request): tripstatus = TripStatus.objects.all().latest('statustime').prefetch_related('statuses') context = { "tripstatus": tripstatus, } return render(request, 'loggedin_load/active_deals.html', context) template: {% for status in vehicledetails.statuses.all %} {{status.Vehicle_Status}} {% endfor %} -
python suds : Server raised fault : Unmarshalling Error: For input string: "" '
im trying to use a soap api in this address https://bpm.shaparak.ir/pgwchannel/services/pgw?wsdl basically this is 2 part proccess lets call them a adn b im having trouble with one of methods in part b but a works fine this is a def a(request): try : client = Client(url="https://bpm.shaparak.ir/pgwchannel/services/pgw?wsdl" ) except : return HttpResponse('error1') a_response = client.service.bpPayRequest(params1=params1 , param2=param2 ) a works fine without any problem this is b : def b(request): try : client = Client(url="https://bpm.shaparak.ir/pgwchannel/services/pgw?wsdl" ) except : return HttpResponse('error1') b_response = client.service.bpVerifyRequest(params1=params1 , param2=param2 ) here is the response for b WebFault at /api/b Server raised fault: 'Unmarshalling Error: For input string: "" ' Request Method: GET Request URL: http://site.in/api/b Django Version: 1.9.7 Exception Type: WebFault Exception Value: Server raised fault: 'Unmarshalling Error: For input string: "" ' Exception Location: python/lib/python/site-packages/suds/client.py in process_reply, line 670 Python Executable: Python Version: 3.4.4 unfortunately the api doesn't have python tech or python sample code (basically they only support php/asp and wont response if you're using anything else ) so im converting this code from their php sample ... in the php sample they mention namespace in their calls could this be the cuz of the problem ? try { $client = @new … -
Slack Bot Interactive Messages
I'm new at Slack Bot integrations. I want to have buttons on my message, so my code is message = { "text": "Would you like to play a game?", "attachments": [ { "text": "Choose a game to play", "attachment_type": "default", "actions": [ { "name": "chess", "text": "Chess", "type": "button", "value": "chess" } ] } ] } return sc.api_call("chat.postMessage", as_user="true", channel=channel_id, text=message) but in Slack channel I see this text=Would+you+like+to+play+a+game%3F&attachments=%5B%7B%27text%27%3A+%27Choose+a+game+to+play%27%2C+%27attachment_type%27%3A+%27default%27%2C+%27actions%27%3A+%5B%7B%27text%27%3A+%27Chess%27%2C+%27type%27%3A+%27button%27%2C+%27name%27%3A+%27chess%27%2C+%27value%27%3A+%27chess%27%7D%5D%7D%5 why this happen?? Thanks -
Setting up WebSockets with Django Channels on AWS Elastic Beanstalk
I'm trying to set up WebSockets on AWS instance. Since I use Django for my webapp, for WebSocket support I use Django Channels. I deployed the app using AWS Elastic Beanstalk, but I get the error: WebSocket connection to 'ws://xxx.elasticbeanstalk.com/' failed: Error during WebSocket handshake: Unexpected response code: 200. After some research I found that I need to set up TCP on port 80 and SSL on 443 instead of HTTP and HTTPS, which I did, but without change, I still get the error. I also disabled load balancing across multiple Availability Zones with no success. I don't know if the EB config file makes problem, since I have only WSGIPath set and not the ASGI which is used by Daphine and Channels. There is no ASGIPath tag to try this. I found an article about new Application Load Balancer, but since it is a quite new service, I wasn't able to find anything for WebSockets with Django. Django Channels is also new, so not many questions and posts about it as well. -
django image upload rest framework and test client
I'm trying to upload a picture with rest framework. It almost works, however when I save the file I have this on the top of my file: --BoUnDaRyStRiNg Content-Disposition: form-data; name="plop.png" If I delete those lines, I can perfectly read my picture, but I don't know how to rid of them. models.py class GenericUser(User): avatar = models.ImageField(upload_to=user_directory_path) views.py class AvatarView(APIView): parser_classes = (FileUploadParser,) def post(self, request): up_file = request.data['file'] user = get_object_or_404(GenericUser, pk=request.user.id) user.avatar.save(up_file.name, up_file) user.save() return Response(status=204) tests.py cl = Client(HTTP_AUTHORIZATION="Token {}".format(token)) with open(MY_FILE, 'rb') as f: data = f.read() res = cl.post('/serunny/avatar', {"plop.png" : data}, HTTP_CONTENT_DISPOSITION="attachment; filename=plop.png;") any hints, how I could make this work? -
How to make rotation of some resourse for threads?
I have the Community django model that contains ForeignKey field app that just contains access token for some rest api. class Community(models.Model): app = models.ForeignKey("VkApp") domen = models.CharField(max_length=300) @property def api(self): if self.app: access_token = self.app.access_token else: access_token = "" return PublicApiCommands(access_token=access_token, domen=self.domen) def get_posts(self, count): return self.api.get_post_list(count) class VkApp(models.Model): access_token = models.CharField(max_length=300) The method get_posts makes call to api property and returns the instanse of PublicApiCommands class. PublicApiCommands is just the wrapper of api of rest service. It contains methods that makes some sort of requests.get('api.vk.com/bla?bla=bla') Now I want to switch app field to ManyToManyField from ForeignKey so that it will contain some set of access tokens. So I will have the ability to controll one commynity by more than 1 access token. And different communities will have either the same set of access tokens or completely different. I want to call get_posts method for different communities asynchronously (by making celery tasks for each community). But the rest api server limits count of calls to its api per second. So I need to forbid using of the same access token in two different threads. I have to choose free access token from the community.app_set.all(). I suppose that I need … -
Chaining filters
Django 1.10.1 On a page I have prepared a lot of controls. Some of them are organized as dynamically changing formsets. So, I don't even know how many of them are present. I need a chained filters with AND, OR and NOT logical operations. For example, I need something like this: Entry.objects.filter(headline__startswith='What').exclude(pub_date__gte=datetime.date.today()).filter(pub_date__gte=datetime(2005, 1, 30)).filter(Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)) Once more the number of filters is changing. I was planning to ac like that: loop through request.POST and depending on a dozen of conditions prepare a string. The same string: "Entry.objects.filter(headline__startswith='What').exclude(pub_date__gte=datetime.date.today()).filter(pub_date__gte=datetime(2005, 1, 30)).filter(Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))" So, the string is correct. But I can't make it work with exec(). I asked here: why it is not working. And the answer was: it will not work, run the Python code directly. I can construct something like that: entries = Entry.objects.filter( **kwargs ) But this is just one filter. I can't imagine how to chain such filters. Could you help me here&