Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, Querysets. How to perform search on 400mb sql query set faster?
I Have a problem. I'm working with a 400mb postgres database. I have to perform searches with a lot of different filters. It takes me around a minute to load the page. example from views.py, the task is to search all the possible combinations of word's letters. Like cat > act > atc etc. : def neighb(): count = 0 words = [] mylist = re.findall(r'\w', word) combinations = (list(itertools.permutations(mylist))) result = '' for comb in combinations: for letters in comb: result += letters if data.filter(form_v=result).exists(): count += 1 words.append(result) result = '' return count, words So, is there some way to make it faster? I have no ideas... Thanks! Best regards, Vladislav. -
I am getting the following error in my Django app Parent module '' not loaded, cannot perform relative import
I have been trying to figure out Django + Celery + RabbitMq. Everything was running fine until I tried to import the Post model. When I try to start the worker I get the following error Parent module '' not loaded, cannot perform relative import This is my file structure environ\ |-src\ |-blog\ |-migrations\ |-static\ |-templates\ |-templatetags\ |-__init__.py |-admin.py |-forms.py |-models |-tasks |-urls |-views and this is my tasks.py file from celery import Celery import requests from bs4 import BeautifulSoup from .models import Post import random import re # from django.contrib.auth.models import User import os app = Celery('tasks', backend='rpc://', broker='amqp://localhost//') @app.task def add(x, y): return x + y @app.task def reverse(string): return string[::-1] @app.task def p_panties(): def swappo(): user_one = ' "Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0" ' user_two = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)" ' user_thr = ' "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko" ' user_for = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:10.0) Gecko/20100101 Firefox/10.0" ' agent_list = [user_one, user_two, user_thr, user_for] a = random.choice(agent_list) return a headers = { "user-agent": swappo(), "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3", "accept-encoding": "gzip,deflate,sdch", "accept-language": "en-US,en;q=0.8", } pan_url = 'http://www.panvideos.com' shtml = requests.get(pan_url, headers=headers) soup … -
Is it possible to list channels stored in a Group?
Is it possible to access the list of channels added in a Group with django-channels? def consumer(message): Group("group_name").add(message.reply_channel) channel_list = Group("group_name").??? -
How to fix the arteria contact form error in django cms?
I just recently installed and added an arteria contact from the Django cms marketplace. The only thing I didn't setup all the way as the e-mail configurations. Anyways, when I added an input form to test it out, I got a connection error: ConnectionRefusedError at /en/contact/ [Errno 111] Connection refused then I get this at the bottom at line 57 47 48 </div> 49 50 </div> 51 </nav> 52 <div class="container-fluid"> 53 <div class="row" style="padding-top: 10px;"> 54 <div class="col-md-4"> 55 {% block sideleft %} 56 <ul id="events-upcoming"> 57 {% placeholder "side1" %} 58 </ul> 59 <ul id="events-past"> 60 {% placeholder "side2" %} 61 </ul> 62 {% endblock sideleft %} 63 </div> 64 <div class="col-md-8"> 65 66 {% block content %} 67 -
Django custom decorator user_passes_test() can it obtain url parameters?
Can Django's user_passes_test() access view parameters? For example I have view that receives an id to retrieve specific record: def property(request, id): property = Property.objects.get(id=int(id)) The record has a field named user_id that contains the id for user that originally created record. I want users to be able to view only their own records otherwise be redirected. I'd like to use a custom decorator which seems simple and clean. For custom decorator is there some variation of something like this that will work? @user_passes_test(request.user.id = Property.objects.get(id=int(id)).id, login_url='/index/') def property(request, id): property = Property.objects.get(id=int(id)) I have tried creating separate test_func named user_is_property_owner to contain logic to compare current user to property record user_id @user_passes_test(user_is_property_owner(id), login_url='/index/') def property(request, id): property = Property.objects.get(id=int(id)) def user_is_property_owner(property_id): is_owner = False try: Property.objects.filter(id=property_id, user_id=user_id).exists() is_owner = True except Property.DoesNotExist: pass But having trouble getting current user id and the property id from the request into the user_is_property_owner decorator function. -
ForeignKey Field in django admin
There are around 1.5 lakhs entry in User model. So when i am using in in admin without the raw_id_fields it is causing problem while loading all the entry as a select menu of foreign key. is there alternate way so that it could be loaded easily or could become searchable. admin.py class ProfileRecommendationAdmin(admin.ModelAdmin): list_display = ('user', 'recommended_by', 'recommended_text') raw_id_fields = ("user", 'recommended_by') search_fields = ['user__username', 'recommended_by__username', ] admin.site.register(ProfileRecommendation, ProfileRecommendationAdmin) models.py class ProfileRecommendation(models.Model): user = models.ForeignKey(User, related_name='recommendations') recommended_by = models.ForeignKey(User, related_name='recommended') recommended_on = models.DateTimeField(auto_now_add=True, null=True) recommended_text = models.TextField(default='') -
Setting 2 sites in a Nginx server with gunicorn + django using systemD service
I am following the tutorial: http://www.obeythetestinggoat.com/book/chapter_09.html So, i have two sites in DigitalOcean with nginx and gunicorn, one for stage and the normal one... stage.nossalista.tk and nossalista.tk, first i manage to successfully deploy and run the stage one, but after upload the normal and added another systemd service for my normal one, everything stops working.. i gonna put all my configs and hope you guys give me some hints were may be the problem.... im getting error 400 from the nossalista.tk and 502 for my stage.nossalista.tk [UPDATE]: I was able to access the site only in stage.nossalista.tk:9000 .... hope this helps who wants to help me First i did is configure the /etc/nginx/sites-available/stage.nossalista.tk: server { listen 80; server_name nossalista.tk; location /static { alias /home/tyago/sites/nossalista.tk/static; } location / { proxy_set_header Host $host; proxy_pass http://unix:/tmp/nossalista.tk.socket; } } Second i configure the service for this stage site in /etc/systemd/system/gunicorn.service: [Unit] Description=Gunicorn server for stage.nossalista.tk After=network.target [Service] User=tyago Group=www-data WorkingDirectory=/home/tyago/sites/stage.nossalista.tk/source ExecStart=/home/tyago/sites/stage.nossalista.tk/virtualenv/bin/gunicorn --workers 3 --bind unix:/tmp/stage.nossalista.tk.socket superlists.wsgi:application Restart=always [Install] WantedBy=multi-user.target and then configure my socket service in /etc/systemd/system/gunicorn.socket: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn/socket ListenStream=0.0.0.0:9000 ListenStream=[::]:8000 [Install] WantedBy=sockets.target and then the gunicorn.conf file in (tyago is my user) /usr/lib/tmpfiles.d/gunicorn.conf d /run/gunicorn 0755 tyago tyago - After … -
The best Python/Django architecture for image heavy web application
I am building a web application that allows users to upload images to their accounts - similar to flickr and 500px. I want to know the best setup for such an application. I'm using Python 3.4 and Django 1.9 I'm currently thinking about the following: Heroku AWS S3 Postgres I'm struggling to find a suitable image processing library. I've looked at ImageKit and Photologue. But I find Photologue to be a little bit heavy for what I want to do. I'm basically looking for a way to allow users to upload images of a certain size without locking up the Heroku dynos. Any suggestions? Thanks -
Django models: form with infinite group of fields repetition
I'm studying django these days and I need your help to find a solution to this problem about form construction. Let's say I have an entity called 'Activity' just made up by: - title: just a char field - ActivityYears: a couple of start-end years that can be repeated multiple times ActivityYears is made up by: - start year - end year That's how my database should look like: activity_table -ID -title activity_years_table -year start -year end -activity ID That's how it looks like front-end Activity title 1 2001 - 2003 2005 - 2006 2007 - 2010 Activity title 2 2011 - 2013 2015 - 2016 and so on I'd dare to say that Activity and ActivityYears are models but I cannot connect them in a proper way. When I add an Activity item I should be able to add as many start-end years as I need but how? Thanx in advance -
Django self referential m2m field causes causes missing attribtue error
I get an error if I try to make a self-referential m2m Field. Am I missing something here? class UserProfile(models.Model): following = models.ManyToManyField('self', related_name='followers') somewhere else in a serializer: def get_followers(user): return user.profile.followers AttributeError: 'UserProfile' object has no attribute 'followers' Is there another way I can implement followers? Maybe I should make another model to do this or use a library? -
Django - Type Error: expected string or bytes-like object
I've seen other questions about this error but none of them were able to help so I figured I make on myself. As per the title, I keep getting this type error and I have run out of ideas as to why it is occurring. I am making an app that involves a Gallery object that adds Photo objects. What I have been specifically working on recently was a zip_upload function in order to add photos from a .zip file. I have tried Photologue but I am deciding to handle everything myself for multiple reasons. Actually, I referred to Photologue a lot when writing it so there any many similarities. Here is my code(left out unimportant details) and traceback: Models: class ImageModel(models.Model): image = models.ImageField('image',max_length=100,upload_to='photos') class Meta: abstract = True class Photo(ImageModel): title = models.CharField('title',max_length=250,unique=True) objects = PhotoQuerySet.as_manager() class Gallery(models.Model): title = models.CharField('title',max_length=250,unique=True) photos = models.ManyToManyField(Photo, related_name='gallery',verbose_name='photos', blank=True) objects = GalleryQuerySet.as_manager() Admin page: class GalleryAdmin(admin.ModelAdmin): def get_urls(self): urls = super(GalleryAdmin, self).get_urls() add_urls = [ url(r'^upload_zip/$', self.admin_site.admin_view(self.upload_zip), name='upload_zip') ] return add_urls + urls def upload_zip(self,request): context = { 'app_label': self.model._meta.app_label, 'opts': self.model._meta, } # Handle form request if request.method == 'POST': form = UploadZipForm(request.POST, request.FILES) if form.is_valid(): form.save(request=request) return HttpResponseRedirect('..') else: … -
Ordering a Many To Many Field based of its "through" model
So I know in a relational database with a many to many field it creates a relationship object that holds the keys for both things its tied to. I currently have models like this class ConfirmEmail(models.Model): owner = models.CharField(max_length = 100) emails = models.ManyToManyField(Sdm) report = models.ForeignKey(Report) def url(self): return "/admin/phone/confirmemail/" + str(self.id) + "/change/" def __str__(self): return str(self.owner) + ": " + str(self.report) class PhoneConfirmemailEmails(models.Model): confirmemail_id = models.IntegerField() sdm_id = models.IntegerField() distance = models.FloatField(blank = True, null = True) class Meta: managed = True db_table = 'phone_confirmemail_emails' unique_together = (('confirmemail_id', 'sdm_id'),) ordering = ('distance',) The PhoneConfirmemailEmails model is the relational object that ties the confirmation email models and its list of SDM objects. (Seen in its Many to Many relationship). (I know im now using the through keyword but trust me this was the model auto created by django so that works) You can see that I have added a distance variable. What I would like is on the admin page if the ManyToManyField was organized by that distance variable. From largest to smallest distance. Is there any way to do this? Thank you -
Django Form - Passing Values
I have the following form and can't seem to use the "self.currentSelectedTeam1" as the initial value for team1 as can be seen at the bottom. When I do try this I get the following error: team1 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,initial=self.curentSelectedTeam1) NameError: name 'self' is not defined Form: class SelectTwoTeams(BootstrapForm): def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) self.curentSelectedTeam1 = kwargs.pop('curentSelectedTeam1', None) self.curentSelectedTeam2 = kwargs.pop('curentSelectedTeam2', None) super(SelectTwoTeams, self).__init__(*args, **kwargs) queryset = StraightredTeam.objects.filter(currentteam = 1) self.fields['team1'].queryset = queryset self.fields['team2'].queryset = queryset team1 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,initial=self.curentSelectedTeam1) team2 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,initial=self.curentSelectedTeam2) Many thanks in advance for any help, Alan. -
Error while saving image using Django Rest Framework with angularjs
I have two models Blogs, Photo. In Photo model I have fields 'blogs' as foreign key to Blogs model. models.py: def content_file_name(instance, filename): custt=str(datetime.now()) return '/'.join(['content', instance.blogs.slug,custt, filename]) class Photo(models.Model): blogs = models.ForeignKey(Blogs) image = models.ImageField(upload_to=content_file_name) class Blogs(models.Model): author = models.ForeignKey(CustomUser) title=models.CharField(max_length=100) postedin=models.ForeignKey(Posted) tags= models.ManyToManyField(Tags) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) slug=models.SlugField(max_length=255,unique=True) def __unicode__(self): return '{0}'.format(self.title) views.py: class PhotoViewSet(viewsets.ModelViewSet): queryset=Photo.objects.all() serializer_class = PhotoSerializer def perform_create(self,serializer): serializer.save(blogs=Blogs.objects.latest('id')) return super(PhotoViewSet,self).perform_create(serializer) serializers.py: class PhotoSerializer(serializers.ModelSerializer): image = serializers.ImageField( max_length=None, use_url=True, ) class Meta: model = Photo read_only_fields = ("blogs",) js: function uploadpic(image) { return $http.post('/api/v1/uploadpic/', image:image, { headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} }); } result: {image: ["No file was submitted."]} Also I want to know, is there a better way to get blogs value (Foreign Key) for Photo Model. -
How can I have two models relate to one generic model?
Model "A" is a generic model, meaning any model can relate to it. Model "B" and "C" are models that want to establish a foreign key relation with Model "A". How can this be done? class A(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') list = # What goes here? class B(models.Model): parent = # What goes here to refer to model A? name = models.CharField(max_length=255) age = models.IntegerField() class C(models.Model): parent = # What goes here to refer to model A? title = models.CharField(max_length=255) body = models.TextField() An example lookup would be: A.list.all() Giving me a list of either B objects or C objects. -
AJAX post method failing in Django: 404
I'm using jQuery in my program to send POST requests to my database to log user actions in a client-side Javascript game, hosted on a Django framework. I had been getting 403 errors until I added csrfmiddlewaretoken: csrftoken with the appropriately-populated csrftoken value, but instead of happily magically working as promised, I'm now getting a 404 error when I try to $.post(). Preemptively: yes, the URL that the error message claims is a 404 does load if I copy and paste it into the address bar. urls.py (partial, omitted irrelevant pages): from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^init/$', views.init, name='init'), url(r'^log/$', views.log, name='log') ] views.py (partial, omitted irrelevant views): from django.shortcuts import get_object_or_404 from django.http import HttpResponse from .models import Partnership, RunLog def index(request): return render(request, 'mysite/index.html') def init(request): [...] return render(request, 'mysite/init.html', args) def log(request): """ This is for logging actions within the blockly-game interface. It is called by jQuery code in maze.js every time the user pushes the Run button, so we can see how they're doing. """ if request.method == 'POST': code = request.POST['usercode'] status = request.POST['status'] ps = get_object_or_404(Partnership, name=request.POST['ps']) runlog = RunLog.objects.create_runlog(ps.name, status, code) runlog.save() return HttpResponse('x') … -
Return html file without rendering in django
I want to use Django with single-page js framework and Django variable braces {{ clashes with framework delimiters. So I need to return some html file like response in my view without rendering file with any context. I've seen that many developers make reconfiguration of delimiters in JS but may be there are more suitable approach to save Django routing? -
Filter nested resource in Django REST framework with write support
I have the following model structure: class CourseSubscription(models.Model): course = models.ForeignKey(Course) student = models.ForeignKey(Student) class AttendanceRecord(models.Model): coursesubscription = models.ForeignKey(CourseSubscription) day = models.DateField() sign_in_time = models.TimeField() sign_out_time = models.TimeField() And I want to have a view which allows for reading/writing attendance record for a given (Course, day) pair which covers a range of CourseSubscription objects. That means, ideally, I'd have a serializer which for given course and day handles the filtered set of AttendanceRecord objects. So far I've came down to this: class AttendanceRecordSerializer(serializer.ModelsSerializer): class Meta: model = AttendanceRecord fields = ('id', 'sign_in_time', 'sign_out_time') class AttendanceSerializer(serializers.ModelSerializer): student = StudentSerializer(read_only=True) attendance = serializer.SerializerMethodField('get_attendance') class Meta: model = CourseSubscription fields = ('id', 'student', 'attendance') def __init__(self, *args, **kwargs): self.day = kwargs.pop('day') super(AttendanceSerializer, self).__init__(*args, **kwargs) def get_attendance(self, obj): try: record = obj.attendancerecord_set.get(day=self.day) return AttendanceRecordSerializer(record).data except AttendanceRecord.DoesNotExist: # this will save effort in js by placing empty mappings instead of nulls return {} This works perfectly for reading but doesn't support writing. SerializerMethodField is ignored by AttendanceSerializer.save(). Any ideas how I could do it using tools already present in REST framework? -
I keep getting a syntax invalid error on my forms.py file
When I run server I get syntaxerror message (invalid syntax) that indicates that the line if commit: is erroneous. Here's my forms.py file: from urllib import request from django.core.files.base import ContentFile from django.utils.text import slugify from django import forms from .models import Photo from PIL import Image from django.utils.translation import ugettext as _ class PhotoCreateForm(forms.ModelForm): class Meta: model = Photo # fields = '__all__' fields = ('title', 'description', 'photo', 'license', 'location', 'url', 'slug') #hide url input from users with the HiddenInput widget widgets = { 'url': forms.HiddenInput, } def clean_title(self): title = self.cleaned_data.get("title") if len(title) > 3: return title else: raise forms.ValidationError("Title must be greater than 3 characters long.") def clean_photo(self): photo = self.cleaned_data.get('photo', False) if photo: pho = Photo.open(photo) w, h = pho.size #validate dimensions max_width = max_height = 500 if w > max_width or h > max_height: raise forms.ValidationError( _('Please use an image that is smaller or equal to ' '%s x %s pixels.' % (max_width, max_height))) #validate content type main, sub = photo.content_type.split('/') if not (main == 'photo' and sub.lower() in ['jpeg', 'pjpeg', 'png', 'jpg']): raise forms.ValidationError(_('Please upload a JPEG or PNG image.')) #validate file size if len(photo) > (1 * 1024 * 1024): raise forms.ValidationError(_('Image file … -
Django Celery Webshop: order confirmation email not sent
I'm doing the webshop tutorial of the book "Django By Example". I'm using Windows. I created the order form page. Looking nice. After sending the order, the website says: "Thank you. Your order has been successfully completed. Your order number is 7". But the "customer" does not receive the order confirmation email. The other command prompt, that is running the celery, gives this kind of an error: "ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it." What you should have in the command prompt according to the book: [2015-09-14 19:43:47,526: INFO/MainProcess] Received task: orders. tasks.order_created[933e383c-095e-4cbd-b909-70c07e6a2ddf] [2015-09-14 19:43:50,851: INFO/MainProcess] Task orders.tasks. order_created[933e383c-095e-4cbd-b909-70c07e6a2ddf] succeeded in 3.318835098994896s: 1 If I add the code below to the settings.py then the order confirmation email is successfully sent to the command prompt. EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' I don't know if this problem is connected to RabbitMQ. I don't know if it's working or not in my system now. Earlier I did do the Erlang and RabbitMQ installations as best as I could. cmatskas.com: "RabbitMQ runs, by default, as a Windows Service and technically you shouldn’t need to do anything else to start interacting with it." -
NoReverseMatch at /accounts/login/ form action query?
Im trying to learn django, but i cant find the answer to this anywhere, or at-least not in simple terms! im trying to implement the included login view in my project and ive tried using the example html that the documentation uses and i get this error. Template error: In template C:\Users\Owner\Documents\django\mysite\templates\registration\login.html, error at line 14 Reverse for 'login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] 4 : 5 : {% if next %} 6 : {% if user.is_authenticated %} 7 : <p>Your account doesn't have access to this page. To proceed, 8 : please login with an account that has access.</p> 9 : {% else %} 10 : <p>Please login to see this page.</p> 11 : {% endif %} 12 : {% endif %} 13 : 14 : <form method="post" action=" {% url 'login' %} "> 15 : {% csrf_token %} 16 : <table> 17 : <tr> 18 : <td>{{ form.username.label_tag }}</td> 19 : <td>{{ form.username }}</td> 20 : </tr> 21 : <tr> 22 : <td>{{ form.password.label_tag }}</td> 23 : <td>{{ form.password }}</td> 24 : </tr> what i dont understand is what does " Action="{% url 'login' %}" actually do? i cant find … -
Apache don't actualize new css
I have a django server which is run by mod_wsgi and apache. Today when I tried to update the css in one of my html pages, the css file was updated but apache was still showing the old css. I tried to rename the css file but it didn't work out. What can I do ? Thank you -
How to keep using 3rd app admin templates after customizations of admin.py?
I use django-photologue and extended it: # gallery.models.py from photologue.models import Photo from profiles.models import UserProfile class PhotoExtended(Photo): user = models.ForeignKey(UserProfile, verbose_name=_('user'), on_delete=models.CASCADE) # gallery.admin.py from photologue.admin import PhotoAdmin as PhotoAdminDefault from photologue.models import Photo from .models import PhotoExtended class PhotoAdmin(PhotoAdminDefault): save_on_top = True admin.site.unregister(Photo) admin.site.register(PhotoExtended, PhotoAdmin) Photologue has a feature to upload zip file with photos and it can be done using additional button in admin. After my changes this button disappeared. Is it possible to use native photologues admin templates in order to avoid copy-pasting them to my app's template folder? In INSTALLED_APPS photologue is higher than my gallery app Here there are the photologues admin templates. -
Django 1.10: Redirect to another view or url not working. django.urls.exceptions.NoReverseMatch
In Django 1.10, My redirect to other view via url or the viewname is not working. The main urls.py file is as below: urlpatterns = [ url(r'^', include('app1.urls')), ] The urls.py file inside app1 is: from django.conf.urls import url from . import views app_name = 'app1' urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^details/$', views.details, name='details'), ] The views.py for app1 is as below: from django.shortcuts import render, redirect from django.utils.timezone import now import datetime from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse def home(request): if request.method == 'POST': print("redirected from home..................") url = reverse('details') return HttpResponseRedirect(url) # return redirect('app1:details') # return redirect('/details/') # return redirect('details') print("Not redirected..................") return render(request, "app1/index.html", {}) def details(request): print("Redirect OK inside details") today = datetime.date.today() return render(request, "app1/details.html", { 'today': today, 'now': now(), 'email_text': request.POST.get('email_item', 'bla bla'), }) I tried all the options in the home view with the commented code like using both HttpResponseRedirect and redirect but not able to redirect to the details view. I get the error: django.urls.exceptions.NoReverseMatch: Reverse for 'details' with arguments '()' and keyword arguments '{'request': <HttpRequest>}' not found. 0 pattern(s) tried: [] Any suggestions would help: -
Django: def __init__ variable usage
I have a form below which works nicely. However, as you can see right at the top the variables team1 and team2 have their initial values set as 12 & 24. What I would like to do is have these two variables link to the two variables called curentSelectedTeam1 and curentSelectedTeam2 within the def __ init __ section further down. Any help with this would be greatly appreciated, many thanks, Alan. class SelectTwoTeams(BootstrapForm): team1 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,initial=12) team2 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,initial=24) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) curentSelectedTeam1 = kwargs.pop('curentSelectedTeam1', None) curentSelectedTeam2 = kwargs.pop('curentSelectedTeam2', None) super(SelectTwoTeams, self).__init__(*args, **kwargs) campaignnoquery = UserSelection.objects.filter(user=user).order_by('-campaignno')[:1] if not campaignnoquery: currentCampaignNo = 1 else: currentCampaignNo = campaignnoquery[0].campaignno cantSelectTeams = UserSelection.objects.filter(campaignno=currentCampaignNo) if not cantSelectTeams: queryset = StraightredTeam.objects.filter(currentteam = 1) else: queryset = StraightredTeam.objects.filter(currentteam = 1).exclude(teamid__in=cantSelectTeams.values_list('teamselectionid', flat=True)) self.fields['team1'].queryset = queryset self.fields['team2'].queryset = queryset