Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Access custom login page along with AD authentication
I am writing a Django application for a company and they have requested me to integrate AD authentication as they already have groups in their Active Directory for all their tasks. I have found a potential solution here: Automatic Login in a Django Application Using External Authentication (It is not yet tested for production) Now, the problem that I am facing is that I can't access the custom/Django's default login system. I need the custom page in case someone outside the AD group wants to access the application (approved by the company). How can I access the login page, in case there is no AD group member logged in? -
django cache_page how to set version
I can set version by cache.set: cache.set(key, value, timeout=60, version=1) but how to set by cache_page decorator? like: @cache_page(60, version=1) def view(request): -
Update model that is connected via ForeignKey
Hi I have models that are contectet via foregin key. I can have multiple orders so let's say that i have 3 orders. 2xTshirt 1xPants and 4xHats. How can I acces each product and change the stock of them based on quantity of an order. views order = Order.objects.get_or_create(customer=customer, complete=False) order_items = OrderItem.objects.filter(order=order) for item in order_items: item.product.stock = int(item.product.stock) - int(item.quantity) item.transaction_id = transaction_id item.save() models class Product(models.Model): title = models.CharField(max_length=70, null=True, blank=True) producent = models.CharField(max_length=40, null=True, blank=True) stock = models.PositiveIntegerField(null=True, blank=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) -
How can i display a custom method to a model in a template using views(generic)?
#Hello people. I have ran into a problem and am kindly asking you to help me. So i have added a custom method to my fee profile model, and i wanted it to calculate for me the fee balance when a fee instance is created. First, before adding the custom method, everything was working out well. I could add a fee profile instance in the django admin without getting errors. Also, i have included a dictionary that stores the fee payment history and am unable to figure out a way to display the fee payment history on a template.I am running django 3.1.4, and using python 3.8.5. Here is my code: #This is the error i got."str returned non-string (type Child)". Remember all was working well till i introduced the fee_status() custom method. '''# Fee model #the admin.py code @admin.register(FeeProfile) class FeeProfile(admin.ModelAdmin): list_display = ( 'child', 'amount_paid', 'date', 'fee_status' ) list_filter = ['date'] search_fields = ['child'] class FeeProfile(models.Model): child = models.ForeignKey('bjs_main.Child', on_delete=models.CASCADE) parent = models.ForeignKey('bjs_main.Parent', on_delete=models.CASCADE) mpesa_code = models.CharField(max_length=10, primary_key=True) amount_paid = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.child def fee_status(self): global total_amount_paid total_amount_paid += self.amount_paid fee_balance = term_fee - total_amount_paid payment_history = { 'amount_paid': self.amount_paid, 'date_paid': self.date … -
Mock a formset save_formset method django forms?
I am new to writing tests and wanted to know the right approach on how I can mock a ModelAdmin save_formset functionality. Basically, I don't want to create a formset and want to mock the value of the formset.forms and pass it to the function so that it just tests the important part of the save_formset function. However, at the end of the function it still tries to call the ModelAdmin formset.save() method and that's where I get a NoneType attribute because in reality I am not passing an actual formset to the function. This is what I tried so far admin.py def save_formset(self, request, form, formset, change): forms = self.get_formset_forms(formset) for f in forms: obj = f.instance if not hasattr(obj, "creator"): obj.creator = request.user formset.save() def get_formset_forms(self,formset): return formset.forms tests.py @patch("core.apps.survey.admin.SurveyAdmin.get_formset_forms") def test_save_formset(self,mock_get_formset_forms,mock_formset_save): user = mixer.blend(User) mock_get_formset_forms.return_value = [{'instance':{'iss':user}}] mock_formset_save.return_value=1 site = AdminSite() survey_admin = admin.SurveyResponseAdmin(Survey, site) survey_admin.save_formset(request=None, form=None, formset=None, change=None) error log survey_admin.save_formset(request=None, form=None, formset=None, change=None) core/apps/survey/tests/test_admin.py:56: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
Django: Get objects of first model by comparing attribute of second OneToOne related model
I have two models, User and Card. One user has one card. I need to get objects of User if the 'card_written' of Card model is False in a view. class User(model.Model): phone = PhoneNumberField(null=False, blank=False, unique=True) email = models.EmailField(verbose_name="email", max_length=60, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class Card(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) card_number = models.CharField(max_length=200) card_written = models.BooleanField(default=False, null=False) card_write_date = models.DateTimeField(null=True, blank=True) card_delivered = models.BooleanField(default=False, null=False) -
Django superuser/admin doesn't login on deployed web app (Digital ocean)
I have developed and deployed a Django web-app on digitalocean following this article from digital ocean but i have an issue logging in after successfully adding a superuser. Locally (on the server i.e http://server_domain_or_IP:8000) i can log in and add data BUT when i add NGINX, i can not login. The rest of the web-app works fine i.e the staticfiles are fine. Here is my GUNICORN FILE [Unit] Description=gunicorn daemon After=network.target [Service] User=ronald Group=www-data WorkingDirectory=/home/user/projectfolder ExecStart=/home/user/projectfolder/virtualenv/bin/gunicorn --access-logfile - --workers 3 --bind 0.0.0.0:8000 projectname.wsgi [Install] WantedBy=multi-user.target And here is the NGINX FILE server { listen 80; server_name server_domain_or_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/projectfolder; } location /media/ { root /home/user/projectfolder; } location / { include proxy_params; proxy_pass http://0.0.0.0:8000; } } I have tried using the projectname.sock file as described in the article above but it's still the same error. -
Field 'id' expected a number but got <built-in function id> error
I want to add a favorites button in my template but seem to run into this error. Views.py class PropertyDetailSlugView(DetailView): queryset = Property.objects.all() template_name = "property/property_details.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) slug = self.kwargs.get('slug') obj = self.get_object() tags = obj.tag_set.all() if self.request.user.is_authenticated: for tag in tags: new_view = TagView.objects.add_count(self.request.user, tag) featured = list(Property.objects.filter(featured=True)) property_type = Category.objects.all() property_list = list(Property.objects.all()) city = City.objects.all().annotate( num_property=Count("property")).order_by("-num_property") favorite_property = get_object_or_404(Property, id=id) is_favorite = False if favorite_property.favorite.filter(id=self.request.user.id).exists(): is_favorite = True context['featured'] = featured context['is_favorite'] = is_favorite context['property_type'] = property_type context['property_list'] = property_list context['city'] = city return context Urls.py from django.contrib.auth.decorators import login_required from django.conf.urls import url from django.urls import path, re_path from .import views from .views import ( PropertyDetailSlugView, ) app_name = 'property' urlpatterns = [ path('<slug:slug>/', login_required(PropertyDetailSlugView.as_view()), name='details'), path('<int:id>/favorite_property/', views.favoriteProperty, name='favorite_property'), ] The error seems to occur while using the Id in Class Based Views is there a different way of using the Id's while using CBV. Any insight would be greatly appreciated. Thanks. -
How can you delete data after each output in django?
I'm building a scrapper that prints out the results on the same page, but whenever I try to search for new results, the old ones still appear. Meaning that the HTML doesn't get deleted at all after each search. I want that the data of the previous emails searched gets deleted for new ones. How can you do that? The code for printing emails: {% for email in email_list %} <p id="results"> {{ email }} </p> {% endfor %} Email list: def scrap(request): url = request.GET.get('Email') crawl = EmailCrawler(url) target = crawl.crawl() email_list = crawl.emails # or whatever class-level variable you use return render(request, 'leadfinderapp/emailsearcher.html', {"email_list": email_list}) For you to understand it better I will put two images: As you can see by the images, the first domains results appear correctly (which would be 3 emails) and the second domains results also appear, but it appears with the results of the first search. I want it to reset the results of the first instead and search for the new ones. -
Reload Bootstrap Toast without reload the page (with django)
I have a bootstrap toast (v 4.5.3) <div class="toast d-flex toast-success" role="alert" aria-live="assertive" aria-atomic="true" data-delay="3000"> <div class="toast-header toast-success"> <i class="fas fa-check"></i> </div> <div class="toast-body"> {{message}} </div> </div> After submiting a form with Ajax POST I want to reload the Toast to show the new message generated in my django view. Can I do that without reloading the entire page ? -
Django Forms - how to add the + sign for a Many2Many field
enter image description hereRelated to Django Forms and Many2Many I have tried to look for ways to add the + to my django form when I want to add a new post to my webpage. What I'm looking for is a similar function as the one in admin module. See picture. I have tried to read though the docs but not sure what to look for. Have anybody build something similar? br Lars -
use a django view in python script
In my django project, I have a url which on GET request, loads a template that gets converted to pdf using pdfkit. I need to use this url in my script so that I'm able to load the template and create the pdf using the script. In urls.py: re_path(r'^/send-invitation/(?P<policy_id>\d+)/$', views.send_invitation), In my views.py def send_invitation(request): //logic to call required details //load the template and create pdf // this part works fine return render(request, 'send_invitation.html',{ 'some_objects':some_objects, }) In my python script, I have: import os, sys import requests proj_path = sys.argv[1] + "myproject/" database = sys.argv[3] os.environ["DJANGO_SETTINGS_MODULE"] = "myproject." + sys.argv[2] sys.path.append(proj_path) # This is so my local_settings.py gets loaded. os.chdir(proj_path) # This is so models get loaded. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() from account_engine.models import * from django.conf import settings import datetime import string url = settings.WEB_ROOT + '/send-invitation/%s' % (policy.id) print('url being used %s' % url) from urllib.request import urlopen response = urlopen(url) simply loading the url in the browser results in template getting loaded and pdf getting created as required. However, same does not work in the script. My understanding is that since I'm doing urlopen, I'm sending a GET request to the url which ideally … -
How to add data to html table and get those data by clicking on corresponding rows
I'm adding table data using Java script. I need code for click event that picks all data from clicked row .I have a table in my code and all the data are added using java script. Now i need to get those added data by clicking corresponding rows. It can be achieved easily by using html elements but for some reasons i cant use the that method. I must use java script to add the data. I am using Django My code looks something like {% extends 'dashboard.html' %} {% block maincontent %} <form method="POST" action="showtrip" id="tripfrm"> {% csrf_token %} <label for="vn">Vehicle No</label> <input type="input" id="vn" name="vn" value="" > <label for="datefrom">Starring Date</label><input type="date" id="datefrom" name="datefrom"> <label for="starttime">Starring Time</label><input type="time" name="starttime"> <label for="dateto">Ending Date</label><input type="date" id="dateto" name="dateto"> <label for="endtime">Ending Date</label><input type="time" id="endtime" name="endtime"> <input type="submit" class="button1" id="sub" value="Check"> </form> <table class="listtbl" id ="listtbl" name= "listtbl" style="cursor: pointer;"> <tr> <th><label>Starting time</label></th> <th><label>Starting point</label></th> <th><label>reached time</label></th> <th><label>Destination Point<label></th> <th><label>AVG. speed<label></th> <th><label>Max Speed<label></th> <th><label>Engine ONTime<label></th> <th><label>Distance<label></th> <th><label>View Rout</label></th> </tr> </table> <script> $( "#vn" ).focus(function() { if(this.value=="select vehclle no"){ this.value="" } }); $( "#vn" ).focusout(function() { if(this.value==""){ this.value="select vehclle no" } }); </script> <script> $(function () { $("#vn").autocomplete({ source: '{% url 'vhnoload' %}' }); }); … -
How can we notify the admin about newly added project by user, by defualt project is_active=False
How the admin will be notified on the dashboard (not by mail), and verify all the projects or can decline the projects. class Compaigns(models.Model): nameOfDeceased = models.CharField(max_length=100, null=False, blank=False) nameOfDeceasedEn = models.CharField(max_length=100, null=False, blank=False) projectName = models.CharField(max_length=255, null=False, blank=False) projectNameEn = models.CharField(max_length=255, null=False, blank=False) phone = models.CharField(max_length=255, null=False, blank=False) image = models.ImageField(upload_to='projects/compaigns/%Y/%m/%d', blank=True, null=True) is_compaign = models.BooleanField(default=True) **is_active = models.BooleanField(default=False)** detail = models.TextField(blank=True, null=True) detailEn = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) suggestedDonation = models.DecimalField( max_digits=10, decimal_places=3, default=0.000) compaignCategory = models.ManyToManyField(CompaignCategory) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.nameOfDeceased class Meta: verbose_name_plural = "Compaigns" -
Django: Is there a way to make sure that only a unique FK related object can be added/related to the PK object?
Say there is a poll app and I want a user to vote only once for a poll question. Assume models.py to be as follows, class PollUser(models.Model): username = models.CharField(max_length=120, unique=True) class PollQuestion(models.Model): question = models.CharField(max_length=250) issuing_user = models.ForeignKey(PollUser, on_delete=models.CASCADE) class PollChoice(models.Model): text = models.CharField(max_length=250) votes = models.PositiveIntegerField(default=0) Is there a way to implement this functionality, without making this check in the views? -
Django Rest Framework: How to properly test a ViewSet?
I'm new to testing in DRF. I have the following ViewSet where I'm only allowing the 'List' and 'Retrieve' actions: class RecipeViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): permission_classes = [permissions.AllowAny] queryset = Recipe.objects.filter(visible=True).order_by('-created') pagination_class = RecipeListPagination lookup_url_kwarg = 'recipe_id' def get_serializer_class(self): if self.action == 'list': return RecipeListSerializer elif self.action == 'retrieve': return RecipeDetailSerializer These are the tests I've written so far: class RecipeViewSetTestCase(test.APITestCase): def setUp(self): # Create objects self.category = RecipeCategory.objects.create(name="meals") Recipe.objects.create(name="Pepperoni Pizza", category=self.category, description="It's rounded") Recipe.objects.create(name="Beef Ragu", category=self.category, description="It's moo'") # Get urls self.recipe = Recipe.objects.first() self.list_url = reverse('recipes-list') self.detail_url = reverse('recipes-detail', kwargs={'recipe_id': self.recipe.id}) def test_recipe_list(self): response = self.client.get(self.list_url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['results']), 2) def test_recipe_detail(self): response = self.client.get(self.detail_url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['name'], self.recipe.name) def test_recipe_create_not_allowed(self): response = self.client.post(self.list_url) self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) def test_recipe_delete_not_allowed(self): response = self.client.delete(self.detail_url) self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) def test_recipe_update_not_allowed(self): response = self.client.put(self.detail_url) self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) def test_recipe_partial_update_not_allowed(self): response = self.client.patch(self.detail_url) self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) I'm not sure if it's necessary to write a test for each method that shouldn't be allowed, or if there is a better way. Also, I'm not sure of what else I should be testing inside this viewset. Does anyone with experience in testing DRF knows how to properly test viewsets? Many thanks! -
django-tenant: tenant-aware file handling issue
I have a django project working with django-tenant. I want to segregate the templates in a way that tenants have custom templates. I believe that the process to achieve this is describe there: https://django-tenants.readthedocs.io/en/latest/files.html#target-dir however, I cannot get it to work for me. Here is my project tree myapp ├── customers │ ├── __pycache__ │ ├── migrations │ │ └── __pycache__ │ └── templates │ ├── landpage │ │ ├── contactform │ │ │ └── img │ │ ├── css │ │ ├── fonts │ │ └── js │ └── registration ├── dashboard2 │ ├── __pycache__ │ ├── migrations │ │ └── __pycache__ │ ├── migrations2 │ │ └── __pycache__ │ ├── templates │ │ └── dashboard2 │ │ └── pdf │ └── tenants │ └── itoiz │ └── templates ├── inventory4 │ └── __pycache__ ├── locale │ └── fr │ └── LC_MESSAGES ├── logs ├── mediafiles │ └── tenants │ └── t5 │ └── api │ ├── historical │ └── preprocessing ├── static │ ├── admin │ │ ├── css │ │ │ └── vendor │ │ │ └── select2 │ │ ├── fonts │ │ ├── img │ │ │ └── gis │ │ └── js │ │ … -
Get all entries with price greater than given price in json filed
I have a model Van which van_slug field and a price field I am using MySQL. I have to save different price for all 12 months. I am using jsonfield. class Van(models.Model): slug = models.SlugField(max_length=200) price = JSONField(null=True) I am saving price like this and showing price of current month to visitor. {'January': 987.0, 'February': 567.0, 'March': 567.0, 'April': 456.0, 'May': 6.0, 'June': 654.0, 'July': 456.0, 'August': 456.0, 'September': 456.0, 'October': 546.0, 'November': 89.0, 'December': 456.0} Problem I have to add an filter for min and max price. I don't know how can I do this. I have tried this Van.objects.exclude(price__June__gte=340) but this is raising error Unsupported lookup 'June' for JSONField or join on the field not permitted. I searched the error and found this only work in postgres. I know this solution query = User.objects.filter(data__campaigns__contains=[{'key': 'value'}]) but i don't need exact matching.Is there any other method to filter vans by price? -
How to Get Items in a model connected to another model using a foreign key in detail view in django?
I am trying to create a cartoon streaming website in which when a user clicks on their cartoon of choice(Eg:Pokemon), they get to see the seasons as a list as well as the detail of the cartoons. from django.db import models # Create your models here. class Cartoon(models.Model): name = models.CharField(max_length=200) cover = models.ImageField() description = models.TextField() start_date = models.CharField(max_length=50) end_date = models.CharField(max_length=50) def __str__(self): return self.name class CartoonSeason(models.Model): cartoon = models.ForeignKey(Cartoon, null=True, on_delete=models.SET_NULL) number = models.IntegerField() season_cover = models.ImageField(blank=True, null=False) season_name = models.CharField(max_length=200, blank=True, null=True) season_description = models.TextField(blank=True, null=False) Here I have linked the Cartoon model with the CartoonSeason model using a Foreign Key so when a new season is to be added, it automatically gets linked with the corresponding Cartoon # Create your views here. from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView, DetailView from .models import CartoonSeason, Cartoon # Create your views here class CartoonListView(ListView): model = Cartoon template_name = "index.html" class CartoonSeasonView(DetailView): queryset = CartoonSeason.objects.filter() model = CartoonSeason template_name = "season.html" I am using a detail view to display the CartoonSeason model so that it displays the Cartoons details as well, but when I try to load the seasons, it only displays … -
ML and Django: using Conda and Pip depending on what I am doing... no?
So I am starting in Data Science and there are two things I am using quite a bit: Machine learning and Django. I have looked throughout the internet and the two worlds seems to be at different ends - ML going with Anaconda/miniconda and Django with PIP. To me, it makes sense, Anaconda has most of the packages needed for DS and feels a more solid option when using it for those purposes (i.e. data analysis, wrangling, ml modelling, etc). However, for Django, there seems to be everyone (by everyone I mean tutorials and articles on Django) uses PIP. And it makes sense, when deploying a quick app, all you want to do is to create a virtual env, install the needed packages, build the app, pip freeze it and upload to server. Boom. However, the more I look on the internet, everyone seems to be use either Anaconda/miniconda or PIP. Some stuff I read on Stackoverflow mentions using pip inside Anaconda/miniconda's environment... but for that I would have to create a PIP-virtual-environment inside Anaconda/miniconda's environment. As you can see, as a newbie, I feel slightly confused with this. As anyone got experience this? What did you do? -
How to Import User and UserProfile data from UserProfile Model Admin?
I have this custom User model- class User(AbstractUser): email = models.EmailField(unique=True) picture = models.ImageField(upload_to='profile_picture', null=True, blank=True) updated_on = models.DateTimeField(auto_now=True) date_activated = models.DateTimeField(null=True, blank=True) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class Meta: verbose_name = 'User' and this UserProfile model- class UserProfile(models.Model): user = models.OneToOneField(User, related_name='userprofile', on_delete=models.PROTECT, primary_key=True) contact = models.CharField(max_length=20, blank=True, default='') about_me = models.TextField(null=True, blank=True) latitude = models.FloatField(validators=[MinValueValidator(-90), MaxValueValidator(90)], null=True, blank=True) longitude = models.FloatField(validators=[MinValueValidator(-180), MaxValueValidator(180)], null=True, blank=True ) age = models.IntegerField(validators=[MinValueValidator(18), MaxValueValidator(100)], null=True, blank=True ) dob = models.DateField(null=True, blank=True,) source_of_registration = models.ForeignKey('core.SourceOfRegistration', on_delete=models.PROTECT, null=True,blank=True ) interests = models.ManyToManyField('core.Interest') languages = models.ManyToManyField('core.SpokenLanguage') gender = models.ForeignKey('core.Gender', on_delete=models.PROTECT, null=True, blank=True ) country = models.ForeignKey( 'core.Country', on_delete=models.PROTECT, null=True, blank=True ) state = models.ForeignKey('core.State', on_delete=models.PROTECT, null=True, blank=True) city = models.ForeignKey('core.City', on_delete=models.PROTECT, null=True, blank=True) zip_code = models.CharField(max_length=12, null=True, blank=True) is_profile_completed = models.BooleanField(default=False) profile_completed_on = models.DateTimeField(null=True, blank=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Meta: verbose_name = 'User Profile' def __str__(self): return self.user.email def clean(self): if self.dob: age_in_days = (datetime.date.today() - self.dob).days age_in_years = age_in_days / 365 if age_in_years < 18: raise ValidationError(gettext_lazy('Age should be more or equal to 18.')) else: self.age = age_in_years This is the UserProfileResource- class UserProfileResource(resources.ModelResource): class Meta: model = UserProfile import_id_fields = … -
How to create a tree view of a directory in a django website
I need to create a tree view of a directory in my Django website The folder structure is like Root Folder Folder 1 File(s) Folders and Files Folder 2 File(s) Folder(s) File(s) or in a similar fashion -
Getting error while defining request in signal receiver
I want a mail to be sent for activating the account.I am using signal concept in django.Created a UserConfirmation Model where I am storing user_id and token.While I am clicking on the user_registration button after populating all the fields I am getting this error TypeError: send_email() missing 1 required positional argument: 'request' If I am assigning a parameter in receiver decorator NameError: name 'request' is not defined @receiver(post_save,request,sender = UserConfirmation) My user table and user_confirmation table is getting populated with the data. @receiver(post_save,sender = UserConfirmation) def send_email(sender,request,instance,created,**kwargs): if created: current_site = get_current_site(request) send_mail( "Account Activation Link", f"Hi Plese click on below given link to activate your account.\n{instance.selector}\{instance.token}", "cj@teckzilla.net", [instance.email], Thanks In Advance -
Django ORM implementation of StdDev on DateTimeField
I'm trying to get the standard deviation of a time in Django. I keep running into django.db.utils.ProgrammingError. I tried it with various data types (DateTimeField, DurationField, IntegerField), also tried casting it first. Event.objects.annotate(StdDev(F('end_ts') - F('start_ts'), output_field=models.DurationField())) Event.objects.annotate(x=Cast(F('end_ts') - F('start_ts'), models.DurationField())).annote(y=StdDev(x, output_field=models.DuratinField)) Given the error, I think it's not yet implemented: django.db.utils.ProgrammingError: function stddev_pop(interval) does not exist LINE 1: SELECT "app_event"."task_id", STDDEV_POP((("app_event"."end_... However, it would save me quite some performance to do it with the ORM compared to manually in Python. If anybody knows a work-around with the ORM, that would be much appreciated! -
Django form data modification with jquery
I am trying to adapt an already working application in Django, but I am quite new to this environment and I am not the original developer so I may have some conceptual errors, but I have not found a way to solve the problem. I have a django model which references a client list: clients = models.ManyToManyField( Client, blank=True, verbose_name=_('Clients'), related_name='clients', ) It is being feed in the admin using the autocomplete feature, obtaining the client data from the other table. This is working perfectly. I want to preload some data based on a select dropbox I have included in the form. On change of the select box, I want to include some values on this manytomany field. I am using jquery to add values to the field, and as far as I have found, I need to add the client references in two places: Add the name and the Id in a Select <select name="clients" id="id_clients" class="admin-autocomplete select2-hidden-accessible" data-ajax--cache="true" data-ajax--type="GET" data-ajax--url="/en/admin/client/client/autocomplete/" data-theme="admin-autocomplete" data-allow-clear="true" data-placeholder="" multiple="" tabindex="-1" aria-hidden="true"> <option value="2355">Client1</option> </select> Add the name in the unordered list (ul) as a new li. <ul class="select2-selection__rendered"> <span class="select2-selection__clear">×</span> <li class="select2-selection__choice" title="Client1"> <span class="select2-selection__choice__remove" role="presentation">×</span>Client1</li> <li class="select2-search select2-search--inline"> <input class="select2-search__field" type="search" tabindex="0" …