Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset processing to filter out duplicate and none values
In a Django app, I can access user sessions and then get users_ids with flat=True. E.g. I'm doing: Session.objects.filter(last_activity_gte=time_window).values_list('user_id',flat=True) But the result is tainted by duplicates and None values. How do I perform the same query and filter out None or duplicates? One way to do this is: time_window = timezone.now() - timedelta(minutes=5) user_ids = Session.objects.filter(last_activity_gte=time_window).values_list('user_id',flat=True) user_ids = [id for id in user_ids if id is not None] user_ids = set(user_ids) But I wonder if I could have achieved that directly while querying the DB, which would be faster. Performance is crucial. If anyone's interested, I'm using https://github.com/Bouke/django-user-sessions to be able to access Django session objects as ORM objects -
Linking words in text to records in another table
I'm using Python 3 and Django 1.10.1 to write a simple dictionary application; there is a list of words with translations and additionally a database of example sentences where the usage of a particular word (in the target language) is explained. A sentence can contain examples of multiple words, of course. Because the word should be highlighted in the example sentence, each entry in the dictionary needs information not only about the example sentences, but also which words in those example sentences should be highlighted. Of course, one solution is to just hardcode the highlighting in the sentences themselves, duplicating them for each dictionary word that uses them. This would work, but requires more work and/or some form of preprocessing the data, and makes adding new entries or editing existing ones cumbersome. Can Django's model system be used to express these kinds of relations? -
Upload file issue Django
Currently i am using below code in my views for uploading file , it works fine on local but on remote server sometime uploads sometime fails file format is pdf files = request.FILES['file'] location_of_file = "testfile.pdf" with open(location_of_file,'w') as cv: for chunk in files.chunks(): cv.write(chunk) Any issue with code ? or anyother better way ? I got this from offical djangodocs. -
I am using mssql db.i made following changes but now i am getting followinfg error " ImportError: No module named 'django.db.backends.util' "
DATABASES = {'default': {'NAME': 'test','ENGINE': 'sqlserver_ado','HOST':'127.0.0.1','USER': 'mssql','PASSWORD': 'mssql','PORT': '1434' } } -
How to query tables having manyTomany field in django
class Publication(models.Model): title = models.CharField(max_length=30) class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) I actually need a single query that can get all "title" and "headline". I need another query for where i can filter using either title or headline. Lastly, I want to filter using both column e.g select all where title="Money" and publication="money talks" Thank you -
How to store a dynamic site-wide variable
I have an html file which is the base,where other html documents extends.Its a static page but i want to have variable in the menu.I don't think it's wise to create a view for it,since i don't intend to let users visit the base alone.So where in my project can I store site-wide dynamic variables that can be called on any page without explicitly stating them in their views. Thank you in advance. -
How to perform Or Query using Django-Filter
class MyFilter(django_filters.FilterSet): class Meta: model = MyModel fields = { 'field': ['exact', 'isnull'], } Now How do I filter this ?field=1&field__isnull=True ??? -
The field was declared on serializer , but has not been included error in django rest
I created few serializers in my django REST API and stuck with weird problem. When i go to the http://127.0.0.1:8000/api/register/ url i'm get error: The field 'photos' was declared on serializer UserSerializer, but has not been included in the 'fields' option. But my UserSerializer doesn't even have 'photos' field. I'm new in django, please, help me to understand source of this problem. serializers.py from django.utils import timezone from django.contrib.auth.models import User from rest_framework import serializers from api.models import Album, Photo class PhotoSerializer(serializers.HyperlinkedModelSerializer): #url = serializers.HyperlinkedIdentityField(view_name="photo-detail") album = serializers.HyperlinkedRelatedField(view_name='album-detail', queryset=Album.objects) owner = serializers.HyperlinkedRelatedField(view_name='user-detail', queryset=User.objects) class Meta: model = Photo fields = ('url', 'name', 'image', 'creation_date', 'owner', 'album') read_only_fields=('creation_date') class AlbumSerializer(serializers.HyperlinkedModelSerializer): #url = serializers.HyperlinkedIdentityField(view_name="album-detail") owner = serializers.HyperlinkedRelatedField(view_name='user-detail', queryset=User.objects) photos = serializers.HyperlinkedRelatedField(view_name='photo-list', queryset=Photo.objects, many=True) def get_validation_exclusions(self): # Need to exclude `author` since we'll add that later based off the request exclusions = super(AlbumSerializer, self).get_validation_exclusions() return exclusions + ['user'] class Meta: model = Album fields = ('pk', 'name', 'creation_date', 'owner', 'photos') read_only_fields=('creation_date') class UserSerializer(serializers.HyperlinkedModelSerializer): #url = serializers.HyperlinkedIdentityField(view_name="user-detail", read_only=True) albums = serializers.HyperlinkedRelatedField(many=True, view_name='album-list', queryset=Album.objects) password = serializers.CharField(write_only=True, required=True) confirm_password = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('url', 'pk', 'username', 'email', 'password', 'is_staff', 'albums') write_only_fields = ('password') read_only_fiels = ('pk') def create(self, validated_data): β¦ -
Is there a more recursive way to do this?
I have the following code: {% if thing.parent.parent.parent.link %} <a href="/y/{{ thing.parent.parent.parent.link }}">{{ thing.parent.parent.parent.name }}</a> {% endif %} {% if thing.parent.parent.link %} <a href="/y/{{ thing.parent.parent.link }}">{{ thing.parent.parent.name }}</a> {% endif %} {% if thing.parent.link %} <a href="/y/{{ thing.parent.link }}">{{ thing.parent.name }}</a> {% endif %} The key thing that changes in this non-recursive code, is simply adding a .parent to the link/link text. I need to do this 20 times in total, as you can see, it's quite ugly to repeat and quite repetitive. Is there a more recursive and nicer way of doing it using django's template framework? -
How do I the value for a foreign key to show up in Django Rest
I want my output json to show the value of a the record that the foreign key is pointing to instead of the key instead. For example i want this to show up: [ { "id": 1, "brand": "ATL Motors", "package": "Full Page", "newspaper": "Gleaner", "cost": 22000, "objective": "Brand Awareness", "ad_date": "2016-10-01", "created_on": "2016-10-07T20:21:52Z" } ] Instead of this: [ { "id": 1, "brand": 2, "package": "Full Page", "newspaper": 1, "cost": 22000, "objective": "Brand Awareness", "ad_date": "2016-10-01", "created_on": "2016-10-07T20:21:52Z" } ] Here is my models.py file: from django.db import models from django.utils import timezone class Brand(models.Model): name = models.CharField(max_length=100) description = models.TextField() website = models.URLField() created_on = models.DateTimeField(default=timezone.now()) def __str__(self): return self.name class Newspaper(models.Model): name = models.CharField(max_length=200) created_on = models.DateTimeField(default=timezone.now()) def __str__(self): return self.name class PurchasedAd(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) package = models.CharField(max_length=350) newspaper = models.ForeignKey(Newspaper, on_delete=models.CASCADE) cost = models.IntegerField() objective = models.TextField() ad_date = models.DateField() created_on = models.DateTimeField(default=timezone.now()) def __str__(self): string = "{} - {}".format(self.brand, self.objective) return string Here is my serializer.py file: from rest_framework import serializers from . import models class BrandSerializer(serializers.ModelSerializer): class Meta: fields = ( 'id', 'name', 'description', 'website', 'created_on', ) model = models.Brand class PurchasedAdSerializer(serializers.ModelSerializer): class Meta: fields = ( 'id', 'brand', 'package', 'newspaper', 'cost', β¦ -
Custom Permissions on Django Rest Framework
Am building an API based on DRF 3.4.7 & Django 1.1.0.2. I've got to the point of giving user's access/permissions. The requirement is to have permissions based on roles and so far my understanding is that one can easily make use of Django's groups to represent roles. There also exists group permissions but those permissions to me are based on model objects which is a bit complicated. As such, I've set the permissions to be based on end-points i.e. URLs. By permissions based on points I mean that if you got e.g. student-address in urls.py, then a user is either allowed to create, read, update or delete an entry on this end-point. To achieve that I've gone ahead and created some classes as below: from django.contrib.auth.models import Group from core.models import BaseModel class Module(BaseModel): """ Model that stores the modules present in app """ title = models.CharField(max_length=100, unique=True) description = models.CharField(max_length=150, blank=True) def __str__(self): return '{}'.format(self.title) class ModuleEndPoint(BaseModel): """ Model that stores end-points available for each module """ module = models.ForeignKey(Module) title = models.CharField(max_length=100, unique=True) description = models.CharField(max_length=150, blank=True) class Meta: unique_together = (('module', 'title'),) def __str__(self): return '{} - {}'.format(self.module, self.title) class RolePermissions(BaseModel): """ Model that stores the permissions β¦ -
ImportError: cannot import name 'BookList'
This a relative import error that got me crazy. Here below is the directory tree and code: books βββ admin.py βββ apps.py βββ forms.py βββ __init__.py βββ models.py βββ tests.py βββ urls.py βββ views.py models.py from django.db import models from django.core.urlresolvers import reverse from . import views class BookList(models.Model): cover = models.ImageField(upload_to='cover/%Y/%m/%d') # cover = models.CharField(max_length=200, blank=False) title = models.CharField(max_length=100, blank=False) author = models.CharField(max_length=50) publisher = models.CharField(max_length=50) review = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse(views.detail_book, kwargs={'id': self.id}) views.py (The code crashed at the line below pdb.set_trace()) import pdb from django.views import generic from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse pdb.set_trace() from .models import BookList from .forms import BookListForm class BookRecommend(generic.ListView): model = BookList template_name = 'books/books_list.html' context_object_name = 'books' paginate_by = 1 def add_book(request): if request.method == 'POST': form = BookListForm(request.POST) if form.is_valid(): book = form.save() return HttpResponseRedirect(reverse(detail_book, kwargs={id: book.id})) else: form = BookListForm() return render(request, 'books/add_book.html', {'form': form}) def delete_book(request): pass def modify_book(request): pass def detail_book(request, id=1): book = get_object_or_404(BookList, id=id) return render(request, 'books/detail_book.html', {'book': book}) Trace back: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0xb621a2fc> Traceback (most recent call last): File "/home/michael/Envs/DJ19/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, β¦ -
how to make django server public in rasb
I use django server. first, I do port forwarding my raspberrypi ( my public ip : 12345) using my Sharer. so, I can access my raspberrypi server using x-shell(putty) and then i want to access my dajngo web server in my home i can access my django server (192.168.1.11:8000) but I can't access my django server except my home wifi-zone. I think i have to do port forwarding one more, but I'm not sure. then, what can i do? enter image description here -
Django Project parsing parameters in request
I have request to my django project from ExtJS application: GET /products/?page=1&start=0&limit=25&sort=%5B%7B%22property%22%3A%22id%22%2C%22direction%22%3A%22DESC%22%7D%5D At the request contains 4 parameters, one of which is a complex, which is called sort: Question: how to extract the values of the parameters property and direction using Python? I did so, but it does not work. I would be glad of any help. class ProductsList(generics.ListCreateAPIView): serializer_class = ProductsSerializer def get_queryset(self): queryset = Products.objects.all() sortParameter = self.request.query_params.get('sort', None) column_name=sortParameter['property'] queryset = queryset.order_by(column_name) return queryset If you know the best way to sort and filter the data on the server side for Django Rest projects, please share your ideas or references. -
Django What if I want to save data as the smallest type(like 1byte tinyint in mysql) with postgresql?
Good morning everyone(in Local time) I am working with Django in Starbucks. I faced one problem and I couldn't get idea to solve it. I am going to save data(integer type) which has range between 0~4. data is not bigger than 255 at most. When I read a manual of Django, there is SmallIntegerField which is 4 byte integer. Well, When I searched a manual of PostgreSQL, there was smallint type which is 2 byte. But actually, my data is just less then 1byte. So I wanted to use tinyint type which has range between 0 and 255.(When I used MySQL with php, I used tinyint) I feel like its wasting if i store that small data with 4byte intergertype. I want to show statue of something. for example, 0 is no toilet. 1 is toilet exist for handicapped people, 2 is toilet exist but not for handicapped people. If I need to have more than 3 options, I can't cover it with BooleanType. (I ran into article which says BooleanType in Django is Tinyint. I couldn't find explanation in Django manual(version 1.10) and I couldn't also find that PostgreSQL has tinyint type. How can I solve this problem? I β¦ -
Using forms with the Django outputs the token
I would really appreciate if you can give a hand with this. What I'm trying to do it's just to render the value of some text label, but it gives me the token. I'm learning django I hope you can comprehend. The result of this is: eee 12121 csrfmiddlewaretoken yYvl3neQZSP33vSRNto3FUFa88AMeFQi view. def test(request): if request.method == "POST": response = '' for key, value in request.POST.items(): response += '%s %s\n' % (key, value) return HttpResponse(response) return render(request, 'datos2.html') datos2. <form action="/test" method="post"> {% csrf_token %} <input type="text" name="eee"> <input type="submit"> </form> <p>ADD VALUE</p> <button onclick="myFunction()">ADD</button> <script> function myFunction() { var x = document.createElement("INPUT"); x.setAttribute("type", "text"); x.setAttribute("value", "0"); x.setAttribute("name", "eee"); document.body.appendChild(x); } </script> -
User UpdateView is not being populated with current user information
I am trying to provide a form to update the current user's information. There are two models: (1) User, which is a custom user model and (2) UserProfile. I made a model form using the get_user_model() method since I created a custom User model. My question is how do I set up my UpdateView so that my update form includes all the fields I specified in forms.py, with the current user's data automatically filled in the form fields? Also is there a way to add model attributes to the fields list that are related by a ForeignKey? My code is listed below. Thanks, Brian models.py from __future__ import unicode_literals from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin ) from django.db import models from django.db.models.signals import post_save from django.utils import timezone from django.conf import settings from django_countries.fields import CountryField from sorl.thumbnail import ImageField class UserManager(BaseUserManager): def create_user(self, first_name, last_name, email, username, display_name=None, password=None): if not first_name: raise ValueError("Please provide your first name.") if not last_name: raise ValueError("Please provide your last name.") if not email: raise ValueError("Users must have an email address.") if not display_name: display_name = first_name.capitalize() user = self.model( first_name=first_name, last_name=last_name, email=self.normalize_email(email), username=username, display_name=display_name ) user.set_password(password) user.save() return user def create_superuser(self, β¦ -
Can't query the sum of values using aggregators
I want to sum the values of all existing rows grouping by another field. Here's my model structure: class Answer(models.Model): person = models.ForeignKey(Person) points = models.PositiveIntegerField(default=100) correct = models.BooleanField(default=False) class Person(models.Model): # irrelevant model fields Sample dataset: Person | Points ------ | ------ 4 | 90 3 | 50 3 | 100 2 | 100 2 | 90 Here's my query: Answer.objects.values('person').filter(correct=True).annotate(points_person=Sum('points')) And the result (you can see that all the person values are separated): [{'person': 4, 'points_person': 90}, {'person': 3, 'points_person': 50}, {'person': 3, 'points_person': 100}, {'person': 2, 'points_person': 100}, {'person': 2, 'points_person': 90}] But what I want (sum of points by each person): [{'person': 4, 'points_person': 90}, {'person': 3, 'points_person': 150}, {'person': 2, 'points_person': 190}] Is there any way to achieve this using only queryset filtering? Thanks! -
No module named 'blogs.models.blogs.comments' django
I try separated file models on several different files I'm create directory models and inside this directory comments: this is my tree directories and files: blogs/ (this is myapp) - models/ -- __init__.py -- blogs.py -- blogs/ --- __init__.py --- comments.py this is __init__.py in models from blogs.models.blogs import * in blogs/ directory __init__.py from blogs.models.blogs.comments import * and blogs.py from django.db import models class Blogs(models.Model): title = models.CharField(max_length=200) description = models.TextField full_text = models.TextField tags = models.TextField comment_id = models.IntegerField(max_length=11) @classmethod def create(cls, title, description, full_text, tags, comment_id): blogs = cls( title=title, description=description, tags=tags, comment_id=comment_id, full_text=full_text ) return blogs in my comments.py from django.db import models from blogs.models.blogs import Blogs class Comments(models.Model): name = models.CharField(max_length=200) content = models.TextField blogs = models.ForeignKey(Blogs) @classmethod def create(cls,name,content,blogs): comments = cls( name=name,content=content,blogs=blogs ) return comments I try run command ./manage.py syncdb but recive this error and back trace: Traceback (most recent call last): File "../manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module β¦ -
Matching values in two tables and adding values to Foreign Key in Django
I have two models in Django app as follows: class EnActress(models.Model): name = models.CharField(max_length=100, null=True) match_name = models.ForeignKey('JpConvert', on_delete=models.CASCADE, null=True) def __str__(self): return self.name class JpConvert(models.Model): jpname = models.CharField(max_length=100, null=True) koname = models.CharField(max_length=100, null=True) name = models.CharField(max_length=100, null=True) def __str__(self): return self.koname Although the relationship is defined objects are not connected. ex) name : Kim, match_name_id : NULL so, I'm trying to adding objects. My plan is this. It's compare the two "name" fields and connect the data with the same value. ex) if EnActress.name : "kim" == JpConvert.name : "Kim" then add to Foreign Key But the struggle to create a function. Probably I'm wrong understanding. I wonder what to do to implement the function. I recommend even a little help and Tell me a supplementary explanation, if necessary. Sorry clumsy English!! -
Deleting a nested object
How do I delete a specific translation given the following serializer structure: from rest_framework import serializers from .models import Category, Translation class CategoryTranslationSerializer(serializers.ModelSerializer): class Meta: model = Translation fields = ('name', 'title', 'language') class CategorySerializer(serializers.ModelSerializer): translation_set = CategoryTranslationSerializer(many=True) class Meta: model = Category fields = ('id', 'order', 'parent', 'translation_set') -
Check for request.Get variable in django template when '?' is encoded
When the url is www.example.com/abc/?q=xyz, we get the value of q in the template by putting {{request.GET.q}}. It works fine normally but in my case, the browser is encoding '?' in url to '%3F' and now {{request.GET.q}} gives nothing. What is the solution. Also, the url shows '?' only but when i click on it the url bar encodes it. The problem is only in chrome. -
Django trans template tag unicode?
My question is why use Django trans tag to convert strings to unicode for internationalization? -
Django: Dynamic inline forms with filter upon user selection
I have created these models: class Service(models.Model): name = models.CharField(blank=False, max_length=200)code here class Monitor(models.Model): name = models.CharField(blank=False, max_length=100) services = models.ManyToManyField(Service, related_name='monitors') class Student(models.Model): name = models.CharField(blank=False, max_length=100) class ServiceMonitors(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) monitors = models.ManyToManyField(Monitor) These models represent a company that offer many services to students. Monitors that work for this company are assigned to students who need the service they offer. A monitor can offer many services and have many students for every one of them. Also, a student can have many services and monitors. Let's suppose the we have 3 services, s1, s2 and s3. When we create a new Monitor we assign him/her some of these services, let's say s1 and s3. Then, when we create a new Student, we should be able to choose which services and monitors the student will have. My problem here is that I need a form to create the student (name, phone, etc...) that allows me to: Select a service from a dropdown control Once a service is selected, the form must show the Monitors that offer that service, so I can choose one or more of them (checkboxes). A + button to create/show a β¦ -
Django Rest Framework queryset custom with group by and ordering
My Model: product = models.CharField(max_length=16, db_index=True) photo = models.URLField(default='') name = models.CharField(max_length=60, default='') last_date = models.DateTimeField(null=True, blank=True, default=None) I need to return in a queryset type(To not lose searching and pagination classes from drf) a result like that: product | name | photo | last_date | total --------------+---------------+-------------------- GZHN34 | tv | url.jpg | 20160530 | 27 GZHUN38 | car | car.jpg | 20160830 | 30 So, I need make a queryset grouping by product ordering by last date. Ideas?