Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django update() to swap values of two fields?
The following does not work: Car.objects.filters(<filter>).update(x=F('y'), y=F('x')) as both x and y ends up being the same value. I need to use update() instead of save() due to performance (large set of records). Are there any other way of doing an update like the one above to mimic Python's x, y = y, x? Thanks -
Django admin saves unicode wrong
Guys when I save something in unicode (for example something in armenian language like մեկ) in django admin it saves like this '???'. I'm using Django 1.9 and the database is Oracle 11gR2 with NLS_CHARACTERSET - WE8MSWIN1252 and NLS_NCHAR_CHARACTERSET - AL16UTF16. Inside DB I can store Unicode data and my table column is of nvarchar2 datatype. My Model is: class ChoiceFieldsParams(models.Model): param_desc = models.CharField(max_length=50,null=False,blank=False) class Meta: managed=True db_table='choice_field_params' def __str__(self): return self.param_desc In my admin i have the following. from __future__ import unicode_literals from django.contrib import admin from .models import ChoiceFieldsParams admin.site.register(ChoiceFieldsParams) Can anybody mention where the problem is? -
Django get context data across Views
I know that there are several generic views like ListView, DetailView, or simply View. The thing is can I actually get the context data that are declared in a BaseMixin's get_context_data() and use it in a View that doesn't have override get_context_data()? Example: class BaseMixin(object): def get_context_data(self, *args, **kwargs): context = super(BaseMixin, self).get_context_data(**kwargs) context['test'] = 1 return context And the view that extends this BaseMixin: class FooView(BaseMixin, View): def foo(self, request): context = super(BaseMixin, self).get_context_data(**kwargs) # do something return This is not working actually, even after put **kwargs as a parameter in foo(). The error is 'super' object has no attribute 'get_context_data'. So is there a way to get context data which was set in BaseMixin in FooView ? Thanks for your answers :) -
Translate python django web app in chinese
I made a python django web app which is using html,css,js as front end languages and python 2.7 as backend language. Now I have to translate the whole app from English to Chinese. I want to have it in both the languages. I have searched a lot and got to know about something called internationalization in python but unable to get how can I exactly integrate it in my app. It would be great if someone can help me with this. -
Python Django | view must be a callable or a list/tuple in the case of include()
File "\app\urls.py", line 10, in name='login'), File "\django\conf\urls__init__.py", line 85, in url raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). urls.py urlpatterns = [ # previous login view # url(r'^login/$', views.user_login, name='login'), # login / logout urls url(r'^login/$', 'django.contrib.auth.views.login', name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'), url(r'^logout-then-login/$', 'django.contrib.auth.views.logout_then_login', name='logout_then_login'), ] views.py from django.http import HttpResponse from django.shortcuts import render from django.contrib.auth import authenticate, login from .forms import LoginForm from django.contrib.auth.decorators import login_required def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['username'], password=cd['password']) if user is not None: if user.is_active: login(request, user) return HttpResponse('Authenticated successfully') else: return HttpResponse('Disabled account') else: return HttpResponse('Invalid login') else: form = LoginForm() return render(request, 'account/login.html', {'form': form}) @login_required def dashboard(request): return render(request, 'account/dashboard.html', {'section': 'dashboard'}) -
Django test with generated sql
How can i use generated .sql file to use in tests? So django should create test db then just import sql file. Is that possible? -
Gunicorn can't connect to socket error
I'm running my django app with gunicorn and ran into a weird issue. This command doesn't work - (venv)-bash-4.1$ gunicorn myapp.wsgi -b unix:/opt/myapp/var/run/app.sock [2016-09-15 06:04:12 +0000] [10100] [INFO] Starting gunicorn 19.4.5 [2016-09-15 06:04:12 +0000] [10100] [ERROR] Retrying in 1 second. [2016-09-15 06:04:13 +0000] [10100] [ERROR] Retrying in 1 second. [2016-09-15 06:04:14 +0000] [10100] [ERROR] Retrying in 1 second. [2016-09-15 06:04:15 +0000] [10100] [ERROR] Retrying in 1 second. [2016-09-15 06:04:16 +0000] [10100] [ERROR] Retrying in 1 second. [2016-09-15 06:04:17 +0000] [10100] [ERROR] Can't connect to /opt/myapp/var/run/app.sock This one works (venv)-bash-4.1$ gunicorn myapp.wsgi -b unix:/tmp/myapp.sock [2016-09-15 06:04:58 +0000] [10105] [INFO] Starting gunicorn 19.4.5 [2016-09-15 06:04:58 +0000] [10105] [INFO] Listening at: unix:/tmp/myapp.sock (10105) [2016-09-15 06:04:58 +0000] [10105] [INFO] Using worker: sync [2016-09-15 06:04:58 +0000] [10110] [INFO] Booting worker with pid: 10110 [2016-09-15 06:05:01 +0000] [10105] [INFO] Handling signal: int Provided, I have 777 permissions on /opt/myapp/var/run/ directory. The only difference is the location of socket file. -
Storing a base64 PDF in FileField
I have the following object that is passed to back end: filename: filename, filetype: filetype, filesize: calcB64FileSize(base64), base64: base64 Now, i need to somehow apply this to my FileField, however i am unable to find a way to do this. To solve the issue with images i used the following: image = Base64ImageField(allow_null=True) But i cant find a similar function for FileField. Here is how it is in my serializer: attachment = validated_data.get('attachment', instance.attachment) And this is my Model: attachment = models.FileField( upload_to='userexperience_attachments', null=True, blank=True) -
mysql connector for django 1.9
I updated from django 1.7 to django 1.9, created new project and app inside it. Now I want to connect with mysql for this app using mysql connector specifically(dont want to use mysqlDB or mysqlclient). I am using python3.4 for development. DATABASE settings in settings file looks like this - DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'NAME': 'mydb', 'USER': 'root', 'HOST': 'localhost', 'PASSWORD': '123456', } } I created a model - class Zipcode(models.Model): code = models.IntegerField(primary_key=True) city = models.CharField(max_length=40) state = models.CharField(max_length=40) country = models.CharField(max_length=20) But while migrating the database I am getting this error - mysql.connector.errors.DatabaseError: 1264: Out of range value for column 'applied' at row 1 During handling of the above exception, another exception occurred: django.db.utils.DatabaseError: Out of range value for column 'applied' at row 1 However this works properly with django 1.7 and 1.8. I know there are compatibility issues while connecting to mysql using mysql connector but I wanted to ask if someone has gone through this error and fixed it? Mysql version - 5.5 Connector version - 2.1.3 Thanks in advance -
How to do an OR on a Django ManyToManyField without getting duplicates?
I have the following two Django Classes MyClassA and MyClassB. MyClassB has a many-to-many field of MyClassAs from django.db import models class MyClassA(models.Model): name = models.CharField(max_length=50, null=False) def __str__(self): return "<%s %s>" % ( self.__class__.__name__, "; ".join(["ID: %s" % self.pk, "name: %s" % self.name, ])) class MyClassB(models.Model): name = models.CharField(max_length=50, null=False) my_class_as = models.ManyToManyField(MyClassA, related_name="MyClassB_my_class_as") def __str__(self): return "<%s %s>" % ( self.__class__.__name__, "; ".join(["ID: %s" % self.pk, "name: %s" % self.name, ])) Then I seed the database with the following data: >>> a = MyClassA.objects.create(name="A") >>> b = MyClassA.objects.create(name="B") >>> c = MyClassA.objects.create(name="C") >>> d = MyClassA.objects.create(name="D") >>> e = MyClassA.objects.create(name="E") >>> u = MyClassB.objects.create(name="U") >>> u.my_class_as.add(c) >>> u.my_class_as.add(d) >>> u.save() I want to find the (unique) list of MyClassBs that have a relationship with a instance c or d of MyClassA. How can I do it?? My solution was to create the following static method on MyClassB: @staticmethod def is_m2m_related_queryset(my_class_a_list): q = Q() for curr_a in my_class_a_list: q |= Q(my_class_as=curr_a) return q ...And then run the following query: >>> MyClassB.objects.filter(MyClassB.is_m2m_related_queryset([c, d])) [<MyClassB: <MyClassB ID: 11; name: U>>, <MyClassB: <MyClassB ID: 11; name: U>>] But wait! Instead of returning to me a singleton list containing the u object as … -
Django 1.10 MySQL INSERT IGNORE on Duplicate
I'm using Django 1.10 and have some large CSVs that will often have duplicates that just need to be ignored. I was thinking the solution might be to use INSERT IGNORE instead of just regular insert, but I'm unsure of how to do this. I think I can create a custom manager, but from there I can't figure it out. It's even possible that this is the "wrong" way to do this, so I'm open to moving in better direcctions as well. Any help would be appreciated. -
Django aggregate by split string
I would like to aggregate by a substring of one of my fields. models.py class SomeModel(models.Model): symbol = models.CharField(db_column='SYMBOL', max_length=16) number = models.IntegerField(db_column='NUMBER') Where symbol will be something like; 'symbol': 'foo.bar', 'number':5 'symbol': 'foo.foo', 'number':10 'symbol': 'some.water', 'number':1 'symbol': 'some.milk', 'number':1 What I would like is to aggregate by; symbol.split('.')[0] With the end result being something like; 'symbol': 'foo', 'number': 15 'symbol': 'some', 'number': 2 I've looked at the annotate and aggregate documentation but I am struggling with this. Thanks. -
How to construct Django Queryset that does OR on many-to-many field?
I have the following two Django Classes MyClassA and MyClassB. MyClassA is an MPTTModel. MyClassB has a many-to-many field of MyClassAs from mptt.models import MPTTModel, TreeForeignKey from django.db import models class MyClassA(MPTTModel): parent = TreeForeignKey('self', null=True, related_name="MyClassA_parent", ) name = models.CharField(max_length=50, null=False) @property def descendants(self): return set(list(self.get_descendants()) + [self]) def __str__(self): return "<%s %s>" % ( self.__class__.__name__, "; ".join(["ID: %s" % self.pk, "parent: %s" % self.parent, "name: %s" % self.name, ])) class MyClassB(models.Model): name = models.CharField(max_length=50, null=False) my_class_as = models.ManyToManyField(MyClassA, related_name="MyClassB_my_class_as") def __str__(self): return "<%s %s>" % ( self.__class__.__name__, "; ".join(["ID: %s" % self.pk, "name: %s" % self.name, ])) Then I seed the database with the following data: >>> a = MyClassA.objects.create(name="A", parent=None) >>> b = MyClassA.objects.create(name="B", parent=a) >>> c = MyClassA.objects.create(name="C", parent=b) >>> d = MyClassA.objects.create(name="D", parent=b) >>> e = MyClassA.objects.create(name="E", parent=a) >>> u = MyClassB.objects.create(name="U") >>> u.my_class_as.add(c) >>> u.my_class_as.add(d) >>> u.save() I want to find the (unique) list of MyClassBs that have a relationship with an instance m of MyClassA where m is a or a descendant of a. How can I do it?? My solution was to create the following static method on MyClassB: from django.db.models import Q @staticmethod def is_descendant_of_MyClassA_queryset(my_class_a): q = Q() for curr_descendant in … -
Django override model subclass create method
I'm looking for right ways to override the create() method of a subclass. Basically I'm doing this: class Base(models.Model): field1_base = models.IntegerField() def __init__(self, field1_base): # LOGICS self.field1_base = field1_base class A(Base): field2_sub = models.IntegerField() def __init__(self, field2_sub, field1_base): # LOGICS self.field2_sub = field2_sub super(A, self).__init__(field1_base) A(field2_sub=1, field1_base=2) However we can't override the __init__() method of a model. I just want to leave some fields to be assigned in base class's methods. Is there a proper way to do this using create() method? -
Postgres, Django, Apache, and virutalenv user permissions
I recently made some changes to a stable environment of postgres, django, apache, and virutalenv on a production server. Now, when I try migrate db changes after a git pull, postgres doesn't let me migrate all the tables and complains of a permissions issue. Beyond the postgres user, I really only have two others: user1 and dbuser. I invoke the virtual env from within user1 and start Apache from within that virtualenv. Virtualenv initializes values for DB_USER and DB_PASS (for dbuser), which are then passed to Django and used for connecting to the Postgres database. Here's the issue: To properly migrate the updates, I have to go into psql, connect to the db and run REASSIGN OWNED BY user1 TO dbuser to allow me to migrate the updates (so-link). I then have to reassign the tables in the db back the other way: REASSIGN OWNED BY dbuser TO user1. If I don't reassign back to user, Django/Apache can't access the tables in db to properly run the server. The one change I can think of that might have caused this (or, the opposite, been necessary due to the underlying permissions problem) was a change to table permissions grants I made … -
Sub-Classed View with Form Not Returning Form Data
I have a situation that I don't understand. I have a sub-class that has a form that is not returning data from request.POST. The super-class also has a form and this IS returning data from request.POST. I've put in a few print() to terminal commands to look at what is coming back (or not coming back) to verify this. The sub-class view code looks like this: class MainView(SidebarBaseView): main_form_class = MainViewForm template_name = 'myapp/my_view.html' def get(self, request, *args, **kwargs): context = super(MainView, self).get(request, *args, **kwargs) context.update(self.get_context_data(*args, **kwargs)) main_form_initial = {} for detail in context['my_data']: # my_data comes from get_context_data() field_name = detail.datatype.name main_form_initial[field_name] = detail.note main_form = self.main_form_class(initial=main_form_initial) context['main_form'] = main_form return render(request, self.template_name, context) def post(self, request, *args, **kwargs): context = super(MainView, self).post(request, *args, **kwargs) context.update(self.get_context_data(*args, **kwargs)) main_form = self.main_form_class(request.POST) print('\n','main_form',main_form,'\n') #to terminal if main_form.is_valid(): main_form_data = main_form.cleaned_data print('\n', 'cleaned data', main_form_data, '\n') #to terminal for detail in context['my_data']: field_name = detail.datatype.name detail.note = main_form_data[field_name] detail.save() main_form_initial = {} for detail in context['my_data']: field_name = detail.datatype.name main_form_initial[field_name] = detail.note main_form = self.main_form_class(initial=main_form_initial) context['main_form'] = main_form return render(request, self.template_name, context) def get_context_data(self, *args, **kwargs): context = super(CompanyStatsView, self).get_context_data(**kwargs) ... return context My form make dynamic fields since I need to … -
How to create a DRY Django models class template with ForeignKey?
There are multiple places in my code where I use this snippet: class PlaceObject(models.Model): modified = models.DateTimeField(auto_now=True) place = models.ForeignKey('Place', models.CASCADE, 'objects') object = models.ForeignKey('storage.S3Object', models.CASCADE, 'places') order = models.SmallIntegerField() I thought I might try to dry this up a little. However, I don't know what to put in the first parameter of models.ForeignKey, should I just leave it empty? Is it even worth creating a template Class for a model this small? class ModelObject(models.Model): modified = models.DateTimeField(auto_now=True) model = models.ForeignKey(on_delete=models.CASCADE) object = models.ForeignKey(on_delete=models.CASCADE) order = models.SmallIntegerField() -
Django : Booking complex Slot booking system
I have a simple slot booking system in my current project. I will be configuring 3 times per day and all the AVAILABLE slots should be displayed in the UI where a user can select the time slot like: Date1: radio button Time1 radio button Time2 radio button Time3 Date2 radio button Time1 radio button Time2 radio button Time3 Date3 radio button Time1 radio button Time2 radio button Time3 Or something like below where in the date is selected and the ONLY available time slots are available. Date1: Time1 Time2 Time3 Date2 Time1 Time2 Time3 .....so on There should be a radio button against each and every time slot. P.S : I am planning to show some time slots to free users and more slots to paid users. Here is the model I have written class TimeSlot(models.Model): plan_code_choices=( ('F','Free'), ('S','Standard'), ('A','Advanced'), ('P','Premium') ) plan_code = models.CharField(max_length=1,choices=plan_code_choices,default=plan_code_choices[0][0]) date_slot = models.DateField() # slot_id =models.IntegerField(choices=slot_id_choices) time1=models.TimeField() time1_isbooked = models.BooleanField(default=False,blank=True) time2=models.TimeField() time2_isbooked = models.BooleanField(default=False,blank=True) time3=models.TimeField() time3_isbooked = models.BooleanField(default=False,blank = True) def __str__(self): return "{0}-{1}-{2}".format(self.plan_code,self.time1,self.time2) I am clueless as in how to project it in my view and make it actionable in HTML. -
How can I access django allauth custom filed
I'd like to save and access custom field of allauth. After I save the form and try to access the data but it's empty. {{ user.school }} I only add forms.py. Do I need to add on models.py too? forms.py from django.contrib.auth import get_user_model from django import forms SCHOOL = ( ('', 'Select your school...'), ('ucla.edu', 'UCLA'), ('berkeley.edu', 'Berkeley'), ) class SignupForm(forms.Form): school = forms.ChoiceField(choices=SCHOOL, required=True) def signup(self, request, user): user.school = self.cleaned_data['school'] user.save() Thanks in advance! -
Comparing dates in template Django
I have two dates in a template that I need to compare in an if statement. Date1 is from the created field of a data element {{ endjob.created|date:"Y-m-d" }} that is displayed as 2016-09-12 Date2 if from an array {{ pay_period.periods.0.0 }} that is displayed as 2016-09-04 Therefore I am trying to ask to display information only if Date1 >= Date2 but I do not get any data. Can you help me with how to clash dates in templates in Django This is my code: <tbody> {% for endjob in endjob %} {% if endjob.created|date:"Y-m-d" >= pay_period.periods.0.0 %} <tr> <td><a href="{{ endjob.get_absolute_url }}" title="Goto Form">{{ endjob.event.name }}</a><br /></td> <td>{{ endjob.event.job_no}} <br /></td> <td>{{ endjob.event.job_type}} <br /></td> <td>{{ endjob.code }} <br /></td> <td>{{ endjob.crewid }}<br /></td> <td>{{ endjob.workers }}<br /></td> <td>{{ endjob.created|user_tz:user|date:"M j, Y" }}<br /></td> </tr> {% endif %} {% endfor %} -
Django Complex lookups with Q objects with same keywords in a m2m reletionship
I'm trying to find out if it's possible to use Q objects to query the database for M2M relationships. Let's say I have the following models: class Movie(models.Model): name = models.CharField(max_length=50, unique=True) rating = models.CharField(max_length=50, unique=True) class Actor(models.Model): name = models.CharField(max_length=50, unique=True) movies = models.ManyToManyField(Band, null=True, blank=True) So I have two movies: 'Mr & Mr smith'(Actors: Angelina Jolie, Brad Pitt, rating:5) and 'Fight Club' (Actors: Brad Pitt, Ed Norton rating:5) When I'm trying to filter by the native fields: a = Movies.objects.filter(Q(name_icontains="i") &Q(name_icontains="t") )) It works as expected(Outputs both movies) but when I try the same with a m2m relationship: a = Movies.objects.filter(Q(actors__name_icontains="pitt") & Q(actors__name_icontains="jolie"))) I get an empty set. Also if I use OR instead of AND it only returns values matching the first Q object ('pitt' in this example). Am I doing something wrong?If so, How can I query dynamically for movies which have both 'pitt' and 'jolie' in their cast? -
Using ModelAdmin subsclass in my application
I have added filtering, sorting, and searching to a ModelAdmin class named AlbumAdmin(admin.ModelAdmin). It works fantastic in the Django Admin application but I would like to display the change_list and add Albums in my application using AlbumAdmin. I cannot find any information or an example on how to do this. Any help is appreciated. -
how to structure API correctly Django 1.10: "CommandError: 'orders' conflicts with the name of an existing Python module.."
I have a structure in a Django project like myproject/api myproject/orders where api and orders folders are apps, with init, views.py, etc... I want to have these structured apps like orders, but I also want to have the API urls like my_url/api/orders, with also having my_url/orders/your_orders/user_id/6, and so on. How can I structure a django project to allow both the API and top-level apps (myproject/app) to coexist? Right now I get this error: $ ls api myproject db.sqlite3 manage.py orders requirements.txt $ cd api $ ../manage.py startapp orders CommandError: 'orders' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name. I don't care if I actually have apps named order and so on in the api folder, I just want the URL my_url/api/order. Thank you -
Regex interpretaion in Django tutorial
despite being familiar with the basics of regex, the tutorial for Django 1.10 does not go into much detail about how some regex generates dynamic links. I am looking at this specific snippet under the polls/urls.py: url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), Could someone go into detail about how that regex is interpreted? The quantifiers at the start of the capture group, (?P<question_id> do not make sense to me. Specifically, how does Django know that <question_id> is a foreign key? -
Django form with ModelChoiceField is always invalid
Below is the relevant part of my template. I'm trying to send the selected field from a dropdown to my form. <form action="character_chat" method="post"> <select id="character_name"> {% for character in characters %} <option name={{character}}>{{character}}</option> {% endfor %} </select> <input type="submit" value="Select"> </form> Relevant code from the view: def character_chat(request): class CharacterForm(forms.Form): character_name = forms.ModelChoiceField(queryset=Character.objects.all()) if request.method == 'POST': form = CharacterForm(request.POST) if form.is_valid(): print(form.cleaned_data['character_name'])