Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having issues with optimizing query on foreign key
I have tried different ways of querying my data, but still results in a large amount of pings to the DB. I have tried using select_related. Here are my models: class Order(models.Model): num = models.CharField(max_length=50, unique=True) class OrderInfo(models.Model): info = models.CharField(max_length=100, unique=True) datetime = models.DateTimeField(auto_now_add=True, blank=True) order_fk = models.ForeignKey(Order) What I am trying to achieve: OrderInfo has a bunch of information pertaining to the Order. What I want is to be able to get the most recent OrderInfo from the DB, but I want it unique to Order. The unique part is where I am struggling to minimize my query amount. ois = OrderInfo.objects.order_by('-datetime').select_related('order_fk') When I try to filter it is doing a query on each Order to check for uniqueness the queries ramp up. For instances: _ = [oi.order_fk for oi in ois] # queries reach to 20k, takes to long. Anyone, know a proper approach to minimize these queries or possibly I may need to restructure my models. Notes: Django 1.7 Python 2.7 SQLite -
Django FilePathField Does not work
If I use Django's FilePathField in a model such as below, class MyModel(models.Model): fileName = models.FilePathField(path='static/myfiles/') It enables me to get the choices and assign a fileName to a record/row in the table using admin site. But displaying field fileName in the Template only shows the path and not the file? -
Django form. How hidden colon from initial_text?
I'm try do this: class NoClearableFileInput(ClearableFileInput): initial_text = '' input_text = '' class ImageUploadForm(forms.ModelForm): title = forms.CharField(label="TITLE", required=False,widget=forms.TextInput(attrs={'placeholder': 'name'}), label_suffix="") image = forms.ImageField(label='NEW FILE',widget=NoClearableFileInput, label_suffix="") class Meta: model = Image fields = ('title','image') There in class NoClearableFileInput cleaned value initial_text. In fields 'title' and 'image' use label_suffix, but from initial_text symbol ":" remained. result How get rid of them? -
Select reverse Foreign Key in ModelChoicefield
I have an order form where the user can choose one item and select a quantity. The price depends on how much is ordered. For example, each item is $10 if you order <100, but $7 if you order 100-200. In the template, I want to display the pricing information underneath the form for each choice. These are my Models: class Product(models.Model): name = models.TextField() class Price(models.Model): """ This lets us define rules such as: When ordering <100 items, the price is $10 When ordering 100-200 items, the price is $7 When ordering 200-300 items, the price is $5 etc """ price = models.FloatField() min_quantity = models.PositiveIntegerField() max_quantity = models.PositiveIntegerField() product = models.ForeignKey(Product) class Order(models.Model): product = models.ForeignKey(Product, null=False, blank=False, default='') quantity = models.IntegerField() I can loop over the form fields and the queryset independently: {% for choice in form.product.field.queryset %} <h1>{{choice}} {{choice.price_set.all}}</h1> {% endfor %} {% for choice in form.product %} <h1>{{ choice.tag }} {{ choice.choice_label }}</h1> {% endfor %} ... but I don't know how to combine the loops to display the prices underneath the form fields. Essentially, I want to select a reverse foreign key from a ModelChoicefield widget. I either need to loop over both the … -
python djaango-rest-framework 3.3.3 update nested serializer
Using django-rest framework 3.3.3 I am trying to update existing data in my database using the django-rest framework, following a previously posted solution :django-rest-framework 3.0 create or update in nested serializer I'm fairly new to django in general, and the rest framework. Given the following models: class Clinic(models.Model): name = models.TextField() streetNumber = models.IntegerField() unitNumber = models.CharField(max_length=10, blank=True, null=True) streetName = models.CharField(max_length=50) city = models.CharField(max_length=50) province = models.CharField(max_length=3) country = models.CharField(max_length=30) postalCode = models.CharField(max_length=6) phone = models.CharField(max_length=10) def __str__(self): return self.name class Time (models.Model): clinic = models.ForeignKey(Clinic, related_name='times') appointmentTime = models.CharField(max_length=100) def __str__(self): return self.appointmentTime And the following serializers: class TimeSerializer(serializers.ModelSerializer): class Meta: model = Time fields = ('appointmentTime',) class ClinicSerializer(serializers.ModelSerializer): times = TimeSerializer(many=True) class Meta: model = Clinic fields = '__all__' def update(self, instance, validated_data): instance.name = validated_data['name'] instance.streetName = validated_data['streetName'] instance.unitNumber = validated_data['unitNumber'] instance.city = validated_data['city'] instance.province = validated_data['province'] instance.country = validated_data['country'] instance.postalCode = validated_data['postalCode'] instance.phone = validated_data['phone'] #print(instance) instance.save() times_data = [item['id'] for item in validated_data['times']] print(times_data) for time in instance.clinics: if time.id not in times_data: time.delete() for item in validated_data['times']: time = Time(id=item['id'], clinic=instance, appointmentTime=item['appointmentTime']) time.save() return instance And the following view: class ClinicList(APIView): def get(self,request): clinics = Clinic.objects.all() serializer = ClinicSerializer(clinics, many=True) return Response({'results': serializer.data}) … -
Building JSON object that can hold contents of file
I have to save contents of a python file to my database. I am writing fixtures so that I can load that to my database from Django project. I have no idea where to begin with. The size is an issue that I need to address for my JSON object. -
Connect social account using python social auth for Oauth2
I am using Signup by OAuth access_token along with django-oauth-toolkit for OAuth2 authentication. Here is the code - from django.contrib.auth import login from social.apps.django_app.utils import psa # Define an URL entry to point to this view, call it passing the # access_token parameter like ?access_token=<token>. The URL entry must # contain the backend, like this: # # url(r'^register-by-token/(?P<backend>[^/]+)/$', # 'register_by_access_token') @psa('social:complete') def register_by_access_token(request, backend): # This view expects an access_token GET parameter, if it's needed, # request.backend and request.strategy will be loaded with the current # backend and strategy. token = request.GET.get('access_token') user = request.backend.do_auth(request.GET.get('access_token')) if user: login(request, user) return 'OK' else: return 'ERROR' I used 'associate_user' pipeline to connect multiple backend with Session auth. How can I use the same pipeline to connect multiple backend using OAuth2 ? I tried connecting two backends, but it logs out the user when I sign in using other backend. Here is the link to the issue on github. -
Can't see Provider inside djangoallauth add social application
I'm a little confused about can't see and add provider inside allauth add social application. . I'm using django=1.8.11 and python=3.4.3, I'm not using anything special, just trying to configure social auth first, and move on so how can I overcome this? -
django compressor key is missing
I'm upgrading a lot of packages in my server and i have a problem in upgrading django compressor. my configurations: USER_NAME = '' AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' AWS_STORAGE_BUCKET_NAME = '' COMPRESS_DEBUG_TOGGLE = DEBUG COMPRESS_ENABLED = True COMPRESS_PRECOMPILERS = () COMPRESS_URL = "https://example.com/path" COMPRESS_STORAGE = 'storages.backends.s3boto.S3BotoStorage' STATICFILES_STORAGE = COMPRESS_STORAGE COMPRESS_CSS_HASHING_METHOD = 'content' COMPRESS_PARSER = 'compressor.parser.AutoSelectParser' COMPRESS_CSS_FILTERS = [ 'compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.cssmin.CSSMinFilter' ] COMPRESS_OFFLINE = True COMPRESS_OFFLINE_CONTEXT = {'STATIC_URL': STATIC_URL} COMPRESS_ROOT = STATIC_ROOT The error i'm getting: OfflineGenerationError('You have offline compression enabled but key "d43989e1dd29dfbfb6da97cf4cacec30" is missing from offline manifest. You may need to run "python manage.py compress') The weird thing is when i checked, all the files are uploaded to S3 and in the compressor manifest everything looks good (but with different keys). my django version is 1.10 and the compressor version is 2.1 after i upgraded from 1.5. also, my configuration worked before so i know that is not a templates problem. Thanks! -
Reverse for 'edit' with arguments '(9,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I'm getting an error when trying to access edit link in django, i have looked here on stack overflow but i haven't found the solution that works in my case. ERROR : Exception Type : NoReverseMatch Exception Value : Reverse for 'edit' with arguments '(9,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] arguments '{}' not found. 0 pattern(s) tried: [] this is my urls.py from django.conf.urls import url, include from django.contrib import admin from posts import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^create/$', views.create, name='create'), url(r'^(?P<id>\d+)/$', views.show_post, name = 'show_post'), url(r'^(?P<id>\d+)/edit/$', views.update_post, name = 'update_post'), url(r'^(?P<id>\d+)/delete/$', views.delete_post), ] views.py from django.contrib import messages from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse, HttpResponseRedirect from .forms import PostForm from .models import Post # Create your views here. def index(request): post_list = Post.objects.order_by('-created_date')[:10] context = {'post_list': post_list} return render(request, 'index.html', context) def create(request): form = PostForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.save() #flass messages messages.success(request, "Successfully created") return HttpResponseRedirect(instance.get_absolute_url()) context = { "form":form, } return render(request, 'post_form.html', context) def show_post(request, id=None): instance = get_object_or_404(Post, id=id) context = {'instance': instance} return render(request, 'show_post.html', context) def update_post(request, id=None): instance = get_object_or_404(Post, id=id) form = PostForm(request.POST or None, … -
How to send additional attribute to assigned method?
I found in internet such solution as: def is_owner(self): if self.request.user.profile_url == self.kwargs['profile_url']: return True else: raise PermissionDenied class CompanyProfileUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = CompanyProfile template_name = 'profiles/create.html' fields = team_fields test_func = is_owner Could anyone tell me, how to send additional value to the method? I want to have something like: def is_owner(self, profile_type): if profile_type == 'user': if self.request.user.profile_url == self.kwargs['profile_url']: return True else: raise PermissionDenied else: # some code test_func = is_owner('user') obviously is not working because there is no self -
Django 1.9 check if email already exists
My site is set up so there is no username (or rather user.username = user.email). Django has an error message if a user tries to input a username that is already in the database, however since I'm not using a username for registration I can't figure out how to do this. Just like the default settings already is, I don't want to reload the page to find out if there is an email address already associated with a user. My guess is to use Ajax, but I can't figure out how to do it. Ive looked at other posts, but there doesn't seem to be anything recent. How can I check to see if an email address already exists, and if so, give an error message for the user to input a new email address? -
How to print query result in python/django
I came from CakePHP and just started playing with Django framework. In CakePHP, I have the habit of printing out all the returned array using pr() straight out to the webpage. For example: A controller spits out a $result to a View, I use pr($result) and it will print out everything right on the webpage so I know how to travel through $result from my View. A form POST a $request to a Controller, I use pr($request) to see what is sending in before processing it in the Controller. The content of $request will be displayed immediately on the webpage right after I hit Submit the form. I'm wondering if I could do the same thing in django instead of going to the shell and try pprint (or could I just use pprint to print out to the web???) This is a really simple example about what I'm talking about: app_name/views.py: def detail(request, soc_id): soc = get_object_or_404(Soc, pk=soc_id) return render(request, 'socs/detail.html', {'soc': soc}) How can I just view clearly what is in "soc". In cakephp, I could just pr($soc) right there and it will be displayed right on the detail.html page. I have tried this and it didn't work (I'm … -
Django settings.py not updating
I have enabled the setting: USE_X_FORWARDED_HOST = True in my settings.py. I am currently deploying the server, but when I try to render my index page it gives me a 404. The email says that it is a: Invalid HTTP_HOST header: u'127.0.0.1:9001 And BEFORE ANYONE SAYS THAT I NEED TO ADD IT TO MY ALLOWED_HOSTS, I already have, so please spare me with from that advice. I also received an email with the debug error. When I looked through the debug info, it had a list of my settings and it stated that: USE_X_FORWARDED_HOST = False Another field that is not being updated is my ALLOWED_HOSTS. I tried restarting apache2, touching wsgi.py, and deleting *.pyc in the main app directory that contains settings.pyc. However, none of this has worked. Some background on my deployment. I have my django behind a proxy because I am using django channels with an apache2 webserver serving as the proxy. I also have daphne running behind it which receives the requests and services them. -
Django adding spaces and quotation marks when pushing string to template
I've tried to build a table in the view and push it out to the template for that view, because doing it in the template isn't proving to be feasible. I can generate a string that has the correct information in it, but when that template variable is evaluated in the browser, there are extra quotation marks and spaces that seem to keep the table from being correctly produced. Here is the code from the view: for unique_activity in uniquelist: currentrow = '<tr data-activityID="' + str(unique_activity[0])+ '">' + '<td>' + str(unique_activity[1]) + '</td>' for visit in visits_list: for activity in visit.activity_set.all(): if activity.id == unique_activity[0]: currentrow = currentrow + '<td>' + 'Reps:'+ str(activity.Repetitions) + '</td>' else: noact = True if noact == True: currentrow = currentrow + '<td></td>' currentrow = currentrow + '</tr>\n' tablerows.append(currentrow) table = '<table>' for row in tablerows: table = table + row table = table + '</table>' table = str(table) The output is what it needs to be.. an example <table><tr data-activityID="1"><td>Initial Evaluation</td><td>Reps:None</td><td></td><td></td></tr> <tr data-activityID="3"><td>Cold Pack</td><td></td><td>Reps:None</td><td></td></tr> <tr data-activityID="6"><td>Recumbent Exercise Bike</td><td>Reps:12</td><td></td><td></td></tr> <tr data-activityID="7"><td>Leg Press</td><td></td><td></td></tr> <tr data-activityID="8"><td>Shoulder Ladder</td><td></td><td></td></tr> </table> However, this is what shows up in the DOM, all that I output to the template is simply {{ … -
Django custom lazy object
I have an Enum: from django.utils.translation import ugettext_lazy as _ class Case(enum.Enum): sg1 = _("1. Case Sg.") sg2 = _("2. Case Sg.") ... sg6 = _("6. Case Sg.") pl1 = _("1. Case Pl.") ... ... which is a very pragmatic approach to it... I would like to do it a little bit smoother: My idea is to use a format "%(c)s. Case %(n)s". The problem is that Case.sg1.value must return a lazy object. So for example this would not work: class Case(enum.Enum): sg1, sg2, sg3, sg4, sg5, sg6, \ pl1, pl2, pl3, pl4, pl5, pl6 = [ _("%(c)s. Case %(n)s") % {"c": c, "n": n} for n in [_("Sg."), _("Pl.")] for c in range(1, 7) ] print(type(Case.sg1.value)) # it is a string, not a lazy object Another approach is using django.utils.functional.lazy directly: fmt =_("%(c)s. Case %(n)s") def trans(c, n): return fmt % {"c": c, "n": n} class Case(enum.Enum): sg1, sg2, sg3, sg4, sg5, sg6, \ pl1, pl2, pl3, pl4, pl5, pl6 = [ lazy(trans) for n in [_("Sg."), _("Pl.")] for c in range(1, 7) ] This does not work, because arguments c and n are missing. I would like to be able to give args or kwargs to lazy() so … -
Use models foreign key _id column as field in django form
When you create a ForeignKey in a django model django also creates a _id column in the database. I'm trying to figure out how to display this value in a django form but can't seem to get it to work. With what I have below the category_id field appears in the for but the value itself doesn't? marketplace/models.py class Category(models.Model): category = models.CharField(null=True) category_code = models.IntegerField(unique=True) store/models.py class Product(models.Model): created = models.DateTimeField(default=now) name = models.CharField(max_length=200, unique=True) category = models.ForeignKey('marketplace.Category', blank=True, null=True, to_field='category_code') store/forms.py class Form(forms.ModelForm): def __init__(self, *args, **kwargs): super(Form, self).__init__(*args, **kwargs) self.fields['category_id'] = self.instance.category_id class Meta: model = OLModel fields = ['name', 'created'] -
Django memcache expire url
from django.core.cache import cache from django.http import HttpRequest from django.utils.cache import get_cache_key def expire_page(path): request = HttpRequest() request.path = path key = get_cache_key(request) if cache.has_key(key): cache.delete(key) Using memcached in django to clear a url from cache.The request seems cached.get_cache_key doesn't return the key. Settings: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } Thanks in advance. -
How to acccess associated files in Django FilePathField
If I use Django's FilePathField in a model of building such as below, class Building(models.Model): name = models.CharField(max_length=32) image = models.FilePathField(path='static/image/') It enable me to get image choices to associate with a building in the admin site. But how to I get the actual filename (with the path) that is associated with the building name when the image field which is a FilepathField only returns the path? -
Django password value showing up as plaintext despite forms.PasswordInput declaration
forms.py from django.contrib.auth.models import User class LoginForm(forms.ModelForm): # specify password type so that passwords show up as *******, not plaintext password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ["username", "password"] def __init__(self, *args, **kwargs): # first call the 'real' __init__() super(LoginForm, self).__init__(*args, **kwargs) # then do extra stuff: self.fields['username'].help_text = '' self.fields['password'].widget = forms.TextInput(attrs={'placeholder': ''}) self.fields['password'].widget.attrs['class'] = 'form-control' So interestingly, when I surface this form in a template, the password value shows up as plaintext instead of '******' text. But only if I add the 'placeholder': '' line. I inspected the form element and figured out that when I added the 'placeholder': '' line, type='password' was being changed to type='text' in the <input type='???'></input>element in the rendered HTML. --> How do I keep this from happening, so passwords continue to show up as plaintext, without removing my 'placeholder': '' line? -
Why does django 1.9 keeps using python2.7 when my virtualenv have python3.5?
Im having problems with python versions, im actually developing a web page with python3.5 under Windows 7. But in my server (CentOS 7) i created a virtualenv with python3.5 (because the default version of python in linux is 2.7). The problem is that when i get an error, it says that django is using python2.7: Request Method: GET Request URL: http://proyect/url/ Django Version: 1.9.8 Exception Type: UnicodeEncodeError Exception Value: 'ascii' codec can't encode character u'\xed' in position 9: ordinal not in range(128) Exception Location: /usr/lib/python2.7/site-packages/django/utils/encoding.py in force_text, line 80 Python Executable: /usr/bin/python Python Version: 2.7.5 Python Path: ['/home/user/proyect', '/home/user/proyect_env/lib/python3.5/site-packages', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib64/python2.7/site-packages/gtk-2.0', '/usr/lib/python2.7/site-packages'] I'm almost 100% sure that this message is displayed because django is using a wrong python version. In my django.conf inside /etc/httpd/conf.d/ i have this configured: WSGIDaemonProcess proyect python-path=/home/user/proyect:/home/user/proyect_env/lib/python3.5/site-packages WSGIProcessGroup project WSGIScriptAlias / /home/user/proyect/proyect/wsgi.py I followed this tutorial to configure my server. -
Django run a function after specified delay
I am new to Django. On receiving a request I have to execute a function after "3minutes of time". But the request should immediately return and the effect of function execution will be seen later after it completes the execution. I am confused on how can I do this in Django. Any help is appreciated! -
One test in Django test suite passes locally but fails on Travis CI server
I have the following view in my views.py: def submit_video_link(request, spot_id): link = request.POST.get('video_link') if link: spot = Spot.objects.get(id=spot_id) email_message = ''' Video to be featured on page for %s:\n %s ''' % (spot.name, link) send_mail( 'user featured video submission', email_message, 'email.address@gmail.com', ['email.address@gmail.com'], fail_silently=False, ) return HttpResponseRedirect(reverse('spot_detail', args=(spot_id,))) I also have the following test of that view: class VideoLinkSubmitTest(TestCase): def test_mail_sent(self): spot = Spot.objects.create(name='Test Spot') fake_link = 'http://youtube.com/fakevideolink' url = '/spots/details/%d/submitlink/' % spot.id with patch('django.core.mail.send_mail') as mocked_send_mail: self.client.post(url) self.assertFalse(mocked_send_mail.called) self.client.post( url, {'video_link': fake_link} ) self.assertTrue(mocked_send_mail.called) ... On my local machine, this test passes. However, when run on the Travis CI server it fails, on the final assertion: self.assertTrue(mocked_send_mail.called) because mocked_send_mail.called returns False. What would cause this test to pass locally, but fail on the Travis CI server? All other tests in a large test suite pass both locally and on the CI server. Django versions are the same in both places. -
Run multiple Django application tests with one command
I have a Django project with multiple apps, app_1, app_2, and app_3. Currently, in order to run the test suite, I use the standard testing command: python manage.py test. This runs the tests for all of my apps. I am also able to run tests for a single app, specifically -- for example, python manage.py test app_1/. However, I'd like to be able to run all of the tests in some, but not all, of my apps. For example, I'd run python manage.py test main_tests and just have the tests in app_1 and app_2 run. Is there a way to do this? I saw that this question specified how to run just a few tests within a single app, but not how to run just a few apps' tests within a project. -
Django Db routing
I am trying to run my Django application with two db's (1 master, 1 read replica). My problem is if I try to read right after a write the code explodes. For example: p = Product.objects.create() Product.objects.get(id=p.id) OR If user is redirected to Product's details page The code runs way faster than the read replica. And if the read operation uses the replica the code crashes, because it didn't update in time. Is there any way to avoid this? For example, the db to read being chosen by request instead of by operation? My Router is identical to Django's documentation: import random class PrimaryReplicaRouter(object): def db_for_read(self, model, **hints): """ Reads go to a randomly-chosen replica. """ return random.choice(['replica1', 'replica2']) def db_for_write(self, model, **hints): """ Writes always go to primary. """ return 'primary' def allow_relation(self, obj1, obj2, **hints): """ Relations between objects are allowed if both objects are in the primary/replica pool. """ db_list = ('primary', 'replica1', 'replica2') if obj1._state.db in db_list and obj2._state.db in db_list: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ All non-auth models end up in this pool. """ return True