Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
accessing dict in django template
I have a django project writing to a PSQL database and I am figuring out how to check which queries are being done. Is there a way to check which queries actually make it to the database? I noticed some queries are cached and use no actual call to the database. (https://docs.djangoproject.com/en/1.11/topics/db/queries/#caching-and-querysets) Reason why I ask: I have a model JobId, which holds all jobs processed on my platform. Processing jobs uses credits. At the end of each job, I save the JobId.credit_detla (= amount credits used) and JobId.credits (= amount credits on account left). I want to show the JobId.credits in the navigation menu but don't want to pull queries on every visited page for this single value. So 2 questions: how could I figure out the quantity of queries? is there a better typical-one-liner-code practice to get this query result in my navigion menu? -
Passing JavaScript variable into Django url?
I have a dropdown menu that allows the user to select between three different use cases, and I want to pass that information to the next page. <option id='b2c-menu' value="Delivery">Delivery</option> <option id='taxi-menu' value="Air Taxi">Taxi</option> <option id='hub-menu' value="Hub-to-Hub">Metro</option> On select, I'm capturing this option as a variable in my JavaScript, and I'd like my second page to be aware of what the currently selected option is. To pass that, I'd like to do something like this: <a href="page2/{{ selected_option }}"</a> Is there a way to make my links dynamic based on my JS content? -
Python - Django - server - Searches for installed module in wrong version of Python using WinSCP
when I try to load my server using Django, I get a 'no module named bs4' error. It seems that it searching to for it in Python 2.7 library instead of Python3.6. python 3.6 is in my PATH. I tried looking, but I'm pretty new to this and don't quite understand all the jargon. Can someone 'explain like I'm 5' on how to make it so that it searches Python 3.6 instead of python 2.7? This is the error: ImportError at / No module named bs4 Request Method: GET Request URL: http://104.236.89.238/ Django Version: 1.8.7 Exception Type: ImportError Exception Value: No module named bs4 Exception Location: /usr/lib/python2.7/dist-packages/gevent/builtins.py in __import__, line 93 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/django/django_project', '/home/django/django_project', '/usr/bin', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] Server time: Mon, 11 Dec 2017 20:58:02 +0000 I'm using WinSCP to transfer the files. Everything works perfectly on a local host before I transfer the files and try and run it on a server. Here are some settings on WinSCP. First here is my manage.py #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_project.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) my settings.py in WinSCP is: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) … -
How can I avoid "database is locked" sqlite3 errors in django?
Django version 1.11, sqlite3 version 3.11. I'm using WAL mode and a long timeout: from django.apps import AppConfig from django.db.backends.signals import connection_created class SQLite3Config(AppConfig): name = 'sqlite3_config' def ready(self): connection_created.connect(configure_sqlite) # noinspection PyUnusedLocal def configure_sqlite(sender, connection, **_): if connection.vendor == 'sqlite': cursor = connection.cursor() cursor.execute('PRAGMA journal_mode=WAL;') cursor.execute('PRAGMA busy_timeout=5000;') I want to retain sqlite3 and not move to mysql or postgres because the application is small and is installed by users on multiple servers. I believe WAL should allow "concurrent" writes by serializing them. The "Database is locked" problem was observed when small bursts (half a dozen or so) were received together. I can reproduce the problem in the shell with threads. The django model method simply sets a flag and saves the model: def activate(self): self.activate = True self.save() When I use threads I find it fails if I launch a few threads that attempt it at the same time. There is no wait so the timeout is not involved. The error occurs before the 5 second busy timeout has elapsed (in less than two seconds): In [2]: [NGThread(notifier_group.id).start() for notifier_group in NotifierGroup.objects.all()[:2]] Out[2]: [None, None] In [3]: [NGThread(notifier_group.id).start() for notifier_group in NotifierGroup.objects.all()[:3]] Out[3]: [None, None, None] In [4]: [NGThread(notifier_group.id).start() … -
django cannot read css file in static folder
I am trying to make a base.html template and inserting a css file in the header. in the page it includes all the styling by it does not do any styling when the link the other page is pressed. I have two files extending base.html one color_choose.html the other statistics.html which have the exact same lines for linking files. color_choose.html works and it is the first page that opens when navigated and the other is statistics.html here is the base.html: <!DOCTYPE html> <html lang="eng"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> <title>ColorStore</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> {% block styles %} {%endblock%} </head> <body> <div id="ColorFavor"> <div style="float: right;"> <h2 id="title" class="page-name">Color Picker</h2> </div> </div> {% block navigation %} {% endblock %} {% block display %} {% endblock %} {% block modal %} {% endblock %} {% block scripts %} {% endblock %} </body> </html> here is the urls.py in the app file: from django.urls import path from . import views urlpatterns = [ path('', views.ColorPageView.as_view(), name='color'), path('statistics/',views.StatsPageView.as_view(), name='statistics'), this is the file css is applied and is also the same text in the other file: {% extends 'base.html' %} … -
complex nested data representation
I'm trying to get all Currency objects with the Ticker objects nested in each currency object. So far i've only been able to get the tickers with the currency object inside, but this is really not convenient? i'm not sure what changes i need to make to achieve below output so for instance what i want is something like this: [ { "id": 1, "name": "Dollar", "symbol": "USD" "ticker": [ { "id": 1, "rank": 1, "price_dkk": 123.25 } ] } ] models class Currency(models.Model): symbol = models.CharField(max_length=4, default='BTC', unique=True) name = models.CharField(max_length=20, default='Bitcoin', unique=True) img = models.ImageField(upload_to = 'static/img/currencies', blank=True) is_active = models.BooleanField(default=False) class Meta: verbose_name_plural = _('currencies') def __str__(self): return self.name class Ticker(models.Model): currency = models.ForeignKey('Currency', on_delete=models.CASCADE) rank = models.IntegerField() price_dkk = models.DecimalField(max_digits=20, decimal_places=6) market_cap_dkk = models.BigIntegerField() percent_change_1h = models.DecimalField(max_digits=4, decimal_places=2) percent_change_24h = models.DecimalField(max_digits=4, decimal_places=2) percent_change_7d = models.DecimalField(max_digits=4, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = _('Ticker') def __str__(self): return self.id serializer class CurrencyTickerSerializer(serializers.HyperlinkedModelSerializer): currency = serializers.PrimaryKeyRelatedField(many=False, queryset=Currency.objects.all()) class Meta: model = Ticker fields = ('currency', 'rank', 'price_dkk', 'market_cap_dkk', 'percent_change_1h', 'percent_change_24h', 'percent_change_7d',) -
Django OneToOneField relation with to_field and db_column been ignored on makemigrations files
Even after reading the docs on db_column and Django' recomendations I was not able to accomplish the desired results with this feature. This is part of my code class DefaultBaseModel(models.Model): slug = models.SlugField(primary_key=True, unique=True, null=False, blank=False) class Bill(DefaultBaseModel): class Payment(DefaultBaseModel): bill = models.OneToOneField(Bill, related_name='payments', on_delete=models.CASCADE, to_field='slug', db_column='bill_slug') What I expect to do is the following on Django's shell: from apps.bills.models import Bill b = Bill.objects.first() b.branch_slug However I get the error: Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'Bill' object has no attribute 'branch_slug' Well, b.branch_id gives me the slug value but it is still creating the column with the suffix _id. I tried to delete makemigrations (migrate) files (those initial.py and others) and create it again Moved from Sqlite to Postgres Looked into Django's makemigrations files and db_column='bill_slug' was there. Any ideas? -
DRF - Nested serializer disappears after parent is_valid() call
TLDR; (full description below) Valid field with nested serializer is dropped upon validation of parent serializer. I read some StackOverflow posts about similar cases, but there the field was dropped because of being read_only=True which is not my case. After POSTing valid object to CreateParentView(generics.CreateAPIView) I get Http 400 Bad request error. I ended up debugging the create() method. # parsed_data is a QueryDict prepared from request.POST and request.FILES # to fit the nested serializers format. -> serializer.is_valid(raise_exception=True) (Pdb) parsed_data.keys() odict_keys(['parent_field_1', 'parent_field_2', 'parent_field_3', 'child']) (Pdb) from .serializers import CreateChildSerializer; ch = parsed_data.get('child'); new_child = CreateChildSerializer(data = ch); (Pdb) new_child.is_valid() True (Pdb) new_child.errors {} # the parent serializer is invalid and drops the 'child' key (Pdb) serializer.is_valid(); False (Pdb) serializer.data.keys() odict_keys(['parent_field_1', 'parent_field_2', 'parent_field_3']) The response is 400 (Bad Request), "{"child":["This field is required."]}" Dafuq, I just provided you with that, and you, sir, dropped it :-( End Of TLDR; Okay, lets have a look on the View, the Serializer and the Model. I'm using a toy model, my real one is too verbose to reproduce here. Lets start with the models.py - the Child and Parent models are OneToOneField relationship. # models.py class Parent(models.Model): objects = ParentManager() user = models.ForeignKey('auth.User', on_delete=models.CASCADE) … -
validate no duplicates in streamfield
Need to create a long scroll page with sidebar nav for on-page navigation. This means each heading will have an id. Can I validate at the streamfield level to make sure a user doesn't put in a duplicate id? -
Select Serializer for field in Django Serializer class
i have Model where i can have owner is user or client @property def owner(self): return self.created_by_user or self.created_by_client and have serializer where i need this field class MessageSerializer(serializer.ModelSerializer): owner = (can be user or client) i take it from @property in model I have 2 serializer UserSerializer and ClientSerializer i want write for owner something like this owner = UserSerializer if insstance(User, value) or ClientSerializer if insstance(Client, value) Any idea?? -
Django Attribute Error: module 'appname' has not attribute models
I know my question probably deals with mutual/circular imports, and I did search SO before posting. The only solution I found that currently solves my problem is to move imports to the end of one of the files, just before the imported functions are actually used. But I've also read that's highly unrecommended. A recommended solution, to just do: in A.py -> import B and in B.py -> import A And then access the functions, isn't working. So I have three apps in my Django app: "core", "notifications", and "accounts". Here are snippets from them: core.models: from django.db import models from django.contrib.auth.models import User import notifications.models from z_misc import general_scripts # Create your models here. class BaseModel(models.Model): created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) class Meta: abstract = True notification.models: from django.db import models import core.models import accounts.models class Notification(core.models.BaseModel): artist_id = models.OneToOneField(core.models.Artist, related_name="artist_notifications", null=False) release_group = models.OneToOneField(core.models.ReleaseGroup, related_name="rg_notifications", null=False) def get_rg_type(self): return self.release_group.type accounts.models: from django.db import models from django.contrib.auth.models import User import core.models from django.db.models import Q # Create your models here. class UserProfile(core.models.BaseModel): #TODO: add email_activated = models.BooleanField(default=False) user = models.OneToOneField(User, related_name="user_profile") As you can see, I'm following the advice not do from and then import, but to … -
Recursion loop in views and templates
I have 2 models, Category and Products class Product(Meta): categories = models.ManyToManyField(Category, related_name='products') class Category(Meta): parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', on_delete=models.CASCADE) When a user select a Category I need to show all the products in that category including all product of his children and grandchildren etc. The Category has a FK to itself, so the number of depth levels theoretically is infinite so I need to extract all product from any category below parent depth. -
Django hidden field is not saving to database
I am trying to save users IP address in my extended profile model. The goal is to make this a hidden field. Currently, I can debug by printing the IP address to the console. The issue arises when I try and save the info. views.py def index(request): #request.session.flush() if request.user.is_authenticated: return redirect('ve:dashboard') elif request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.refresh_from_db() # Load the profile instance created by the Signal user.profile.birth_date = form.cleaned_data.get('birth_date') user.ipaddress = get_ip(request) print(user.ipaddress) user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('ve:dashboard') else: form = RegistrationForm() return render(request, 'index.html', {'form': form}) forms.py class RegistrationForm(UserCreationForm): # birth_date = forms.DateField(help_text='Required. Format: YYYY-MM-DD') birth_date = forms.DateField(widget=SelectDateWidget(years=range(1999, 1910, -1))) #ipaddress = forms.IntegerField(widget=forms.HiddenInput(), required=False) class Meta: model = User fields = ('username', 'email', 'birth_date', 'password1', 'password2',) exclude = ['ipaddress',] index.html <form method="post"> {% csrf_token %} {% for field in form %} <p class="text-left"> {{ field.label_tag }}<br> {{ field }} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Sign up</button> </form> models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... ipaddress = models.CharField(default="104.236.0.10", max_length=30) This form was working fine before I tried adding the ipaddress … -
Use a constant inside models.Func()
I want to compute a datetime difference by using the timestampdiff sql function in django. I tried by this way : models.Func( models.Value('SECOND'), models.F('date1'), models.F('date2'), function='timediff') but models.Value() add quotes to the parameter which must be set as a constant. The final request I want to do is timestampdiff(SECOND,date1,last_date2) Can I do this with django and Func object ? -
Django retrieving object instances created during last two weeks
I have a model called Book which has an attribute when_added which stores the time when an instance of the object is created: class Book(models.Model): book_id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) # Record the date whenever a new book is added, it will be helpful for showing new arrivals when_added = models.DateTimeField(auto_now_add=True, blank=True, null= True) #This helps to print in admin interface def __str__(self): return u"%s" % (self.title) I am writing a view that will return me list of books those were added during last two weeks: from datetime import date, timedelta @api_view(['GET']) def new_arrivals(request, library_id): """ List all new arrival books in a specific library """ d=date.today()-timedelta(days=14) print(d) if request.method == 'GET': books = Book.objects.filter(which_library=library_id) books = books.filter(when_added=d) print(books) serializer = BookSerializer(books, many=True) return Response(serializer.data) Here I get a warning saying RuntimeWarning: DateTimeField Book.when_added received a naive datetime (2017-11-27 00:00:00) while time zone support is active. and no book is returned. What am I doing wrong? -
oReverseMatch at /posts/post/18/comment/ Django Error
I've been getting this error, and I couldn't seem to fix it. Here is a screenshot of it: erros image Here my view's.py:' from django.shortcuts import render, get_object_or_404, redirect from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from posts.forms import PostForm, CommentForm from django.core.urlresolvers import reverse_lazy from django.http import Http404 from django.views import generic from braces.views import SelectRelatedMixin from . import forms from . import models from django.contrib.auth import get_user_model User = get_user_model() class PostList(SelectRelatedMixin, generic.ListView): model = models.Post select_related = ("user", "group") class UserPosts(generic.ListView): model = models.Post template_name = "posts/user_post_list.html" def get_queryset(self): try: self.post_user = User.objects.prefetch_related("posts").get( username__iexact=self.kwargs.get("username") ) except User.DoesNotExist: raise Http404 else: return self.post_user.posts.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["post_user"] = self.post_user return context class PostDetail(SelectRelatedMixin, generic.DetailView): model = models.Post select_related = ("user", "group") def get_queryset(self): queryset = super().get_queryset() return queryset.filter( user__username__iexact=self.kwargs.get("username") ) class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): # form_class = forms.PostForm fields = ('message','group') model = models.Post # def get_form_kwargs(self): # kwargs = super().get_form_kwargs() # kwargs.update({"user": self.request.user}) # return kwargs def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) class DeletePost(LoginRequiredMixin, SelectRelatedMixin, generic.DeleteView): model = models.Post select_related = ("user", "group") success_url = reverse_lazy("posts:all") def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user_id=self.request.user.id) def delete(self, *args, **kwargs): … -
heroku : git push heroku master
I wrote a web app and I want to deploy it by heroku.I'm new to this and couldn't figure out this problem.I already searched everything about this but didn't work.Hope you guys can give me some suggestions. This is my requirements.txt alabaster==0.7.10 asn1crypto==0.22.0 astroid==1.4.9 astropy==1.3.2 Babel==2.4.0 backports.shutil-get-terminal-size==1.0.0 comtypes==1.1.2 conda==4.3.21 contextlib2==0.5.5 cryptography==1.8.1 cycler==0.10.0 Cython==0.25.2 cytoolz==0.8.2 dask==0.14.3 datashape==0.5.4 decorator==4.0.11 distributed==1.16.3 dj-database-url==0.4.2 dj-static==0.0.6 docutils==0.13.1 entrypoints==0.2.2 et-xmlfile==1.0.1 fastcache==1.0.2 Flask==0.12.2 Flask-Cors==3.0.2 gevent==1.2.1 greenlet==0.4.12 gunicorn==19.7.1 h5py==2.7.0 ....... xlwings==0.10.4 xlwt==1.2.0 zict==0.1.2 psycopg2==2.6.1 When I got error I'll delete the line in requirements.txt.At the first I thought that is only one but the truth is more the one not found.Everytime I will commit ater I change requirement.txt.I don't know why and how to debug.I hope it can run and I can deploy it. This is my error C:\Users\user\django_project>git push heroku master Counting objects: 13090, done. Delta compression using up to 4 threads. Compressing objects: 100% (9553/9553), done. Writing objects: 100% (13090/13090), 118.21 MiB | 316.00 KiB/s, done. Total 13090 (delta 2753), reused 12586 (delta 2529) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.3 remote: -----> Installing pip remote: -----> Noticed cffi. Bootstrapping libffi. remote: -----> Installing requirements with … -
ModuleNotFoundError but path to module is correct
I have a Django project with my models, views, and URLs set up. The path structure is as follows: --MainProject --Measurements --views.py --urls.py --models.py --migrations --templates.py --management --commands --add_data.py --clear_data.py --init.py --_pycache_ When building this project, I created the models.py first and then made migrations. Afterwards, I migrated. The add_data.py file adds data to the table and the clear_data.py file removes the data. I ran the add_data.py file and it worked once, but I had similar errors leading up. I forgot how I made it run through the command line. However, now if I delete the database and try to run the add_data.py file I get this error: from measurements.models import Area, Category, Location, Measurement ModuleNotFoundError: No module named 'measurements' Here's my code: models.py from django.db import models from django.db.models import Avg class Area(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=200) longitude = models.FloatField() latitude = models.FloatField() def number_of_locations(self): return len(self.location_set.all()) # Function to get the average measurements of locations in area def average_measurement(self): return Measurement.objects.filter(location__area=self).aggregate(Avg('value'))['value__avg'] # Get all category names for area def category_names(self): categories = self.category_set.all() cList = "" for category in categories: cList+= category.name + ", " return cList[:-2] def __str__(self): return self.name class Location(models.Model): id = models.IntegerField(primary_key=True) … -
How to get one users object from a foreign key in Django?
I'm making a contact list and only want to display the contacts for the current user and not allow anybody who didn't make the contact view the contacts. Basically, I want to have contacts specific to the user that made them and viewable by only the person who made them views from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin from . import forms from . import models from django.views import generic from django.contrib.auth import get_user_model User = get_user_model() from django.http import Http404 # Create your views here. class ContactList(generic.ListView,LoginRequiredMixin): model = models.Contact template_name="PhoneBook/contact_list.html" def get_queryset(self): self.use = User.objects.prefetch_related("contacts").get( user__username__iexact=self.kwargs.get("username") ) return self.use.contacts.all() class CreateContact(generic.CreateView,LoginRequiredMixin): model = models.Contact form_class = forms.ContactForm def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) class ContactDetail(generic.DetailView): model = models.Contact models from django.db import models from django.conf import settings from django.core.urlresolvers import reverse from django.contrib.auth import get_user_model User = get_user_model() from django.core.validators import RegexValidator class Contact(models.Model): user = models.ForeignKey(User,related_name="contacts") fullname = models.CharField(max_length=100) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Invalid Input") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True,null=True) email = models.EmailField(blank=True,null=True) def __str__(self): return self.fullname def get_absolute_url(self): return reverse( "PhoneBook:view", kwargs={ "pk": self.pk } ) class Meta(): unique_together = ('user', 'fullname') contact_list.html {% extends "base.html" %} {% block content … -
how to get a related value from a ForeignKey model django admin
I've a model with a fk, but when save method I need get related value, e.g: class Pedidos(models.Model): ped_cliente = models.ForeignKey(Clientes, verbose_name='Cliente') ped_remetente = models.ForeignKey(Remetentes, verbose_name='Remetente') ped_produto = models.ForeignKey(Produtos, verbose_name='Produto') ped_data_pedido = models.DateField(verbose_name='Data Pedido') ped_quantidade = models.DecimalField(verbose_name='Peso/Volume', max_digits=10, decimal_places=0) ped_key = models.IntegerField(unique=True, editable=False, verbose_name='Cod. Pedido') class Pagamentos(models.Model): pag_cliente = models.ForeignKey(Clientes, verbose_name='Cliente') pag_key_ped = models.ForeignKey(Pedidos, verbose_name='Cód. Pedido') pag_vencimento = models.DateField(verbose_name='Data Vencimento') pag_vlr_total = models.DecimalField(verbose_name='Valor Total', max_digits=10, decimal_places=2) I need when I save model Pagamentos the value field: pag_key_ped receive Pedidos.ped_key value How I do to access this value? -
Ordering a django queryset by sum of two (or more) fields
I have found a few questions that are similar to mine, but most of them are dated, or too (or too little) verbose to be helpful. I have a model like this: class Breakfast(models.Model): count_eggs = models.IntegerField() count_bacon = models.IntegerField() had_toast = models.BooleanField() Now, in building a RESTful API, I need the ability to sort Breakfast objects by the total of count_eggs + count_bacon without storing this permanently on the model. Many of the current and popular questions suggest something like this: Breakfast.objects.extra( select={'total_food':'count_eggs + count_bacon'}, order_by=('total_food',) ) This seems to work for many, but Django docs appear to dissuade this solution. So, in the 1.10+ world, What is the best/correct way to do this type of filtering on the sum of two (or more) fields in Django -
Cannot use extra_option with path django
I don't understand why I cannot use the path() method as documented here: https://docs.djangoproject.com/en/2.0/topics/http/urls/#passing-extra-options-to-view-functions in my apps urls.py. Here is the code I have: from django.conf.urls import url, include from django.contrib import admin from django.urls import path from . import views as AliasViews from permissions import views as PermissionsViews urlpatterns = [ ... path(r'^user/(?P<alias_id>\d{1,})/members/?$', AliasViews.UserAliasMember.as_view(), name='useralias_member', {'alias_type':'UserAlias'}), ... ] I get this error: SyntaxError: non-keyword arg after keyword arg. -
prefetch_related and Prefetch object tripple search(2 reverse), and one distinct
I have 3 models Category, Account, and Products class Product(Meta): categories = models.ManyToManyField(Category) company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE) I want to get: the Products for Company, and the Categories of the Products the Categories distinct (use as a sidebar) to filter the Company products by Category first/by id Category of the Product to show as text near Product name On a View inheriting from DetailView: def get_queryset(self): qs = super().get_queryset() products = Product.objects.order_by('-updated_at', '-created_at').prefetch_related( Prefetch('categories', queryset=Category.objects.distinct())) return qs.prefetch_related( Prefetch('products', queryset=products)) are displayed as categories.Category.None So, I can access the products as company.products.all and category as product.categories.all in the loop Now the distinct works inside the Product relation, but how I get the all categories (not by product) distinct ? I tried {% regroup products.all.categories by products.all as category_list %} {% for cat in category_list %} {{ category.name}} {% endfor %} but is not working. Try also variation with or without calling all. -
'WSGIRequest' object has no attribute 'session' AT LOGIN
I'm trying to teach myself python\Django. This was built in Visual Studio with the Django starter site so all the settings.py etc where prebuilt and just added upon. When I attempt to login to the site from the IIS Server I get "AttributeError at /login/ 'WSGIRequest' object has no attribute 'session'" although when I attempt to run it on my local machine from "python manage.py runserver" it runs just fine. settings.py 1/3 | 2/3 | 3/3 -
How to filter in prefetch_related columns?
I have this code, where I combine a list of articles to their (translated) descriptions: desc = models.ArticleDescription.objects.filter(lang__iexact=translation.get_language()) c = models.Article.objects.all().order_by('articleid').prefetch_related( Prefetch('articledescription_set', queryset=desc, to_attr='description_tr')) this works fine, but how can I now filter the descriptions? Let's say I only want the description "foo". I am looking for something like this: desc = models.ArticleDescription.objects.filter(lang__iexact=translation.get_language()) c = models.Article.objects.all().order_by('articleid').prefetch_related( Prefetch('articledescription_set', queryset=desc, to_attr='description_tr')). filter(description_tr__description="foo") But that doesn't work. How can I achieve this?