Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django & gunicorn on VPS gives error: ImportError No module named 'vp.wsgi'
When I try to check the status of gunicorn I get the following error: gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Sat 2017-04-22 19:23:39 UTC; 10min ago Main PID: 7295 (code=exited, status=3) Apr 22 19:23:39 vp-first gunicorn[7295]: return util.import_app(self.app_uri) Apr 22 19:23:39 vp-first gunicorn[7295]: File "/home/tony/vp/vpenv/lib/python3.5/site-packages/guni Apr 22 19:23:39 vp-first gunicorn[7295]: __import__(module) Apr 22 19:23:39 vp-first gunicorn[7295]: ImportError: No module named 'vp.wsgi' Apr 22 19:23:39 vp-first gunicorn[7295]: [2017-04-22 19:23:39 +0000] [7300] [INFO] Worker exiting (pi Apr 22 19:23:39 vp-first gunicorn[7295]: [2017-04-22 19:23:39 +0000] [7295] [INFO] Shutting down: Mas Apr 22 19:23:39 vp-first gunicorn[7295]: [2017-04-22 19:23:39 +0000] [7295] [INFO] Reason: Worker fai Apr 22 19:23:39 vp-first systemd[1]: gunicorn.service: Main process exited, code=exited, status=3/NOT Apr 22 19:23:39 vp-first systemd[1]: gunicorn.service: Unit entered failed state. Apr 22 19:23:39 vp-first systemd[1]: gunicorn.service: Failed with result 'exit-code'. It says ImportError: No module named 'vp.wsgi' When I edit my gunicorn configuration file the following is in there: [Unit] Description=gunicorn daemon After=network.target [Service] User=tony Group=www-data WorkingDirectory=/home/tony/vp/vp ExecStart=/home/tony/vp/vpenv/bin/gunicorn --workers 3 --bind unix:/home/tony/vp/vp/vp.sock vp.wsgi:$ [Install] WantedBy=multi-user.target I have to note that my wsgi.py file is located: ~/vp/vp/vp/vp/wsgi.py My virtualenv is located at: ~/vp/vpenv My settings are located at: ~/vp/vp/vp/config/settings/production.py I … -
How to identify id of object being accessed django
So what I am trying to do in Django is writing a delete function. Basically I have a manytomanyfield set for my Course model where I specify the relationship with the User model which i have called students. students = models.ManyToManyField('User', blank=True, related_name='studies') From looking through django documentation and some other stackoverflow questions, I found that I could use course.students.remove(user). to remove a user object from a specific course. However, what I am having trouble with is understanding how I can find the specific course id at the specific instance. So this is my url. url(r'^courses/(?P\d+)$', CourseDetail.as_view(), name='courses.detail'), I want to find out the current identifier for the course object being accessed so that I can eventually filter through my course objects looking for the specific course in order to remove the student. -
How to preserve position after page reload using infinite scroll in Django
I have implemented infinite scroll for my data objects using jQuery and Waypoints. Works fine but I want to make it more convenient. First of all I`m looking for a way to preserve position after page reload. Also would be nice to add fixed pagination bar with a possibility to dislay your curent page dynamically while scrolling. I have add one, but how to dynamically display your position. Implies, I have 20 objects per page, when scrolling down for 20 next it should automatically switch current page for second one on pagination bar. And vice versa for scrolling up. Another question is when choosing exact page at my current pagination menu it opens separate page with link 'http://127.0.0.1:8000/?page=2' for example, and displays objects only from 41th to 60th. I need it to open exact page but with possibility to scroll up and down for previous and next pages. Which way it`s possible to do this? Here is my code below. models.py from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models class Bancnote(models.Model): type = models.CharField(max_length=11) par = models.PositiveIntegerField() year_from = models.PositiveIntegerField() year_to = models.PositiveIntegerField() size = models.CharField(max_length=7) sign = models.CharField(max_length=20) desc = models.TextField(max_length=200) image = models.ImageField(upload_to='bons_images') def __str__(self): return str(self.par) … -
How to show perisan (jalali) calendar in django?
i want to show times and dates in persian (jalali) calendar in django template but timezone.now() just show Gregorian calendar in template , how can i use jalali calendar in django template ? -
Django serializers, foreignkeys error
I have 2 tables, class Person(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) curp = models.CharField(max_length=50) rfc = models.CharField(max_length=12) gender = models.CharField(max_length=20) class Employee(models.Model): id = models.IntegerField(primary_key=True) joining_date = models.DateField() salary = models.DecimalField(18, decimal_places=2, max_digits=50) status = models.IntegerField() person = models.ForeignKey(Person, related_name='persons', on_delete=models.CASCADE) user = models.ForeignKey(User) branch = models.ForeignKey(Branch) On the serializer im trying to show the person data into Employee but im getting this error ot AttributeError when attempting to get a value for field persons on serializer EmployeeSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Employee instance. Original exception text was: 'Employee' object has no attribute 'persons'. Serializers class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ('name', 'curp', 'rfc', 'gender') class EmployeeSerializer(serializers.ModelSerializer): persons = PersonSerializer(many=True) class Meta: model = Employee fields = ('persons') It's my first time working on django so i dont get how to call the foreing keys. In my database i have the table Employee with 3 foreign keys (user, person and branch) Thanks! -
ImportError: cannot import name '__version__' error while trying to run Django project
I am not sure whether such format of question is valid. Simply I spent three hours trying to google the issue, but I the worst think is that I can't figure out where to look for the root cause of the problem. I am not experienced at analyzing traceback beyond elementary syntax error or missing module issues. I beg you guys, could you give a hint on what direction to dig ? Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import … -
Custom template tag don't work as expected (django)
My custom template tag is called change_page and should change page=x in the url without changing anything else in the url. (That means anything in the url, before and behind the ?. That's the template code part: (it works with the standard django paginator) {% if page_obj.has_previous %} <a href="{{ request.path }}?{% change_page current=request.GET.urlencode page=page_obj.previous_page_number %}" class="left_sharp">Zurück</a> {% else %} <a tabindex="2" href="" class="noteditable">Zurück</a> {% endif %} <div class="screen_only"> {% for i in paginator.page_range %} {% ifequal page_obj.number i %} <a href="" tabindex="2" class="noteditable">{{ i }}</a> {% else %} <a href="{{ request.path }}?{% change_page current=request.GET.urlencode page=i %}">{{ i }}</a> {% endifequal %} {% endfor %} </div> {% if page_obj.has_next %} <a href="{{ request.path }}?{% change_page current=request.GET.urlencode page=page_obj.next_page_number %}" class="right_sharp">Weiter</a> {% else %} <a href="" tabindex="2" class="noteditable">Weiter</a> {% endif %} </nav> {% endif %} The code of the template tag change_page: @register.simple_tag def change_page(current="", page=""): args = current.split('&') all='' for arg in args: all += re.sub(r'page=[0-9]+', 'page='+str(page), arg) + '&' all = all[:-1] return all It doesn't work. It allways returns an empty string. What did I wrong? -
Django model lookup on reverse ManyToMany Field
I am somewhat new to Django and I'm trying to solve what is probably a fairly simple task. I have two models (Destination and Tour). Tour has a ManyToManyField to destination in that a tour can be assigned to multiple destinations. class Destination(TimeStampedModel): title = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) site = models.ForeignKey(Site, db_index=True, related_name='guide_destination') sub_title = models.CharField(max_length=100, blank=True) active = models.BooleanField(default=False) description = models.TextField(blank=True) image = models.ImageField(null=True, blank=True, upload_to="guide/destination/") image_caption = models.TextField(null=True, blank=True) subject_location = models.CharField('subject location', max_length=64, null=True, blank=True, default=None) slideshow = FilerFolderField(null=True, blank=True) map_embed = models.TextField(null=True, blank=True) seo_title = models.CharField(blank=True, help_text=u'Max 255 characters', max_length=255) seo_keywords = models.CharField(blank=True, help_text=u'Comma separated list of keywords. Max 255 characters.', max_length=255) seo_description = models.CharField(blank=True, help_text=u'Max 255 characters', max_length=255) def __unicode__(self): return self.title def get_absolute_url(self): return reverse("guide-destination-detail", kwargs={"slug": self.slug}) and class Tour(TimeStampedModel): title = models.CharField(max_length=100) slug = models.SlugField(max_length=100) site = models.ForeignKey(Site, db_index=True, related_name='guide_tour') active = models.BooleanField(default=False) sub_title = models.CharField(max_length=100, blank=True) duration = models.CharField(max_length=100, blank=True) start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) description = models.TextField(null=True, blank=True) image = models.ImageField(null=True, blank=True, upload_to="guide/tour/") image_caption = models.TextField(null=True, blank=True) subject_location = models.CharField('subject location', max_length=64, null=True, blank=True, default=None) slideshow = FilerFolderField(null=True, blank=True, related_name='guide_tour') destinations = models.ManyToManyField(Destination, blank=True) experiences = models.ManyToManyField(Experience, blank=True) seo_title = models.CharField(blank=True, help_text=u'Max 255 characters', max_length=255) … -
Location of urls.py in Zinnia for Django
I'm trying to use the Zinnia app in Django. My question where is 'urls.py' in url(r'^weblog/', include('zinnia.urls')), I've search but can not find it. Or does it mean find all url files inside Zinnia app not just one named urls.py -
Getting No reverse Match at /techpedia/(name of my website)
While registering new users or logging in new users ,I am getting following error NoReverseMatch at /techpedia/ Reverse for 'profile' with arguments '(u'juit',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] This error is only showing up when I am trying to use bootstrap template.Without bootstrap,there is no error I went through these questions but they are of not much help.Django NoReverseMatch Django NoReverseMatch Please tell me what additional information I need to post as I don't have any idea what is causing this error. -
Django admin CSS randomly gone
I was working on the admin interface of my Django project, trying to get the right fields to show up in the right form, then on one of the reloads the CSS stopped loading, the Chrome inspector tells me the CSS files return a 404 error. I don't know what happened and can't figure it out. It's not a static files issue - the project doesn't use static files at all, and the staticfiles app has been commented out in settings.py (this is not recent, the CSS has been working for weeks without it). Debug is set to True (this also is not recent), however the project isn't served by runserver anyway. I've tried destroying and recreating the virtual machine the project is running on, which means literally everything except the project's own files is 100% fresh. Problem still persists. The question is, what can I do to get CSS working again? -
Django 1.9.13 complains SubfieldBase is deprecated, but I'm not using it. How to resolve?
I am upgrading an old Django project from Django 1.8.3 to the current Django 1.11, but to be cautious, I am upgrading to each major release of Django along the way, so I can find errors & deprecations and fix them before taking the next step. (I haven't touched this code in almost two years, so I'm a little rusty; forgive me if I'm making a simple mistake.) I first upgraded to Django 1.9.13 (the last before 1.10), and when I manage.py runserver, I get this error: /Users/mboszko/.virtualenvs/opticaldev/lib/python2.7/site-packages/django/utils/six.py:808: RemovedInDjango110Warning: SubfieldBase has been deprecated. Use Field.from_db_value instead. return meta(name, bases, d) If I'm reading this error right, the error stems from the custom version of six that Django embeds. I have searched my code, and I don't seem to be using SubfieldBase anywhere in my own code. (I have also googled, with not much success, for this particular error in six.) Is this just a situation where I should upgrade to Django 1.10, and the new version of six in that package will be compatible, or is there something that I need to resolve myself before I upgrade? -
Trigger to send new rows added to database to another database in postgres?
I have 2 databases on 2 different servers (say A & B). I have some crawlers that use API functions to write data to database (A). Some of this data are new and others are just updates to previous rows. If some new rows are added to (A) I want to add id of these new rows to (B). I want this to happen in real time without full scan of (A) iteratively. I want something like a trigger in (A) to send new ids to (B). How should I do write this trigger?(If you think there is a better solution, please help me) -
Django, how to display reply form for comment and what should the views.py look like
this is my first question here. I have a post_detail function in views.py to show the comment form def post_detail(request, id=None): instance = get_object_or_404(Post,id=id) form = CommentForm(request.POST or None) if form.is_valid(): c = form.save(commit=False) c.posts_id = instance.id c.save() return HttpResponseRedirect('/hello/get/%s' % id) else: form = CommentForm() context = { 'title': instance.title, "instance" : instance, "form": form, } return render(request,'post_detail.html',context) my models look like this class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) title = models.CharField(max_length=140) .... class Comment(models.Model): posts = models.ForeignKey(Post, related_name='comments') body = models.TextField() created = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) def approved(self): self.approved = True self.save() def __str__(self): return self.body class Meta: ordering = ['-created'] #negative class Reply(models.Model): comment = models.ForeignKey(Comment, related_name='reply') body = models.TextField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body class Meta: ordering = ['-created'] and the html <h2>Comments</h2> <form method='POST'>{% csrf_token %} {{form|crispy}} <input type='submit' value="Post Comment"> </form> <div> <h3><p>Total comments:{{instance.comments.count}}</p></h3> {% for comment in instance.comments.all %} {{comment.body}} <p>by:{{instance.user}}-Commented on:{{comment.created}}</p> {% for reply in comment.reply.all %} <p>{{reply.body}}</p> <p>by:{{instance.user}}-Replied on:{{reply.created}}</p> {% endfor %} <br/> {% empty %} <p> There are no comments</p> {%endfor%} </div> User is able to post comment and it is working fine. Also reply is getting displayed if done through django-admin. I want the user to … -
using querydict item for if-statement
The url: myurl/?page=1&reverse Now I want to check in the template whether reverse is in there: {% if request.GET.reverse %} do somthing {% endif %} But what's in between of if and endif never happens! What should I use instead of request.GET.reverse? -
Django - working with queryset
My models currently look like this: class Dealer(models.Model): name = models.CharField(unique=True, max_length=255, default='') url = models.URLField() def __str__(self): return self.name class Category(models.Model): name = models.CharField(unique=True, max_length=255, default='') def __str__(self): return self.name class Car(models.Model): name = models.CharField(unique=False, max_length=255,default='') category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name class Price(models.Model): car = models.ForeignKey(Car, default='') dealer = models.ForeignKey(Dealer, default='') price = models.DecimalField(max_digits=9, decimal_places=2) url = models.URLField(max_length=255) def __str__(self): return str(self.price) What I want to be able to do is answer the following question (something that will ultimately become the context of my view): Show me a list of cars in a particular category that are available at different dealerships, with their prices. The query that I'm using for testing is this: carprice = Price.objects.filter(car__category='1').values('car__name','price','dealer__name').order_by('car__name') The resulting QuerySet looks something like this: <QuerySet [{'car__name': 'Audi Model A', 'price': Decimal('32000.00'), 'dealer__name': 'Dealer A'}, {'car__name': 'Audi Model A', 'price': Decimal('35000.00'), 'dealer__name': 'Dealer B'}, {'car__name': 'Audi Model A', 'price': Decimal('35000.00'), 'dealer__name': 'Dealer C'}, '...(remaining elements truncated)...']> Question 1: Can the query be modified so that the QuerySet does not repeat the car__name every time but instead groups prices and dealers by car__name? If someone could point me to a good tutorial/documentation on QuerySets, I would be really grateful. … -
Django app on Heroku, deployed successfully but could not be served
I have built a simple blog app with Django by following a video and deployed it to Heroku by following another video. The app works fine locally, but it is not working online. Heroku gives me this error message: This app has no process types yet Add a Procfile to your app in order to define its process types. I had already added a Proclife created with Notepad with these contents: web: gunicorn mysite.wsgi But how can I add another Procfile to an app already deployed to Heroku? Where should I place it? -
Django rest framework - return objects ordered by callable method result
So basically the title says it all: how can I order the queryset that will be returned on the API by a callable method result that is not stored on the database? This field is dynamic and depends on each user's request, hence it can't be stored anywhere. I tried just using, which is what I want to achieve: queryset = Post.objects.filter('my_filters').order_by('my_method') but it doesn't work since it has to be a column on the database. I also tried: queryset = sorted(Post.objects.filter('my_filters'), key=lambda x: x.my_method()) But it throws the "AttributeError: 'list' object has no attribute 'model'" error. How can I sort the results of the queryset according to a method then? Any ideas? I will also need to limit the number of responses to the top results calculated this way. Thanks! -
Showing flash messages in DJango with close button
I want to display flash messages in Django with the close button. Existing message framework in Django allows to display messages and does not allow to close it. As an example, web2py provides such flash messages. I am looking for similar functionality in Django. If it can be done with few lines of code , it would be great. I do not want to add any other libraries or framework on top of Django. Thanks in advance. -
Django subdomain configuration for third party application integration
I am building a regular django project - the difference is this: I want the django website to only "work" on a specified subdomain - for example, http://www.foo.mydomain.com I want to use an entirely different application to run on another specified subdomain - e.g. http://www.foobar.mydomain.com How do I setup a django project, so that it only runs on a specific subdomain, and does not intercept requests to other subdomains - so other other applications can run on other subdomains on the same parent domain? -
Saving a Date in a Coisefield - Django?
so what I'm trying to build is basically a calendar. For this, a user has to choose a beginning date and time for an event as well as an end time. Everything then has to be stored - of course - in the database. I want to realize that by using a ChoiseField (unless there is a better solution). How would it be possible to generate all the dates of the month in a coisefield since some months are 30 days others have a different length etc.? Same with the hours of a day? I cant seem to come up with a working approach? How would one approach this problem? suggestions? -
Django ORM: building models of dialog where one member has to be emphasized
It's not so obvious to me how to organise a dialog with django ORM. Especially if I need to know who first started a dialog(because he is a buyer and person who answers is a sales, and we need to know exactly who sales a thing ). So, I see two solutions. First one looks like this: class Dialog(models.Model): buyer = models.ForeignKey(UserProfile, related_name='buyer_reverse') sales = models.ForeignKey(UserProfile, related_name='sales_reverse') But queryset could bring some trouble. As I suppose, query would look something like: dialogs = Dialog.objects.filter(Q(buyer=request.user.userprofile) | Q(sales=request.user.userprofile)) Another solution I guess is: class Dialog(models.Model): members = models.ManyToManyField(UserProfile) sales = models.ForeignKey(UserProfile, related_name='sales_reverse') What is the best solution except there are both wrong? -
ImageField instance doesn't have save method in Django shell. But it does when I'm running the actual server
I'm a Django novice studying with Django By Example by Antonio Mele. I stuck up at chapter 5 where I needed to resort to ImageField's save method. Here is a part of the code edited by me. from urllib import request from django import forms from django.core.files.base import ContentFile from images.forms import ImageCreateForm from images.models import Image class ImageCreateForm(forms.ModelForm): def save(self): img = super(ImageCreateForm, self).save(commit=False) # ... response = request.urlopen(image_url) img.image.save(image_name, ContentFile(response.read(), save=False) # ... class Meta: model = Image # ... And the Image model looks like this. from django.db import models class Image(models.Model): # .... image = models.ImageField(upload_to='images/%Y/%m/%d') # .... So img in save method of ImageCreateForm is an instance of Image and img.image is an instance of models.ImageField, right? I looked it up on the official django document and even inspected django sourcecode but I couldn't find save method. I tried this on django shell but it gave me only an error. It seems like models.ImageField type doesn't have save method. But, somehow when I actually run the server this raises no errors and gets to have save method. How can this be possible? You can find the whole source code here. https://github.com/guinslym/django-by-example-book/tree/master/Django_By_Example_Code/Chapter%205/bookmarks -
How to render a html string in javascript?
In my Django project, I use jQuery ajax to post some data, and then the view function return some other data. I conver the markdown text to html text and return a response to ajax, then I insert the html text to page, but the html text can't be rendered. For example, if the markdown text is:# This is a title, then it would be convered to <h1>This is a title</h1>, but if insert to page, it just the html text<h1>This is a title</h1>, it can't be rendered. Here is my code: javascript code function commentSubmit(username, articleid) { var text = $(".comment-editor-input textarea").val(); var post_data = { 'username': username, 'text': text, 'articleid': articleid, } $.ajax({ type: "POST", url: "commentsubmit/", data: post_data, dataType: 'json', success: function(result) { var html = '<div class="comment-item">' + '<img class="comment-avatar" ' + 'src="">' + '<span class="comment-username">' + result.username + '</span>' + '<div class="comment-item-content">' + result.content_html + '</div><div class="comment-item-foot">' + '<span class="comment-time">' + '2017' + '</span>' + '</div></div>'; $(".comment-list").append(html); $(".comment-editor-input textarea").val(''); } }); } Django view def comment_submit(request): if request.method == 'POST': # post_text is a markdown text post_text = request.POST.get('text') username = request.POST.get('username') article_id = request.POST.get('articleid') user = User.objects.filter(username=username).first() article = get_object_or_404(Article, pk=article_id) # in Comment … -
Django select2 dependent_fields
How can i filter results in ModelSelect2Widget by value from depended select? I have simple form for two select fields: Company and Object class CompanySelect2Widget(ModelSelect2Widget): model = Companies search_fields = ['name__icontains'] def label_from_instance(self, obj): return force_text(obj.name) class CompanySelect2Field(ModelChoiceField): widget = CompanySelect2Widget( max_results=10, attrs={ 'id': "select2_client", 'data-placeholder': "Select client", 'style': 'width: 200px;', } ) class ObjectSelect2Widget(ModelSelect2Widget): model = Objects search_fields = ['name__icontains'] def label_from_instance(self, obj): return force_text(obj.name) class PGSelect2Form(ModelForm): company = CompanySelect2Field(label=u'Client', queryset=Companies.objects.all()) object = ModelChoiceField( queryset=Objects.objects.all(), widget=ModelSelect2Widget( model=Objects, search_fields=['name__icontains', 'company'], label=u'Object', max_results=10, attrs={ 'id': "select2_object", 'data-placeholder': "Select place", 'style': 'width: 200px;', 'dependent_fields': {'company': 'company'} } ) ) class Meta: model = Objects fields = ('company', 'object') Object model has field company company = models.ForeignKey('company.Companies', null=True, blank=False, editable=True) Rendered widgets: But nothing filtered in Object select, if Company selected before or after Object :/