Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
difficulties with Django ''follow'' other user ( RedirectView )
I have a problem with a class in my Views.py class FollowToggle(RedirectView): def get_redirect_url(self,*args,**kwargs): username = self.kwargs.get("username") userprofile = self.kwargs.get("userprofile") user = self.request.user obj = get_object_or_404(UserProfile, user=user) if user.is_authenticated(): if user in obj.follow.all(): obj.follow.remove(user) else: obj.follow.add(user) url_ = obj.get_absolute_url() return url_ I want to give an User the option to follow each other. I have this call which I want to use later in an API. (everything is set up and running) but right now all It does is following itself. so if a user is doing http://127.0.0.1:8000/profiles/testuser/follow it redirects to the last page and updated the data in the model, but the followed user is the user himself. I figured that the Problem is obj.follow.remove(user) here should 'user' be 'username' but this throws me an error (invalid literal for int() with base 10: 'testuser'). If anybody knows how to solve this please let me know. Models.py: class UserProfile(models.Model): follow = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True,default=1, related_name='follow') def get_follow_url(self): return reverse("profiles:follow-toggle", kwargs={"user": self.user}) def get_api_follow_url(self): return reverse ("profiles:follow-api-toggle", kwargs={"user": self.user}) def get_absolute_url(self): return reverse("profiles", kwargs={"username": self.user}) -
how to send more than one instances in one form django
I have a post that have more that one file attached to it. Now when i edit the post i initialize post form with post instance but i have more than one file so how can i pre-initialize file form so that i can change/delete the files. views.py instance = get_object_or_404(Post, user = request.user, slug = slug ) form = PostForm(request.POST or None, instance = instance) fileForm = FileForm(request.POST or None, request.FILES or None) context.update({'form':form, 'fileform':fileForm}) print(fileForm.is_valid()) if form.is_valid() and fileForm.is_valid(): instance = form.save(commit=False) instance.user = request.user slug = create_slug(instance) instance.slug = slug instance.save() print(request.FILES) if request.FILES : for f in request.FILES.getlist('file'): file.objects.create(Post = instance, file=f) return HttpResponseRedirect('/%s/post/%s/'(request.user.username,slug)) forms.py class FileForm(forms.ModelForm): file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True,'class':'none','id':'file_input_file','required':'False'}), required = False) class Meta: model = file fields = [ "file" ] models.py: import os from django.db import models from django.conf import settings from django.utils.text import slugify from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from classroom.models import Classroom from comments.models import Comment # Create your models here. def upload_location(instance, filename): return "Post/%s/%s" %(instance.Post, filename) class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) title = models.CharField(max_length=120) slug = models.SlugField(unique=True, blank = True) content = models.TextField() choice = ( ('post','post'), ('anouncement','anouncement'), ('question', 'question'), ('assignment', 'assignment') ) post_type … -
Django 1.10 - Create two formsets from single queryobject
I have Book model, which has title, and author string fields. title fields may be different, but author is always equal to joey or martin. On a single page, I want to display two formsets, BUT I don't want to create QuerySet and make DB query separately for each form. Is it possible to, get all the objects at once, and then split them into separate lists and pass them info formset? My view function: def index(request): books = Book.objects.all() # Here we will take all at once joey_books = [] martin_books = [] for book in books: # books here are evaluated - only once! if book.author == 'joey': joey_books.push(book) elif book.author == 'martin': martin_books.push(book) joey_book_formset = forms.modelformset_factory( Book, form=BookForm, fields=['title', 'author'], can_delete=True, extra=1 ) joey_book_formset = joey_book_formset(queryset=joey_books) # Exception raised martin_book_formset = forms.modelformset_factory( Book, form=BookForm, fields=['title', 'author'], can_delete=True, extra=1 ) martin_book_formset = martin_book_formset(queryset=martin_books) # Exception raised context = { 'joey_forms': joey_book_formset, 'martin_forms': martin_book_formset, } return render(request, 'myapp/index.html', context) My expectation: Two formsets would be created and there would be running just one query. Problem: Following exception is raised: AttributeError: 'list' object has no attribute 'ordered' It is probably because formsets accept only QuerySet objects. Is there any workaround … -
Django/reportlab: Save generated pdf directly to FileField in AWS s3
I am writing a Django app, for which I need to generate a PDF, using reportlab, and save it to a FileField. My problem is that my media is stored in S3, and I don't know how to save this pdf directly to S3. I am creating the pdf locally then reading it and saving to the FileField in s3, then deleting the local version, but I'm wondering if there's a better solution, where I can save the file directly to S3. here's how I generate the contract now: #temporary folder name to generate contract locally folder_name = ( '/tmp/' + '/contracts/' + gig.identifier ) mkdir_p(folder_name) address = ( folder_name + '/contract_' + lang + '.pdf' ) doc = SimpleDocTemplate( address, pagesize=A4, rightMargin=72, leftMargin=72, topMargin=120, bottomMargin=18 ) doc.build(Story, canvasmaker=LogoCanvas) local_file = open(address) pdf_file = File(local_file) contract = Contract.objects.create(lang=lang, gig=gig) contract.contract_file.save('contract_'+lang+'.pdf', pdf_file) contract.save() #remove temporary folder shutil.rmtree(folder_name) return True and the Contract model is defined like this: class Contract(models.Model): gig = models.ForeignKey(Gig, related_name='contracts') lang = models.CharField(max_length=10, default='') contract_file = models.FileField( upload_to=get_contract_path, blank=True, null=True, default=None ) -
Djnago: how to make a link on main page to sub-pages
This is my first Django proj. I have had successfully deployed some pages which are in urls.py and could be reached with no problems. There is also default page should have links to 127.0.0.1/page1 and 127.0.0.1/page2. How could that be achieved? sitename is in settings.py I have tried the following in index.html: <h3>This is the URL for "page1": <a href="{% url 'sitename:page1.html' %}"> Click here</a></h3> > django.urls.exceptions.NoReverseMatch: 'sitename' is not a registered namespace <h3>This is the URL for "page1": <a href="{% url 'page1.html' %}"> Click here</a></h3> > Reverse for 'exp.html' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] -
how to manage Django urls alias redirections?
I'd like set up my urls correctly avoiding doing it like the example below since it afects my Google indexation : urls.py (wrong way) : url(r'^virtual-reality/$', views.virtualreality, name="virtual-reality"), url(r'^virtual-reality$', views.virtualreality, name="virtual-reality"), url(r'^vr/$', views.virtualreality, name="virtual-reality"), url(r'^vr$', views.virtualreality, name="virtual-reality"), As you can see I'd like vr/, vr, virtual-reality/, virtual-reality to redirect to the same page. I have more than 30 urls on my site and doing each url redirection like this is problematic since the structure grows. I do not use Apache on my Django site, so Rewriting Rules can not be made. (I'm on pythonanywhere (webserver : Gunicorn)) What's the best way to redirect all types of aliases in the same view without affecting my google search indexation and avoid to enter each url with the same view to urls.py ? -
Django, Run fucntion after the user login / Register
Once a user registers on my site, I want run a function and after a user login I want to be able to run another function. I want to know is anyway to do this apart from after the user logins redirects them to a view and once ive done what ive wanted redirect them again Or is their a way i can overwrite the django register and login classes. -
Using Django cycle template tag to number rows
I am trying to use Django cycle to make my css class have the current table row number in it. I'm trying the following: {{ formset.management_form }} {% for form in formset %} <tr class="{% cycle 'row1' 'row2' 'row3' %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} Where my rows are added dynamically using jquery.formset.js https://gist.github.com/vandorjw/f884f0d51db3e7caaecd For some reason this just gives me <tr class="row1 formset_row">...</tr> <tr class="row1 formset_row">...</tr> <tr class="row1 formset_row">...</tr> <tr class="row1 formset_row">...</tr> ... Why isn't this working? From what I understand this will give me row1 row2 row3 row1 row2 row3 row1... How can I make this continue counting... row1 row2 row3 row4 row5 row6 row7... -
Django multiple SQL join when no backwards relation are created (related_name='+')?
I need to execute this SQL statement (see below) using Django's ORM. I've to join 3 Django models. This is my SQL requirement: select a.attr_a, c.attr_c from table_a as a left join table_b as b on a.a_id = b.a_id and b.d_id = 1 left join table_c as c on a.a_id = c.a_id and c.d_id = 2 where b.attr_b = 'foo' and c.attr_c = 'bar' Then here are my Django models: class A(models.Model): a_id = models.AutoField(primary_key=True) attr_a = models.CharField(max_length=250) class Meta: db_table = 'table_a' class B(models.Model): b_id = models.AutoField(primary_key=True) attr_b = models.CharField(max_length=250) fk_to_a = models.ForeignKey(A, related_name='+') fk_to_d = models.ForeignKey(D, related_name='+') class Meta: db_table = 'table_b' class C(models.Model): c_id = models.AutoField(primary_key=True) attr_c = models.CharField(max_length=250) fk_to_a = models.ForeignKey(A, related_name='+') fk_to_d = models.ForeignKey(D, related_name='+') class Meta: db_table = 'table_c' class D(models.Model): d_id = models.AutoField(primary_key=True) attr_d = models.CharField(max_length=250) class Meta: db_table = 'table_d' Is there a way to resolve this with a single Django ORM query? Otherwise, could you show me how? -
Django - credentials not working for CustomUser
I'm trying to make a custom user, but there's one problem, when i get request.user, it’s an instance of User, not an instance of CustomUser, so i don’t get the extra fields and methods. I've found this, but when i'm trying to login in the django admin it won't work anymore. Here is my code: models.py class CustomUser(User): timezone = models.CharField(max_length=50, default='Europe/Bucharest') porecla = models.CharField(max_length=50, null=True) selectat = models.BooleanField(default=False) objects = UserManager() auth_backends.py - so i can use the methods of the custom user when using request.user from django.conf import settings from django.contrib.auth.backends import ModelBackend from django.core.exceptions import ImproperlyConfigured from django.apps import apps class CustomUserModelBackend(ModelBackend): def authenticate(self, username=None, password=None): try: user = self.user_class.objects.get(username=username) if user.check_password(password): return user except self.user_class.DoesNotExist: return None def get_user(self, user_id): try: return self.user_class.objects.get(pk=user_id) except self.user_class.DoesNotExist: return None @property def user_class(self): if not hasattr(self, '_user_class'): self._user_class = apps.get_model(*settings.CUSTOM_USER_MODEL.split('.', 2)) if not self._user_class: raise ImproperlyConfigured('Could not get custom user model') return self._user_class settings.py AUTHENTICATION_BACKENDS = ('football_app.auth_backends.CustomUserModelBackend', ) CUSTOM_USER_MODEL = 'football_app.CustomUser' admin.py class CustomUserAdmin(admin.ModelAdmin): list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'is_active', 'selectat', ) admin.site.register(CustomUser, CustomUserAdmin) -
How to remove Django`s BinaryField from memory?
I have a Django model with BinaryField: class MyData(models.Model): someData = models.CharField() data = models.BinaryField() In my app I need to iterate over the big set of rows. Of course I mark binary field as deferred: myDataList = MyData.objects().filter(...).defer('data') for myData in myDataList: doSmthWithData(myData.data) ... The result of the initial request requires small amount of memory. But while I iterate over the query set I fetch binary data from the database. Because of the size of the binary fields, memory is quickly exhausted. We can do a trick to free the memory - at the end of loop set data to None: myData = None. But in this case to modify and save entity I need to query it again from the database, otherwise binary data will be lost. Do we have any other way to delete binary data from the memory? Something like: set_defer(myData.data) -
Django send_mass_email with html content
Im triying to send a mass email with django's "send_mass_email" method, i've read the documentation but the examples only show plain text messages. How can i be able to send HTML messages with the "send_mass_emal" method? i tried like a regular email but the recived only html code. Here is my code: for row_index in range(12, sheet.nrows): if sheet.cell(rowx=row_index, colx=0).value != "": template = get_template("MonthlyEmail.html") context = Context({ 'name': str(clean_string(sheet.cell(rowx=row_index, colx=2).value)), 'doc_type': str(sheet.cell(rowx=row_index, colx=4).value), 'document': str(sheet.cell(rowx=row_index, colx=3).value), 'email': str(sheet.cell(rowx=row_index, colx=5).value), 'acc_numb': str(sheet.cell(rowx=row_index, colx=6).value), 'brute_salary': str(sheet.cell(rowx=row_index, colx=8).value), 'vacation_commision': str(sheet.cell(rowx=row_index, colx=9).value), 'brute_total': str(sheet.cell(rowx=row_index, colx=10).value), 'social_sec': str(sheet.cell(rowx=row_index, colx=14).value), 'isr': str(sheet.cell(rowx=row_index, colx=27).value), 'other_retention': str(sheet.cell(rowx=row_index, colx=13).value), 'net_payment': str(sheet.cell(rowx=row_index, colx=29).value) }) content = template.render(context) messages.append(('Monthly Salary Report', content, 'intranet@intranet.com', [str(sheet.cell(rowx=row_index, colx=5).value)])) send_mass_mail_html(messages, fail_silently=False) -
Jquery form.validate on submit not working
I'm trying to validate the input form before submitting it into the view. When add student is clicked for the first time, it generates a input row and submit button via jQuery. When i tried to validate on add student click, it works fine but, on submit button which is dynamically generated, validation doesn't work and form.valid() returns true even though it's not valid. Please toss me some idea what's wrong in the JS part or html part. image description html <div class="container" style="min-height:80%;"> <div class="col-sm-12"> <form id="form" action="#" name="registration" method="post" class="signup-form"> {% csrf_token %} <h1>Student List</h1> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>first name</th> <th>last name</th> <th>birthday</th> <th>Parent's Email</th> <th>Parent's Number</th> <th>Student's Number</th> <th>Student ID</th> <th>Oid #</th> <th>delete</th> </tr> </thead> <tbody> {% for student in student_list %} <tr> <td>{{ student.first_name }}</td> <td>{{ student.last_name }}</td> <td>{{ student.birthday }}</td> <td>{{ student.parent_email }}</td> <td>{{ student.parent_number }}</td> <td>{{ student.student_number }}</td> <td>{{ student.member_account_id }}</td> <td>{{ student.oid_id }}</td> <td> <a href="#" class="icon"> <span class="glyphicon glyphicon-remove"></span> </a> </td> </tr> {% endfor %} </tbody> </table> </div> <div class="button"> <button type="button" class="btn" name="add">Add student</button> </div> </form> </div> </div> JS var is_first = true; jQuery('button.btn').click(function (event){ event.preventDefault(); var form = $('.signup-form'); if(form.valid()==false) { alert("check inputs before add new student"); … -
Cant seem to retrieve info on django many to many, 'object has no attribute'
In my app, I have a custom defined 'Group_Set' model, designed to group users together. I can't seem to retrieve the users in the groups though. from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True) display_name = models.CharField(max_length=30, blank=True) slug = models.CharField(max_length=30, blank=True) bio = models.TextField(max_length=500, blank=True) avatar = models.ImageField(upload_to = 'avatars/', default = 'avatars/default.jpg') location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) public = models.BooleanField(default = False) def __str__(self): return self.slug class Group_Sets(models.Model): name = models.CharField(max_length=30) slug = models.CharField(max_length=30, blank=True) bio = models.TextField(max_length=500, blank=True) users = models.ManyToManyField(User, related_name='users') public = models.BooleanField(default = False) def __str__(self): return self.slug Once we get a Group_Set object, group = get_object_or_404(), all the other attributes work. However, group.users returns 'auth.User.none' even though I can see the relationship function in the database, and in the admin. Can anyone see anything wrong with how I've set this up? -
window.print() after print, appear "()" in the python's templates in the end of field
There is part of html code that using for print and where will appear "()": <tr> <td>Номер карточки</td> <td> {% if patient.number_card == None or patient.number_card == 0 %} <a href="" id="number_card" data-url="{% url 'ajax_patient_edit' %}" data-pk="{{patient.id}}">Дані відсутні</a> {% else %} <a href="" id="number_card" data-url="{% url 'ajax_patient_edit' %}" data-pk="{{patient.id}}">{{patient.number_card}}</a> {%endif%} </td> Screenshot what was printed: and want we had in the page: We also using X-editable library: $(document).ready(function() {$('#number_card').editable({ type: 'number', title: 'Введіть новий номер', params: function(params) { var objRequest = {number_card: params.value, pk:params.pk}; return objRequest; }, success: function(response, newValue) { // console.log(response); } }); Perhaps because of this problem? -
huge latency with python model
I've a classical model as: class Category(models.Model): code = models.IntegerField() name = models.CharField('name', max_length=200) parent = models.ForeignKey("self", null=True) def __str__(self): return self.name I've imported 5839 entries and now I cannot access or create a new Category entry, my browser keep in an infinite loop. Is there something wrong with my code or, is there best practices to referer self as parent ? -
How to use Django-haystack with Elasticsearch for filter form?
everyone. I have a Django Catalog app. He has Product with the brand, category, price. How can I build a filter with Django-haystack and use faceted for form filter? also, can I use with it Django-filter? -
My Python web crawler loop thru a list but writes over and over in the same field in my SQL Database
I working on web crawler, which gathers brand names for my an save the name in a SQL database. Since I'm programming with python I choose Django to build my GUI, so I also use Djangos ability to connect to SQL database. Somehow when I loop thru the list of brands, in the end it's aways the last brand name wich get stored in the database. My suspicion is that I didn't understand how the auto field of my brand class is working. So I will show you, how my brand class looks like, I will not post the whole web crawler, cause it's not important how I code that one, in the end the crawler return a list, and then I will sho you the function saveBrands(), which should store the brand names in my database. QUESTION: What do I need to do, that companyid = models.AutoField(db_column='CompanyID', primary_key=True) increases automatically? Or isn't that the problem? Thanks in Advance! class Companies(models.Model): companyid = models.AutoField(db_column='CompanyID', primary_key=True) # Field name made lowercase. companyname = models.CharField(db_column='CompanyName', max_length=45, blank=True, null=True) # Field name made lowercase. comfair = models.TextField(db_column='ComFair', blank=True, null=True) # Field name made lowercase. This field type is a guess. comecological = models.TextField(db_column='ComEcological', … -
Django doesnt display images from image field
I have got a bit of problem, and I have been searching for solution for a few hours and nothing works. The problem is when i visit django admin page I cant display image I uploaded through admin and get this error: Page not found (404) Request Method: GET Request URL: http://localhost:8000/inventory/shoe_4.jpg Using the URLconf defined in shoe_store.urls, Django tried these URL patterns, in this order: ^inventory/ ^$ [name='index'] ^inventory/ ^(?P<pk>[0-9]+)/$ [name='detail'] ^inventory/ ^inventory\/(?P<path>.*)$ ^admin/ The current path, inventory/shoe_4.jpg, didn't match any of these. This is my settings.py: MEDIA_URL = '/inventory/' MEDIA_ROOT = 'inventory/media/inventory' My admin.py: class ShoeAdmin(admin.ModelAdmin): list_display = ('title', 'price') fields = ( 'image_tag', ) readonly_fields = ('image_tag',) admin.site.register(Shoe) My models.py: from django.db import models class Shoe(models.Model): title = models.CharField(max_length = 200) description = models.TextField() price = models.DecimalField(max_digits=5, decimal_places=2) shoe_picture = models.ImageField() def __str__(self): return self.title def url(self): # returns a URL for either internal stored or external image url if self.externalURL: return self.externalURL else: # is this the best way to do this?? return os.path.join('/',settings.MEDIA_URL, os.path.basename(str(self.shoe_picture))) def image_tag(self): return '<img src="/inventory/media/inventory/%s" width="150" height="150" />' % (self.shoe_picture) image_tag.short_description = 'Image' image_tag.allow_tags = True My urls.py: from django.conf.urls import url from django.contrib.staticfiles.urls import static from django.conf import settings from … -
How do I upload images to a separate imageFields in Django model using Django form inside a Bootstrap modal?
I am currently creating a website using Django. I am creating a gallery page where the user can upload and display images inside 8 different squares. Each square is a different ImageField in the model. When the user clicks a square on the page a Bootstrap modal appears, containing a form that the user can use to upload an image. This works and at the moment I can upload an image to one of the squares, however, I would like to: 1) Check which image square has been clicked on the page allowing me to update the corresponding image in the database. 2) load this image into the correct image square. Code for the modal that appears when the user clicks the square, and then saves the image: <div class="modal fade" id="image-upload"> <div class="modal-dialog"> <form class="modal-content" action="#" method="POST" id="imageform" enctype='multipart/form-data'> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p>Upload a item..</p> <div class="form-group filepicker"> <label for="{{form.image.imageid }}">Image:</label> {{ form.image }} </div> </div> <div class="modal-footer"> <button type="submit" class="save btn btn-default">Upload</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </form> </div> </div> JQuery to load the modal: <script> $(function(){ $(".img-thumbnail").click(function(eventObject){ $('#image-upload').modal() alert(imagesquare) }) … -
How to open upload pdf django?
How to open upload pdf in new tab? models.py class PostLecture(models.Model): """comment""" title = models.CharField(max_length = 200) pdf = models.FileField(upload_to=('uploads/files')) time = models.DateTimeField(auto_now_add = True) def __unicode__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"id": self.id}) class Meta: ordering = ['-time'] I did upload in admin side. <div class="div_table"> <table> <tbody> <tr> <td>1</td> <td> <a href="">Понятие асимптотической сложности</a> </td> <td><a href="{% url 'main:problemlist' %}">Задачи по лекции</a></td> </tr> </tbody> </table> </div> How to open pdf (upload) after clicking first link? And how to do it in admin panel. I opened upload file but it was error 404 -
TestCase - Exception not raised in with statement when mocking __enter__
I'm trying to test a Python method containing a with statement. The code inside the with statement can raise an RuntimeError. The test I'm talking about tests if the RuntimeError is raised. The __enter__ and __exit__ methods are heavy (typically open and close SSH connections), and I mock them when testing. Here is a simplified definition of the method I want to test: # client.py class Client(): def method_to_test(): with self: raise RuntimeError() For clarification purpose, I omitted the definition of __enter__ and __exit__, and removed all the code in method_to_test which was not involved in the current issue. To test this method, I mock __enter__ and __exit__, and check if RuntimeError is raised: # tests.py from django.test import TestCase import mock from .client import Client class ClientTestCase(TestCase): @mock.patch('mymodule.client.Client.__enter__') @mock.patch('mymodule.client.Client.__exit__') def test_method_raises_Runtime(self, mock_exit, mock_enter): mock_enter.return_value = None client = Client() with self.assertRaises(RuntimeError): client.method_to_test() This test fails with: AssertionError: RuntimeError not raised If I do not mock __enter__, the RuntimeError is raised. Why does mocking __enter__ makes this test fail? -
How to redirect to particular URL after clicking on browser's back button?
I am using below code : <script> jQuery(document).ready(function($) { if (window.history && window.history.pushState) { $(window).on('popstate', function() { var hashLocation = location.hash; var hashSplit = hashLocation.split("#!/"); var hashName = hashSplit[1]; if (hashName !== '') { var hash = window.location.hash; if (hash === '') { alert('Back button was pressed.'); window.location='/User/makeTrans/'; return false; } } }); window.history.pushState('forward', null, './#forward'); } }); by using above code i can redirect to specific function or page after click on back button but when i refresh the page it redirects to previous page with #forward in url. But i dont want that #forward i want to stay on same page after refreshing it please can any one suggest solution.Thanks in advance. -
Range query in Elasticsearch_dsl by integer field
I used elasticsearch-dsl==5.2.0, elasticsearch==5.3.0 and Django==1.8.15. Django model: class Item(models.Model): price = models.DecimalField(default=0) def to_search(self): return DocItem( meta={'id': self.id}, price=self.price ) DocType class: class DocItem(DocType): price = Integer() FacetedSearch class: class ItemSearch(FacetedSearch): index = 'item' doc_types = [DocItem, ] fields = ['price'] When I need to search all items with price == 5.0, I do the next: search = ItemSearch().search() result = search.filter('match', price=5.0).execute() Question: How can I search all items with price in range: 1.0 < price <= 5.0 ? -
having two models on a ListView in django
I have set a ListView querry which works fine. I now want to add a star ratings to the thumbnail so that each car has its own customer star rating within the thumbnail. My present Listview is as such: class CarListView(FilterMixin, ListView): model = Car queryset = Car.objects.all() filter_class = CarFilter I am getting an error saying: 'str' object has no attribute '_meta' Now I think it is because I have not added the star ratings model which is an app on its own onto the ListView. Any idea how I can add the star ratings model here?