Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3 and jQuery - sort <li> items on all paginated pages
Currently I can sort li items on one page but not all paginated pages. I select an item from a dropdown list to sort by various attributes based on a model. Here is the jquery for one of the items. ''' var sortIconsetsTitle = function () { $("ul.iconsets-list li[data-sort-title]").detach().sort(function(a,b){ return String($(b).attr('data-sort-title')) < String($(a).attr('data-sort-title')) }).appendTo($("ul.iconsets-list")) $('div.iconsets-sort span').text("Title"); // show the order by name }; $('li a.sort-title').on('click', function () { sortIconsetsTitle(); }); //make it so ''' The code works beautifully - but only on one page. How can I use this code to return results from all the paginated pages? -
Foreign Key between Django application
In Django, I would like to link foreign key from another app. Bellow is the method for same application, but in my case, they are two different applications on same project. App Client Model : name = models.CharField(max_length=64) App Invoice Model : client = models.ForeignKey('Client', on_delete=models.CASCADE) thanks -
Count the number times a choice is selected by users, and plot a chart based on the data
I have a model models.py ILLNESS_CHOICES = ( (1, "Anxiety"), (2, "Arthritis "), (3, "Asthma"), (4, "Anemia"), (5, "Cancer"), (6, "Covid-19"), (7, "Diabetes"), (8, "Ebola"), (9, "HIV"), ) class MedicalHistory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) illness = MultiSelectField(choices=ILLNESS_CHOICES) symptoms = models.CharField(max_length=100) additional_info = models.CharField(max_length=100) disability = models.BooleanField(default=False) medications = models.BooleanField(default=False) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.username} Medical History' I am trying to plot a chart by counting the number of times an Illness is selected by users. I have seen similar questions from Count the number of occurrences of certain choices in models, Django Monthly/quartarly grouping of DateField() data and some other tutorials, but I am still not clear on how to approach. I am making use of Chart.js to display the data. views.py def pie_chart(request): labels = [] # illnesses as labels data = [] queryset = # get the count of each of the choices selected by users for entry in queryset: labels.append(#append the labels) data.append(#append the count of the choices) return JsonResponse(data={ 'labels': labels, 'data': data, }) Any help with this would be appreciated. -
Django how to annotate count nested forloop queryset dictionary
Good Day, My Problem is: my project depending on giving points to users who make any actions like (post, comment, favorite, likes ......). So, in users list page i want to list all users and other data for each user (name, points, badges, ....) to give the users points i have to count his posts, comments, likes, and so on..... i tried several methods and ways but all is failed to get annotate or prefetch_related or select_related Models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') Views.py def user_list(request): users = User.objects.all() template = 'user/users_list.html' nested_posts = {} for user in users: posts = user.posts.all() nested_posts[user, posts] = posts.count() print("nested : ", nested_posts) context = { 'users': users, 'user':user, 'posts': posts, 'nested_posts': nested_posts,} return render(request, template, context) when i print nested .. i found the count of every user' posts .. but how can i make it as variable to re-use in calculated field QuerySet nested : {(<User: Fareed>, <QuerySet [<Post: Senior Purchasing Specialist>]>): 1, (<User: Hussein>, <QuerySet [<Post: Senior Software Development Engineer in Test>]>): 1, (<User: Karima>, <QuerySet []>): 0, (<User: Yahia>, <QuerySet []>): 0} and i also tried : GetUserID = User.objects.get(id=2) var01 … -
Append information to queryset to sort
I have Book and and Reader models, and each of them have m2m relationship with Author and Genre. For any given book, I have a function that iterates over all readers and calculates a likely_to_read score (from 0 to 100, details of how it's calculated aren't particularly relevant). I'd like to now have this function return a list of readers sorted by likely_to_read from highest to lowest, that also includes the calculated score, but I'm not sure what the best way of achieving this is. I know I can create a local dictionary that stores just the reader_id and likely_to_read score, and then reverse it by score and have another queryset where id__in=<ids>, but I'm wondering if there's some way to 'extend' the queryset with this score? -
What's the purpose of setting "X-Forwarded-For" header in nginx
I have the following Nginx configuration for my Django application: upstream api { server localhost:8000; } server { listen 80; location / { proxy_pass http://api; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /staticfiles { alias /app/static/; } } I based this config on a tutorial here. After some research, looks like setting the Host header allows the Django API to determine original client's IP address (instead of the IP address of the proxy). What's the point of the X-Forwarded-For header? I see a field called $http_x_forwarded_for in the nginx logs but I'm not sure it's related. -
Django swagger ui not accessible on nginx
I have setup Django using nginx, gunicorn and postgres as per below url. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7 Now I am trying to access swagger ui. Nginx is up and running however showing default page. When I run the same project using, python manage.py runserver myip:8000 and then access the same url I can see actual swagger ui with rest end points. I am not sure what I am doing wrong here. Here is what I have added to nginx file. server { listen 80; server_name <myipaddress>; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/threat-dashboard/backend; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/tmp/backend.sock; } } -
Clear entire cart with one button click - Django/Python
So I have a working shopping cart. You can add and delete items, one at a time. However, once payment is submitted, I want to be able to just click a button and delete all of the items in the cart at once. Here is what I have: Cart Views.py: def remove_from_cart(request, id): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: return HttpResponseRedirect(reverse("cart")) cartitem = CartItem.objects.get(id=id) cartitem.delete() return HttpResponseRedirect(reverse("cart")) try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: return HttpResponseRedirect(reverse("cart")) cartitem = Cart.objects.all() cartitem.delete.all() return HttpResponseRedirect(reverse("cart")) The top section is what allows users to delete one item at a time. The second half is me attempting to use the same view on the same page to delete every cart item. Models.py: class CartItem(models.Model): cart = models.ForeignKey('Cart', null= True, blank = True, on_delete = models.CASCADE) product = models.ForeignKey(Product, on_delete = models.CASCADE) quantity = models.IntegerField(default=1) line_total = models.DecimalField(default = 10.99, max_digits = 1000, decimal_places=2) def __unicode__(self): try: return str(self.cart.id) except: return self.product.title class Cart(models.Model): total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) active = models.BooleanField(default=True) def __unicode__(self): return "Cart id: %s" %(self.id) Urls.py: url(r'^add-to-cart/(?P<item_id>[-\w]+)/$', add_to_cart, name="add_to_cart"), url(r'^cart/(?P<id>\d+)/$', carts_views.remove_from_cart, name='remove_from_cart'), url(r'^cart/(?P<slug>[\w-]+)/(?P<qty>\d+)/$', carts_views.update_cart, name='update_cart'), url(r'^cart/$', carts_views.view, name='cart'), url(r'^cart/(?P<id>\d+)/$', carts_views.remove_from_cart, name='clear_cart'), HTML: {% for item in cart.cartitem_set.all %} <a … -
e.preventDefault() not letting me submit my form
I wrote some javascript to validate a form. However, if the form fields pass all validations, the form never submits! Is my code somehow incorrectly preventing the form from being able to submit? If I delete all of the javascript and use browser's built-in validation then form executes fine and user is added to the database. const form = document.getElementById('form'); const first_name = document.getElementById('first_name'); const last_name = document.getElementById('last_name'); const username = document.getElementById('username'); const email = document.getElementById('email'); const password = document.getElementById('password'); const password2 = document.getElementById('password2'); // Show input error message function showError(input, message) { input.className = 'form-control is-invalid'; const small = input.parentElement.querySelector('small'); small.className = 'invalid-feedback'; small.innerText = message; } // Show success outline function showSuccess(input, message) { input.className = 'form-control is-valid'; const small = input.parentElement.querySelector('small'); small.className = 'valid-feedback'; small.innerText = message; } function checkRequired(inputArray) { inputArray.forEach(function(input) { if (input.value.trim() === '') { showError(input, `${getFieldName(input)} is required`); return false; } else { showSuccess(input, "Looks Good!"); return true; } }); } // Check email is valid function checkEmail(input) { const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if (re.test(input.value.trim())) { showSuccess(input, 'Looks Good!'); return true; } else { showError(input, 'Email is not valid'); return false; } } // Check input length function checkLength(input, min, max) { if … -
Book value calculation in Django
quick question. I have the following model: class Shares(models.Model): name = models.CharField(max_length=128) ticker = models.CharField(max_length=128) date = models.DateField() quantity = models.FloatField(default=0) price = models.FloatField(default=0) currency = models.CharField(max_length=128) and I'm trying to calculate the book value of each position with the following view: class SharesListView(ListView): model = Shares context_object_name = 'shares_details' def get_context_data(self, **kwargs): context = super(SharesListView, self).get_context_data(**kwargs) latest_fx = fx_table.objects.last() queryset = context['shares_details'].annotate(book_value=Case( When(quantity > 0, then=F('price')*('quantity')), default= Value (0), output_field=FloatField() ) ) context['shares_details'] = queryset context['total'] = queryset.aggregate(sum=Sum('book_value'))['sum'] return context However I can't make it work. Would you please be able to help? Thanks in advance -
In wagtail how do I setup the v2 api to attach the full base url ( e.g. http://localhost:8000" ) to steamfield images and richtext embeds?
I am currently using nuxt.js as a frontend for my wagtail headless cms. When I load a richtext field or an image block within a streamfield I am unable, or don't know how to, attach the full base url of the wagtail server so when it gets rendered on the nuxtjs site it resolves to src="/media/images/image.png which in the end tries to find the image on the nuxtjs site http://localhost:3000 and it needs to find it on the wagtail server side http://localhost:8000. For standard images I can intercept and prepend the server base url, but not when it comes to anything inside a streamfield. -
Postgresql trigger fire for arrayfield on tsvector
We have the following model which creates a Trigger event for simple TextField on INSERT or UPDATE. from django.db import models from django.contrib.postgres.search import SearchVectorField from django.contrib.postgres.indexes import GinIndex class Page(models.Model): title = models.CharField(max_length=100, unique=True) content = models.TextField() # New modifications. A field and an index content_search = SearchVectorField(null=True) class Meta: indexes = [GinIndex(fields=["content_search"])] Custom migration file to create trigger event for postgres database. from django.db import migrations class Migration(migrations.Migration): dependencies = [ # NOTE: The previous migration probably looks different for you, so # modify this. ('web', '0002_auto_20190524_0957'), ] migration = ''' CREATE TRIGGER content_search_update BEFORE INSERT OR UPDATE ON web_page FOR EACH ROW EXECUTE FUNCTION tsvector_update_trigger(content_search, 'pg_catalog.english', content); -- Force triggers to run and populate the text_search column. UPDATE web_page set ID = ID; ''' reverse_migration = ''' DROP TRIGGER content_search ON web_page; ''' operations = [ migrations.RunSQL(migration, reverse_migration) ] How to create a trigger event in the migration file for Arrayfield as tsvector_update_trigger expects text or varchar field.?? class Page(models.Model): title = models.CharField(max_length=100, unique=True) content = models.TextField() tags = ArrayField(models.TextField(blank=True),blank=True,null=True,default=list) ### ['wordpress','drupal'] content_search = SearchVectorField(null=True) tags_search = SearchVectorField(null=True) class Meta: indexes = [GinIndex(fields=["content_search","tags_search"]),] -
I would like to be able to redirect connected users to the main page and also use user_passes_test and login_required thank you
I created a user_passes_test (groups) to limit users according to user groups but when I redirect all the users already connected to the main page it creates a redirection loop and firefox displays 'The page is not redirected correctly' is the link to my home page is the link that is accessible to all connected users [is the page link which authorize when i want to leave d home page to this page with a user who is not authorized firefox referral The page is not redirected correctly Firefox has detected that the server is redirecting the request for this address in a way that will not be successful. {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="{% static 'accounts/img/favicon.ico' %}"> <title>Authentification</title> <link href="{% static 'accounts/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'accounts/css/loguer.css' %}" rel="stylesheet"> <script type="text/javascript" src="{% static 'accounts/js/jquery-3.3.1.min.js' %}"></script> <script type="text/javascript" src="{% static 'accounts/js/bootstrap.min.js' %}"></script> </head> <body> <div class="container-fluid"> <div class="row"> <main role="main" class="col-sm-6 ml-sm-auto col-md-12 pt-6"> <div class="container"> <div class="card card-container"> <!-- <img class="profile-img-card" src="//lh3.googleusercontent.com/-6V8xOA6M7BA/AAAAAAAAAAI/AAAAAAAAAAA/rzlHcD0KYwo/photo.jpg?sz=120" alt="" /> --> <img class="profile-img-card" src="{% static 'accounts/img/academy.png' %}" /> {% if form.errors or error %} <p … -
Django rest frame work nested serializer doesn't update object
I have a model with a Foreign Key field and upon serialization of the object, I'm performing a create method on it which updates the field if it None. In the second serializer, I overwrote the update method to make sure that the data was inserted. I don't get any errors when running the update, yet, the field is not updated. models: class Mission(models.Model): # Some other irrelevant fields. area = models.CharField( name='Area', max_length=8, choices=AREAS, ) date_added = models.DateTimeField(verbose_name="Date Added", default=now()) gdt = models.ForeignKey(KnownLocation, on_delete=models.PROTECT) class KnownLocation(models.Model): """ Add known location to map, But also use this as Base Object to describe locations as GDTs. :rtype Django base model for GeoLocation. """ name = models.CharField(name="Name", unique=False, primary_key=True, max_length=150, blank=False, help_text="Enter the location's name") area = models.CharField(name='Area', max_length=8, choices=AREAS, ) date_added = models.DateTimeField(default=timezone.now) latitude = models.FloatField(name="Latitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=DEFAULT_VALUE) longitude = models.FloatField(name="Longitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google Maps.", default=DEFAULT_VALUE) elevation = models.FloatField(name="elevation", help_text="Enter the location's ~Sea Level~ elevation, or Leave empty for auto-fill. ", blank=True, null=True, verbose_name="Elevation" ) serializers: class KnownLocationSerializer(HyperlinkedModelSerializer): def create(self, validated_data): """ Checks if user inputted the elevation or left … -
Postgresql fire TRIGGER on BEFORE INSERT OR UPDATE on multiple columns in single query
from django.db import models from django.contrib.postgres.search import SearchVectorField from django.contrib.postgres.indexes import GinIndex class Page(models.Model): title = models.CharField(max_length=100, unique=True) content = models.TextField() # New modifications. A field and an index content_search = SearchVectorField(null=True) class Meta: indexes = [GinIndex(fields=["content_search"])] Custom migration file to create trigger event for postgres database. from django.db import migrations class Migration(migrations.Migration): dependencies = [ # NOTE: The previous migration probably looks different for you, so # modify this. ('web', '0002_auto_20190524_0957'), ] migration = ''' CREATE TRIGGER content_search_update BEFORE INSERT OR UPDATE ON web_page FOR EACH ROW EXECUTE FUNCTION tsvector_update_trigger(content_search, 'pg_catalog.english', content); -- Force triggers to run and populate the text_search column. UPDATE web_page set ID = ID; ''' reverse_migration = ''' DROP TRIGGER content_search ON web_page; ''' operations = [ migrations.RunSQL(migration, reverse_migration) ] Trigger which works for only one column field content_search whenever Page table get's updated. How do I create a trigger event for both following multiple columns in single fire class Page(models.Model): title = models.CharField(max_length=100, unique=True) content = models.TextField() content_search = SearchVectorField(null=True) title_search = SearchVectorField(null=True) class Meta: indexes = [GinIndex(fields=["content_search","title_search"]),] -
Getting the correct data for the form in Django
Currently, I am getting the data from the whole database so I am attempting to filter it and then pass the filtered model to the form so only the data relevant to the user is shown. I did it according to what I found on google but I am getting this error: too many values to unpack (expected 2) It makes no sense to me as I am filtering the data as expected. Here is my code: models: from django.db import models from django.contrib.auth.models import User from posts.models import PDF from children.models import Children HEADER_CHOICES = [ ('Financial Support', 'Financial Support'), ('Educational Support', 'Educational Support'), ('Governmental Support', 'Governmental Support '), ('Charity Support Groups', 'Charity Support Groups'), ('Therapy Support', 'Therapy Support '), ('Transport Support', 'Transport Support ') ] AGE_CHOICES = [ ('0-4', '0-4'), ('4-11', '4-11'), ('11-18', '11-18'), ('18-25', '18-25') ] class Timeline(models.Model): header = models.CharField(max_length=30, choices=HEADER_CHOICES) age = models.CharField(max_length=6, choices=AGE_CHOICES) child = models.ForeignKey(Children, on_delete=models.CASCADE) class Pdf(models.Model): pdf = models.FileField(upload_to='timelinepdfs') timeline = models.ForeignKey(Timeline, on_delete=models.CASCADE) children model: from django.db import models from django.contrib.auth.models import User from PIL import Image from django.urls import reverse from django.dispatch import receiver from django.db.models import signals DIAGNOSIS_CHOICES = [ (1, ("Yes")), (2, ("No")) ] class Children(models.Model): first_name = … -
Server-side implementation of image downloading in Django web app (images served from a remote location)
I'm trying to do a server side implementation of a download button for static assets (served via AWS S3) in a Django web app. What I've tried: I first tried the download attribute with a tags. But it doesn't cover Firefox in my experience (i.e. instead of the asset being downloaded, a new browser tab opens and the asset renders in that window). I tried a server-side solution once the aforementioned failed. Specifically, in an html template, I've got: <form method="GET" action="{% url 'download_image' %}" target="_blank"> <input type="hidden" name="img_url" value="{{ img_url }}"> <button>Download</button> </form> And in a view, I'm trying: def download_image(request): """ Download the image """ image_url = request.GET.get("img_url",None) # image_url value is //s3.eu-central-1.amazonaws.com/my-app/ebc4596f-d7db-340f-b7d6-4952c949f011.jpg if image_url: with open('https:'+image_url, 'rb') as fh: response = HttpResponse(fh.read(), content_type="image/jpg") response["Content-Disposition"] = 'attachment; filename="content.jpg"' return response This results in an IOError: No such file or directory: u'https://s3.eu-central-1.amazonaws.com/my-app/ebc4596f-d7db-340f-b7d6-4952c949f011.jpg' I feel I'm doing something fundamentally wrong. Can an expert guide me via an illustrative example? Thanks in advance. -
Django file upload using Dropzone.js
I am trying to add images to a blog post using Dropzone and Ajax and I cannot manage to upload the files successfully and my post object gets created without the images. I am not seeing any errors in the console but by images are not being added. my image form: class ImageForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ImageForm, self).__init__(*args, **kwargs) self.fields['file'].required = False file = forms.FileField( widget=forms.ClearableFileInput( attrs={ 'multiple': True, 'class':'image_upload_form' })) class Meta: model = Images fields = ('file',) my post_create.html: {% load crispy_forms_tags %} {% load static %} <body> <form id="postCreate" method="POST" data-url="{% url 'home:post-create' %}" class="post-create-form dropzone" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" >Create a Post</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" style="overflow-y: auto; margin:0;"> <div id="loadingDiv"> <div class="d-flex justify-content-center mb-1"> <div class="spinner-border" role="status"> <span class="sr-only">Loading...</span> </div> </div> </div> {{ form|crispy }} <div class="d-flex justify-content-left"> <div> <button type="button" id="upload-image" class="btn btn-sm mr-auto btn-primary pb-1 fileinput-button"> <span><i class="fas fa-image"></i></span> </button> </div> <div> <p class="pt-1 mx-2 text-muted small">Add up to four images to your post</p> </div> </div> <div id="previews" class="dropzone-previews"></div> <div class="fallback"> {{ image_form }} </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" id="submit-all" class="btn btn-primary">Post</button> </div> </form> <script … -
Transfer data from node application to django application both using postgres
How to efficiently insert data from one postgres database to another? I have a legacy node app which I am converting to Django. Both projects are using Postgres. The data schema in node app is vastly different from the new Django app. Therefore, I have written a script that maps old data into new data schema. The problem is that the script is painfully slow. 5 records a second. I have over 1 million records. What is the most efficient way to achieve this? My current script looks like: @transaction.atomic def migrate_users(cursor): select_query = "select * from users order by id" # old database cursor.execute(select_query) records = cursor.fetchall() for row in records: record_dict = {} record_dict['id'] = row[0] record_dict['name'] = row[1] record_dict['email'] = row[2] defaults = { 'name' : record_dict['name'], 'extra' : { 'old_node_db_values' : { 'id': record_dict['id'] } } } u, created = User.objects.get_or_create( email=record_dict['email'], defaults = defaults ) if created: u.set_password(DEFAULT_USER_PASSWORD) u.save() This is a simplified script. Actual data requires a lot of massaging. -
Why is my pagination not working? (Django)
I've been working with Django-Listviews and I used paginate_py in a class to get some pagination going. But it'll just show all the items. This is the class: class PostListView(ListView): model = publicaciones template_name = 'store/search.html' context_object_name = 'queryset' ordering = ['Promocionado'] paginate_by = 2 def get_queryset(self): qs = self.model.objects.all().order_by('id') search = self.request.GET.get('q') if search: qs = qs.filter(Título__icontains=search) return qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) MyFilter = PubFilters(self.request.GET, queryset=self.get_queryset()) context['filter'] = MyFilter context['filtered_items'] = MyFilter.qs context['count'] = self.get_queryset().count() context['búsqueda'] = self.request.GET.get('q') return context Please tell me if I need to post anything else, like filters.py and so on. Thanks in advance! -
FILE PATH can't open with TOKEN in MOD HEADER - UNABLE TO OPEN S3 BUCKET FILE [DJANGO REST]
I've created a REST API app in Django REST. Through it you can upload files to a server, tag them etc. I have connected an S3 AWS bucket as the storage system. The problem is. The app has a token authentication set up. So you get to upload files only if authenticated. BUT when you want to open the file (click on the json link in the displayed data), you have to turn off your mod header with the authentication token, because otherwise it messes up with the opening and tries to input the token in constantly. And this is the better option, for it to at least open like that I had to make the bucket completely public. So the reality is, you post files, with the token authentication on. You can access the api only with the auth token on. But whenever you would want to open a file, you have to turn off the mod header which results in you checking and unchecking the mod header token constantly like an idiot if you want to browse api + open files. Plus because the bucket is public, anybody could see your files... not ideal REST API Serialized data … -
Django: How can I add an aggregated field to a queryset based on data from the row and data from another Model?
I have a Django App with the following models: CURRENCY_CHOICES = (('USD', 'US Dollars'), ('EUR', 'Euro')) class ExchangeRate(models.Model): currency = models.CharField(max_length=3, default='USD', choices=CURRENCY_CHOICES) rate = models.FloatField() date = models.DateField() class Donation(models.Model): date = models.DateField() donor = models.CharField(max_length=250) amount = models.FloatField() currency = models.CharField(max_length=3, default='USD', choices=CURRENCY_CHOICES) I also have a form I use to filter donations based on some criteria: class DonationFilterForm(forms.Form) min_amount = models.FloatField(required=False) max_amount = models.FloatField(required=False) The min_amount and max_amount fields will always represent values in US Dollars. I need to be able to filter a queryset based on min_amount and max_amount, but for that all the amounts must be in USD. To convert the donation amount to USD I need to multiply by the ExchangeRate of the donation currency and date. The only way I found of doing this so far is by iterating the dict(queryset) and adding a new value called usd_amount, but that may offer very poor performance in the future. Reading Django documentation, it seems the same thing can be done using aggregation, but so far I haven't been able to create the right logic that would give me same result. -
When running Django tests using Travis CI, my tests are running and completing locally, but are not running (or being found) remotely
As per the question, I have two tests which I am running successfully on my local machine. Running "python manage.py test" in the command line produces the following output: Creating test database for alias 'default'... System check identified no issues (0 silenced). .. ---------------------------------------------------------------------- Ran 2 tests in 0.495s OK Destroying test database for alias 'default'... These tests are part of a project which is currently residing in a GitHub repository. This repository is linked to Travis CI, and as such, a travis.yml file can be found in the repository's root directory. The contents of the file are as follows: language: python install: - python -m pip install -r requirements.txt before_script: - cd TNI_Project script: - python manage.py test For reference, the "TNI_Project" directory is the one which contains the "manage.py" file, and the "requirements.txt" file contains the output of pip freeze. However, once the build is launched on Travis CI, the build exits with 0, but none of the tests are run. The exact output can be found below: $ python -m pip install -r requirements.txt before_script 0.00s$ cd TNI_Project 0.41s$ python manage.py test System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK The … -
Django models many to many relation adds automatically
I have a model class like this. When I create a student, the django automatically adds all courses to student. class Course(models.Model): course_name = models.CharField(max_length=25) is_open = models.BooleanField(default=True) def __str__(self): return self.course_name class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) EXP = ( ('1', 'Unexperienced LA'), ('2', 'Experienced LA'), ('3', 'Unexperienced TA'), ('4', 'Experienced TA'), ('5', 'DEFAULT'), ) courses = models.ManyToManyField(Course,null=True) exp = models.CharField(max_length=1, choices=EXP) -
Elasticsearch_dsl in django - unable to use password
I want my Django application to use a password for connecting to the elasticsearch container. Therefor I set a connection string in my settings.py which was working fine until I setup password authentication for elasticsearch. Currently I get the following error from Django: elasticsearch.exceptions.AuthenticationException: AuthenticationException(401, '') Using curl like this is working fine inside the container: curl -u "${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD}" "${ELASTICSEARCH_HOST}:${ELASTICSEARCH_PORT" But if I set the same env. vars. for the ELASTICSEARCH_DSL config at my settings.py, I simply fail and cannot establish a connection to elasticsearch due to the auth. failure mentioned above: ELASTICSEARCH_DSL = { 'default': { 'hosts': env.str('ELASTICSEARCH_USERNAME') + str(':') + env.str('ELASTICSEARCH_PASSWORD') + str('@') + env.str('ELASTICSEARCH_HOST') + str(':') + env.str('ELASTICSEARCH_PORT') }, } Is the syntax here maybe wrong for : or @ at the connection string? I already searched the docs and web on this but was not able to find a solution till now.