Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter with two hops over ForeignKeys
foo = Account.objects.filter( owner__address__zipcode='94704').get() Can I do something like that? Account has an "Owner" foreignKey to an Owner model Owner has anAddress foreign key to an Address model Address has a "zipcode" char field. -
Importing my package from a Django management command
I've written a package which was originally a command-line tool, but I've decided that for Django it should be run from a management command. I've installed my external package (called codequal) using pip install --editable, and I can successfully use manage.py shell to import a module from that package: in[0]: from codequal import something in[1]: something.some_method() out[2]: u'result' This works fine. However, when I try to do the same thing in a management command, I run into an error: File "/home/path/to/django/project/some_app/management/commands/codequal.py", line 8, in <module> from codequal import something ImportError: cannot import name something Why is this? I can use other installed packages from management commands. Could it be something to do with my setup.py? I can post snippets from that if needed. Mainly I'm wondering if this part is to blame: entry_points={ 'console_scripts': [ 'codequal = codequal.cli:main', ], Does this prevent from the module being imported from certain places? I can't see how it would, since I can do it from manage.py shell. -
Getting started building a template/view for a django model that joins two models together
I have a form where I can create and edit a group (a business really). Though I want to be able to say this business has many locations. I have the models written but the UI is giving me trouble. I think mostly my question would be answered by how to update the Group model (creating/editing a group) and the GroupLocations model with a single form (adding an address as a new location if need be) so almost three models with a single form? The models are: class Address(models.Model): city = models.CharField(max_length=50) state = models.CharField(max_length=50) zip_code = models.CharField(max_length=50) address_line_one = models.CharField(max_length=50) address_line_two = models.CharField(max_length=50, null=True, blank=True) contact = models.CharField(max_length=50, null=True, blank=True) phone = models.CharField(max_length=50) fax = models.CharField(max_length=50, null=True, blank=True) created_at=models.DateField(auto_now_add=True) updated_at=models.DateField(auto_now=True) def __str__(self): return self.city class Group(models.Model): group_name = models.CharField(max_length=50) group_contact= models.CharField(max_length=50) tin = models.CharField(max_length=50) npi =models.CharField(max_length=50) notes = models.TextField(max_length = 255, null=True, blank=True) billing_address = models.ForeignKey('Address', related_name = 'billing_address', on_delete=models.SET_NULL, null=True) mailing_address = models.ForeignKey('Address', related_name = 'mailing_address', on_delete=models.SET_NULL, null=True, blank=True) start_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) end_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) change_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) change_text = models.TextField(max_length = 255, null=True, blank=True) term_comment = models.TextField(max_length = 255, null=True, blank=True) group_phone=models.CharField(max_length=50) group_fax = models.CharField(max_length=50) group_term = models.ForeignKey(GroupTerm, … -
Django-Haystack(elasticsearch) Autocomplete giving results for substring in search term
I have a search index with elasticsearch as backend: class MySearchIndex(indexes.SearchIndex, indexes.Indexable): ... name = indexes.CharField(model_attr='name') name_auto = indexes.NgramField(model_attr='name') ... Suppose I have following values in elasticsearch: Cable Magnet Network Internet Switch When I execute search for 'netw' it returned Magnet & Internet also along with Network. Using some other test cases I think haystack is searching for substring also, like net in netw as you see in above example. Here is the code: sqs = sqs.filter(category='cat_name').using(using) querried = sqs.autocomplete(name_auto=q) Also tried with: querried = sqs.autocomplete(name_auto__contains=q) How can I resolve this and make it working to return only those results that contains exact search term ? Using django-haystack==2.4.1 Django==1.9.1 elasticsearch==1.9.0 -
django: how collectstatic overwrite old css files?
In my deb postinst file: PYTHON=/usr/bin/python PYTHON_VERSION=`$PYTHON -c 'import sys; print sys.version[:3]'` SITE_PACKAGES=/opt/pkgs/mypackage/lib/python$PYTHON_VERSION/site-packages export PYTHONPATH=$SITE_PACKAGES echo "collect static files" $PYTHON manage.py collectstatic --noinput When I run 'dpkg -i mypackage.deb' to install the package, no problem. When I run 'dpkg -i mypackage.deb' to re-install the package, old css files unchanged. When I changed '$PYTHON manage.py collectstatic --noinput ' to '$PYTHON manage.py collectstatic --noinput -c' and run 'dpkg -i mypackage.deb' to re-install the package, the error is following: OSError: [Errno 2] No such file or directory: '/opt/pkgs/myporject/static' Any idea? -
How to read django autocomplete lights value to generate choices dynamically?
Hey i would like to get the value of django autocomplete light in the model form and generate choices for the next fields accordingly. class GroupPropertiesForm(forms.ModelForm): <strike>fields['equipment_grade']: forms.ChoiceField( choices=[(o.id, str(o)) for o in GroupProperties.objects.all(group=???group???)]</strike> class Meta: model = GroupProperties fields = ('group', 'bells') widgets = { 'group': autocomplete.ModelSelect2( url='groups-autocomplete') ) } -
Python3 csv.reader read from Requests stream (strings, not bytes)
I'm trying to stream response to csv.reader using requests.get(url, stream=True) to handle quite big data feeds. My code worked fine with python2.7. Here's code: response = requests.get(url, stream=True) ret = csv.reader(response.iter_lines(decode_unicode=True), delimiter=delimiter, quotechar=quotechar, dialect=csv.excel_tab) for line in ret: line.get('name') Unfortunately after migration to python3.6 I got an following error: _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?) I was trying to find some wrapper/decorator that would covert result of response.iter_lines() iterator from bytes to string, but no luck with that. I already tried to use io package and also codecs. Using codecs.iterdecode doesn't split data in lines, it's just split probably by chunk_size, and in this case csv.reader is complaining in following way: _csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode? -
Django Tables2 Display Multiple Tables
I've got user records that have related(ish) course and enrollment records. I want to click on a user and see raw data from the user table, course table, and enrollment table in the same page. The process breaks down when I attempt to render the tables. views.py: def explore_related(request, client_id, user_id): client = get_object_or_404(Client, pk=client_id) users = Users.objects.filter(pk=user_id) enrollments = Enrollments.objects.filter(client_id=client_id).filter(userID__in=users.values_list('userID', flat=True)).all() courses = Courses.objects.filter(client_id=client_id).filter(sectionSchoolCode__in=enrollments.values_list('sectionSchoolCode', flat=True)).all() userTable = UserTable(users, prefix='u_') courseTable = CourseTable(courses, prefix='c_') enrollmentTable = EnrollmentTable(enrollments, prefix='e_') payload = { 'userTable': userTable, 'enrollmentTable': enrollmentTable, 'courseTable': courseTable, } return render(request, 'importer/explore_related.html', payload) explore_related.html: {% load render_table from django_tables2 %} <html> <body> {% render_table userTable %} <br> {% render_table courseTable %} <br> {% render_table enrollmentTable %} </body> </html> tables.py class UserTable(tables.Table): selection = tables.CheckBoxColumn(accessor='userID', orderable=False) errors = tables.Column() User_ID = tables.LinkColumn( 'importer:explore_related', text=lambda record: record.userID, kwargs={ 'client_id': tables.A('client_id'), 'file_kind': 'user', 'object_id': tables.A('id'), }, empty_values='NULL', ) class Meta: model = Users attrs = {'class': 'paleblue'} exclude = ['id', 'client', 'userID'] sequence = ( 'selection', '...', 'errors' ) class CourseTable(tables.Table): selection = tables.CheckBoxColumn(accessor='pk', orderable=False) errors = tables.Column() class Meta: model = Courses attrs = {'class': 'paleblue'} exclude = ['id', 'client'] sequence = ( 'selection', '...', 'errors' ) class EnrollmentTable(tables.Table): selection = tables.CheckBoxColumn(accessor='pk', orderable=False) … -
Execute task once when starting uwsgi-emperor app
I'm using uwsgi-emperor on Debian 8 in my production systems. For a specific Django project, I need to run a computing intensive setup task only once at the launch of the vassal. The vassal can have multiple workers/threads, but the task must be executed only one time, no matter how many workers/threads are spawned. Currently, I'm executing this setup task every time a new worker is launched, but this is clearly suboptimal. The setup task is an invocation of a method from the same Django project, but I think that doesn't change the problem. Is there any way of doing this from uWSGI? -
Django saving in a model with User field
I have token auth implemented in django and my models looks like- class Portfolio(models.Model): owner = models.ForeignKey(User, verbose_name='User', null=True) company = models.TextField(null=True) volume = models.IntegerField(blank=True) date = models.DateField(null=True) And to save in this model, I have the following in views- arr = [] contents = request.data user = User.objects.filter(username=request.user) user_is = User(username=user) for i in range(0, len(portfolio_contents)): line = portfolio_contents[i].split(",") get_isin = Endday.objects.get(company=line[0]) datestuff = line[2] datestuff = datestuff[0:10] arr.append(Portfolio(owner=user_is, company=line[0], volume=line[1], date=datestuff)) Portfolio.objects.bulk_create(arr) This code saves the data but when I try to see the data, I get this- [ { "company": "BAL", "volume": 1425, "date": "2014-02-19", "owner": null }, { "company": "RLD", "volume": 2245, "date": "2014-02-19", "owner": null }, Owner should not be null because if I try to print(user.username), it prints <QuerySet [<User: ku>]>. What seems to be the problem? -
django admin custom view in model properties
I have such models: class Product(models.Model): ... id = models.IntegerField(unique=True) ... class Question(models.Model): product = models.ForeignKey(Product, related_name='question', null=True) answer = models.ForeignKey(Answer, related_name='question', blank=True, null=True) user = models.ForeignKey(User, null=True) text = models.TextField(null=True) ... class Answer(models.Model): user = models.ForeignKey(User, null=True) text = models.TextField(null=True) ... All these models are registered in django admin. How can I get a custom report table while editing one of a Questions (/admin/qa/question/1/change/): ... editable standart_fields from Question model ... non-standart report(without editable fields): all questions: related answers to them User: Question(related to a product) - User: Answer to it User: Question(if it exists) - User: answer to it Is it possible in admin site? -
Python Django populate() isn't reentrant
I've had a program that has been running fine for months. I've been trying to install Postfix on the server this morning and suddenly start getting an error on the site. Here is the traceback mod_wsgi (pid=11948): Target WSGI script '/var/www/zouzoukos/zouzoukos/wsgi.py$ mod_wsgi (pid=11948): Exception occurred processing '/var/www/zouzoukos/zouzoukos/wsgi.py'. Traceback (most recent call last): File "/var/www/zouzoukos/zouzoukos/wsgi.py", line 29, in <module> application = get_wsgi_application() File "/var/www/zouzoukos/env/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup() File "/var/www/zouzoukos/env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) "/var/www/zouzoukos/env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant The thing is, I have a couple more versions of the site running for other people and they're still fine (this was the first). I cannot understand what I need to update to get it working again. I've tried everything in this thread and still nothing -
Login as last step in django form wizard
So I have a normal SessionWizardView which consists of 3 forms/steps. Now, I want the users to fill out the wizard, but not be able to submit it unless they're logged in. Scenario: Users enters step1, step2, step3, (if not logged in)redirect to login-> submit. Right now I've made it so they're redirected immediately to login page if they're not logged in, via urls.py url(r'^add/$', login_required(views.l_wizard) How would I go about doing something like this? Documentation mentions nothing like this. -
Django Rest Framework retur 1 if relation exist
I have two questions. How i can just return true if relation exist? For example I have post model and comment model also, comment have foreginKey to post. Now after post serialization i wanna have something like this { id: 2 content: "My first post!" has-comments: True } And my second question is how rename field name in model relation? Again we have post and comment. In comment model i have foregin key to post like post = models.ForeignKey(Post) Now when i add new comment i send JSON data with {post: postIdHere}. Is possible to change post to postId only in drf not in django model? I hope you understand me :) Best Redgards, Sierran. -
How we can install supervisor to python 3.4.3 in windows 7 and we are using sublime 3 editor And Along with how we can run celery backend?
How we can install supervisor to python 3.4.3 in windows 7 and we are using sublime 3 editor And Along with how we can run celery backend? And we are using sqlite Database -
Adding custom user registration fields in django
I couldn't find much information/am having trouble adding custom user fields to the django create_user function. I have quite a few fields and am not sure how to get them into the database, as currently this function only allows username, password, first name and last name. My views/form/models are: views: def create_account(request): form = CreateAccountForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] password2 = form.cleaned_data['password2'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] gender = form.cleaned_data['gender'] medication = form.cleaned_data['medication'] medical_history = form.cleaned_data['medical_history'] DOB = form.cleaned_data['DOB'] email = form.cleaned_data['email'] telephone = form.cleaned_data['telephone'] address = form.cleaned_data['address'] city = form.cleaned_data['city'] state = form.cleaned_data['state'] postcode = form.cleaned_data['postcode'] if password == password2: if (password_verification(password)) == 3: if (username_verification(username)) == False: user = User.objects.create_user(username, email, password) user.last_name = last_name user.first_name = first_name user.save() return HttpResponseRedirect('/login') else: return HttpResponseRedirect('/create_account') else: return HttpResponseRedirect('/create_account') else: return HttpResponseRedirect('/create_account') return render(request, "create_account.html", {'form': form}) Models: class user(models.Model): username = models.CharField(max_length=20) password = models.CharField(max_length=15) password2 = models.CharField(max_length=20) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) gender = models.CharField(max_length=20) medication = models.CharField(max_length=50, blank=True) medical_history = models.CharField(max_length=50,blank=True) DOB = models.CharField(max_length=20) email = models.EmailField(max_length=30) telephone = models.CharField(max_length=20) address = models.CharField(max_length=30) city = models.CharField(max_length=20) state = models.CharField(max_length=20) postcode = models.CharField(max_length=30) Forms: class CreateAccountForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) … -
Import Polygon Data from geojson files into PostGIS using GeoDjango
Am using GeoDjango with PostGIS as Backend. I have few geojson files with features as following example. GeoDjango has provided information to import shape files and other formats but geojson formats. How do I import these geojson files into DB? "features": [ { "type": "Feature", "properties": { "SubName": "X", "SubSubName": "TIRUVURU" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 70.693828, 37.074496 ], [ 70.693828, 37.074496 ] ] ] } } , { "type": "Feature", "properties": { "SubName": "X", "SubSubName": "Y" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 70.502913, 27.065997 ], [ 70.502913, 27.065997 ] ] ] } } I have two core requirements: Load the Subregion polygons on webportal using D3JS Map library When i have a lat-long, find in which polygon does this point exist and get the SubName & SubSubName from the polygon properties. It would be great, if there is proper documentation on PostGIS usage & import files for GeoDjango. Thanks in Advance. -
Django using functions from a python class from frontend?
I am new to Django, but i managed to create the back-end and front end for my website but in the front end i am connecting to an external socket and getting data on the fly and i implemented a class that has the function add_data2GraphDB(Data) that adds the element to my graph database How can I call this function from the front end so it is applied in the back-end without disturbing the rendering of the website. this is the js code on the front-end page <script> eventToListenTo = 'tx' room = 'inv' var socket = io("https://blockexplorer.com/"); socket.on('connect', function() { // Join the room. socket.emit('subscribe', room); }) socket.on(eventToListenTo, function(data) { ***add_data2GraphDB(Data)***; }) </script> -
How to configure redis in django in microsoft azure?
I have this locator job deployed in azure. My redis cache host name(DNS) is mycompany.azure.microsoft.net. I created it in azure, but not sure where i can find the password and hostname for the redis server. Also can it be run from my local machine ? or just give the a correct url for configuring . i would also -
NameError: global name 'query' is not defined
I have a small django project and Im trying to pass a variable from my views.py into tasks.py and run a task using the variable, but I am getting name is not defined error, ive tried many solutions ive seen on other questions but i cannot seem to get it to work here is my views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, loader from django.template import Context from django.http import HttpResponse import json import requests from tasks import rti def index(request): return render(request, 'bus/index.html') def search(request): query = request.GET.get('q') t = loader.get_template('bus/search.html') c = Context({ 'query': query,}) rti() return HttpResponse(t.render(c)) here is my tasks.py from background_task import background import time @background(schedule=1) def rti(): timeout = time.time() + 60 * 15 while time.time() < timeout: from views import search dblink = '*apiurl*' + str(query) + '&format=json' savelink = 'bus/static/bus/stop' + str(query)+ '.json' r = requests.get(dblink) jsondata = json.loads(r.text) with open(savelink, 'w') as f: json.dump(jsondata, f) here is the traceback: Traceback (most recent call last): File "/Users/dylankilkenny/dev/python/test2/lib/python2.7/site-packages/background_task/tasks.py", line 49, in bg_runner func(*args, **kwargs) File "/Users/dylankilkenny/dev/python/test2/mysite/bus/tasks.py", line 9, in rti from views import search NameError: global name 'query' is not defined -
Tastypie - Calling dispatch of other resoueres Manually
I need to create an API(named Dummy) that connects to multiple other API's in order to apply filters What i did was call the dispatch method on the main API's dispatch method. I changed the requests QUERY_STRING for each API that was being called class DummyResource(MultipartResource, ModelResource): class Meta: queryset = Dummy.objects.all() resource_name = 'dummy' allowed_methods = ['get'] def dispatch(self, request_type, request, **kwargs): #Call the 1st API request.META['QUERY_STRING']='years_experience__in=2&production_2015__gt=105000' obj=APIONEResource() print 'Result'+str(obj.dispatch(request_type, request, **kwargs)) #Call the 2nd API request.META['QUERY_STRING']='LOS__contains={2}&annual_production__in=4' obj=APITWOResource() print 'Result'+str(obj.dispatch(request_type, request, **kwargs)) return super(DummyResource, self).dispatch(request_type, request, **kwargs) Now when I call the 1st API everything works fine and I get the correct filtered result. But when I call the 2nd API it returns all the results without any filters. I can confirm that the QUERY_STRING was changed correctly and cannot understand why this doesnt work. I have tried reversing the calling order and the results are that the first time any API is called the filters are applied but the 2nd time it does not apply. Any ideas ? -
UPDATE MySQL with 'onclick' button command in Django Project
I am extremely new to django and web dev on the whole, so please bear with me. I have created a simple site with a MySQL backend for my local football team and want to create a page to update the score of a game (stored on a table) simply by clicking a button (increment the current score by + 1). I have no doubt in my mind that this is super simple, but after WEEKS of trawling through similar posts, nothing seemed to work for me (nothing that I could understand at least). I have a template that that creates a button that contains the ID for the record that needs to be updated: <a href="{% url livegame_update %}?value={{stat.id}}?updatetype=goals" class="btn btn-success" role="button" onclick="alert({{stat.id}})" id={{stat.id}}>Goal</a> This points to this URL: url(r'^livegame_update', 'steelers_fc.players.views.livegame_update', name='livegame_update'), Which in turn executes this function the Views; def livegame_update(request): StatID = request.GET.get('value','1') StatType = request.GET.get('updatetype','1') SQL = "update players_statistics set " + StatType + " = " + StatType + " + 1 where id = " + StatID + ";" #stat_edit = statistics.objects.get(id=StatID) #stat_edit.goals = stat_edit.goals + 1 #stat_edit.save() # save object cursor = connection.cursor () cursor.execute (SQL) connection.commit() cursor.close () connection.close () return render_to_response … -
"CSRF Failed: CSRF token missing or incorrect." in Django Rest: UpdateModelMixin
I am using UpdateModelMixin from Django rest framework to update the entries from the Test model. from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache from rest_framework import mixins, filters, viewsets decorators = [never_cache] @method_decorator(decorators, name='dispatch') class TestViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): queryset = Test.objects.all() serializer_class = TestSerializer filter_backends = [filters.DjangoFilterBackend] filter_class = TestFilter When I try to update the object from the Test Model It's giving following error - "detail": "CSRF Failed: CSRF token missing or incorrect." Can anyone please help me to resolve this issue? -
send_mail is clearly sending email but no email is showing up in inbox
I have these email settings in my settings.py EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'email@myemail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 and am using this function to send email to recipients. def send_email(subject, body, recipients, agent_email, bcc=[], attachments=[]): recipient_list = [] if isinstance(recipients, (str, unicode,)): recipient_list.append(recipients) else: recipient_list = recipients recipient_list = recipient_list + bcc send_mail(subject, body, settings.EMAIL_FROM, recipient_list) while it looks quite clear when I go to the django-admin site that the email was indeed sent and no error messages show in the log files whatsoever, when I go to check the email that it was sent to, nothing shows in the inbox. I would expect to see the email there, especially given that it shows as sent in django-admin. Have I misunderstood something about how email is sent from the system? -
django testing http get replaces args
Django replaces my arguments by others during my tests for no apparent reason: client = Client() print(reverse('search_manufacturer')) # prints /search/manufacturer client.get(reverse('search_manufacturer'), dict(q=str(uuid4())))` results in me getting : django.core.urlresolvers.NoReverseMatch: Reverse for 'show_manufacturer' with arguments '()' and keyword arguments '{'manufacturer_id': 5}' not found. 0 pattern(s) tried: [] Where is manufacturer_id comming from? my url patern is : url(r'^manufacturer$', views.search_manufacturer, name='search_manufacturer') If I call client.get(reverse('search_manufacturer') it works fine, but it is not what I would like to test