Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Select from two tables through their ForeignKey with Django ORM
Suppose we have these Models (in drugs app): class SprDrugs(models.Model): drug = models.CharField(primary_key=True,max_length=10) product_name = models.CharField(max_length=255) class SprMeasure(models.Model): measure = models.IntegerField(primary_key=True) name = models.CharField(max_length=10) class Procurements(models.Model): procurement_date = models.DateField() measure = models.ForeignKey('SprMeasure', to_field='measure') drug = models.ForeignKey('SprDrugs',to_field='drug') class AveragePrice(models.Model): drug = models.ForeignKey(SprDrugs, to_field='drug') measure = models.ForeignKey(SprMeasure, to_field='measure') avg_price = models.DecimalField(max_digits=16, decimal_places=2) How can I do select all rows from procurements table with corresponding to them avg_price values (drug and measure values in both tables must be equal)? In raw SQL this is a simple case: SELECT public.drugs_procurements.*, drugs_averageprice.avg_price FROM public.drugs_procurements, public.drugs_averageprice WHERE drugs_procurements.measure_id = drugs_averageprice.measure_id AND drugs_procurements.drug_id = drugs_averageprice.drug_id; But in Django ORM it needs a bit of magic. I have read about select_related and prefetch_related, but stiil can't make a valid QuerySet for this. Thanks in advance! -
How can I split DataFrame (pandas) on pages with django paginator?
It is easy for Series. I just pass it to paginator. But, when I use DataFrame, it is call "The truth value of a Series is ambiguous". Maybe, there are problem with 'count' method, but I don't know how I can change it. In my project DataFrame must be split on pages by rows. def listing(request): contact_list = pd.DataFrame(np.arange(12).reshape(4,3)) paginator = Paginator(contact_list, 1) # Show 1 row per page page = request.GET.get('page') try: contacts = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. contacts = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. contacts = paginator.page(paginator.num_pages) return render(request, 'list.html', {'contacts': contacts}) -
Resource views in Django
I'm using Django for the first time (I'm also new to Python in general) and I've been struggling with a certain problem related to class based views for a while now. I'm coming from PHP with Laravel, where you can have so-called "RESTful Resource Controllers". For everyone not familiar with Laravel: the idea is that you have one controller (or view, in Django-speak) per 'resource'. This controller/view defines methods such as index(), show(), create(), store(), edit(), etc. The associated urls and HTTP methods for these controller methods are GET /photos, GET /photos/1, GET /photos/create, POST /photos, GET /photos/1/edit respectively (for example, if you're dealing with photos). In Laravel's routing, you have to declare just one line Route::resource('photos', 'PhotoController') and those URLs are automatically generated. For more info, I refer to Laravel's docs. I really like this pattern and I'd like to use it in Django. As far as I understand, Django doesn't really have such a thing out of the box. Django does have class based views, but those don't represent resources. Rather, you have a view for your 'index()' (PhotoListView), a view for your 'show()' (`PhotoDetailView') and so on. I'm not sure how I should implement this pattern in … -
Django 1.10.3 Application labels aren't unique, duplicates: sites?
Django 1.10.3 is giving me this error, but django 1.6.11 giving me following error ? ==>sh my.sh init index run *** Initializing server on www.my_app.me:8080 with my.settings.base *** Running all tests Traceback (most recent call last): File "manage.py", line 9, in <module> execute_from_command_line(sys.argv) File "//anaconda/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "//anaconda/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "//anaconda/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "//anaconda/lib/python2.7/site-packages/django/apps/registry.py", line 89, in populate "duplicates: %s" % app_config.label) django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: sites Duplicate question Please suggest me how I can resolve the issue ? Thanks in advance !! -
how {% block main_content %} works in django crudbuilder
I'm using a django app called crudbuilder with the purpose of building a table that can be manipulated with multiple filter inputs, as well as being able to toggle the categories within the table on and off. The github for crudbuilder is here https://github.com/asifpy/django-crudbuilder/blob/master/crudbuilder/templates/base.html#L54 and I have marked the specific line of their code that is giving me trouble. {% block main_content %}{% endblock %} is the line that's giving me some trouble. "main_content" refers to a table, a search bar, a title, a "create button" and a pagination. I want to be able to manipulate the table depending on custom search inputs that I've implemented into the UI. I can get results to come up but they completely erase the "main_content" block. I want to be able make it so that my custom search box can filter through the table, I'm just having a hard time figuring out how it works in the crudbuilder github code. Within the crudbuilder code, that main_content block contains a search bar that does exactly what I want. but I con't figure out how they are making in work. Their search bar will filter the names on the database but that's it. I have … -
Deploying django on apache: No module named Portfolio.settings
I've got my project in /var/Django/Portfolio while having a virtualenv in /var/Django/env. It's just a new project without any changes except that I've set the DEBUG = False in the settings.py. Virtualenv has Django 1.9.15 and Python2.7 installed. When I run the project with the runserver on debug mode the site displays just fine, but when I try to deploy and open the site I get a 500 Internal Server Error. Looking at the log file it says ImportError: No module named settings Like I said I've changed nothing, just created the project with the startproject command. My /etc/apache2/sites-enabled/000-default.conf file has the following settings added to it (was default before): WSGIDaemonProcess folio python-path=/var/www/Django:/var/www/Django/env/lib/python2.7/site-packages WSGIProcessGroup folio WSGIScriptAlias / /var/www/Django/Portfolio/Portfolio/wsgi.py <Directory /var/www/Django/> <Files wsgi.py> Require all granted </Files> </Directory> -
POST is not working in angularJS
I made a simple recipe organizer as I am trying to get more familiar with AngularJS, Django, and python. When I try to post my recipe, it gives me a Internal Service Error (500). I cant figure out why it wont post. Anyone willing to help me out? here is where the recipe posts to after I add it: <section id="download" class="download bg-primary text-center"> <div class="container"> <div class="row"> <div ng-repeat="recipe in recipes" id="single-recipes" class="col-sm-2"> <h4><a href="/app/#/recipes/{{ recipe.id }}">{{ recipe.name }}</a></h4> <img ng-src="{{ recipe.photo }}"> <h4>Description:</h4> <p>{{ recipe.description }}</p> </div> </div> </div> </section> along with that is the JS: 'use strict'; angular.module('myApp.recipes', ['ngRoute']) .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/recipes', { templateUrl: 'recipes/recipes.html', controller: 'RecipesCtrl' }) }]) .controller('RecipesCtrl', ['$scope', '$routeParams', 'Restangular', function ($scope, $routeParams, Restangular) { Restangular.all('recipes').getList().then(function (recipes) { $scope.recipes = recipes; }); }]); here is the form for adding the new recipe: <section id="contact" class="contact bg-primary"> <div class="container"> <div class="row"> <div id="add-recipe-body" class="col-sm-6 col-sm-offset-3"> <h4>Add A New Recipe</h4><br> <div class="form-group"> <label>Recipe Name</label><br> <input type="text" placeholder="Recipe Name" class="form-control" ng-model="recipe.name" required> </div> <br> <label>Recipe Photo</label> <img ng-src="{{ recipe.photo }}" ng-show="recipe.photo" width="200" class="img-responsive img-rounded"> <div class="form-group"> <input type="file" id="file" name="file" accept="image/gif, image/x-png, image/jpeg, imgage/jpg" onchange="angular.element(this).scope().addPhoto()"/> </div> <br> <div class="form-group"> <label>Recipe Description</label><br> <textarea placeholder="Description" class="form-control" ng-model="recipe.description" … -
django filter and order by not being able to modify field?
I have a BooleanField called 'used' in my LabHours model which has a default value of False (this is supposed to be an attendance system), and I want to set this to True based on a filter and ordering. Even though I explicitly set this field to be true, when I print out its value, it still displays False. Here is my code for reference: LabHours.objects.filter(used=False).order_by("endtime").first().used = True for hours in LabHours.objects.all(): hours.save() print hours.used Console output: False False False False False False False Why does it not set this field to be True? -
Tastypie Not Found Exception while creating new entry in database
I am using tastypie as REST api. I am trying to create a new entry in my database after checking that the data is not already present in the db. def obj_create(self, bundle, request=None, **kwargs): attempt = ABC.objects.filter( phone=bundle.data['phone'], name=bundle.data['name']) if attempt.count() < 1: bundle = super(ABCResource, self).obj_create(bundle, **kwargs) else: raise ABCNotSaved( {"id": int(attempt[0].id), "error": "Duplicate"}) return bundle class ABCNotSaved(Exception): pass When I am trying to create an entry in my db, it throws 500 error along with the message {"error_message": "Sorry, this request could not be processed. Please try again later."} phone and name are unique fields in my ABC model. -
Django how to populate fields in 'trough' intermediate model when adding an object to a ManyToManyField?
I couldn't word it properly nor could I find it in the documentation, but how do I also add to the intermediate 'through' model of a ManyToManyField when add new objects to it? Note that its a recursive relationship, but I used ManyToMany as I was unsure if OneToOne supports a "through" model (the documentation does not specifies it) Also Person_Person will be used regardless of the curr_partner field, adding objects like parents/child relationships to it (which have no field in Person) (I realize that my model has some contextual/theoretical flaws, but let's abstract that for now) For example Models.py : class Person(models.Model): objectid = models.AutoField(primary_key=True) name = models.CharField() curr_partner = models.ManyToManyField( self, on_delete = models.CASCADE, through = Person_Person, #This lets you define the model that will act as an intermadiary symmetrical = False, #This needs to be set with recursive relationships ) class Person_Person(models.Model): person_1 = models.ForeignKey(Pessoa, ondelete=models.CASCADE) person_2 = models.ForeignKey(Pessoa, ondelete=models.CASCADE) relation = models.ChoiceField( ('P', 'Parent'), ('C', 'Child'), ('E', 'Engaged'), ('W', 'Widow'), ) Query : #Adding a married couple father = Person(name = "John") mother = Person(name = "Anna") p1.curr_partner.add( p2 , through.relation = "Engaged") #??? #Adding a 'Child' relation child = Person(name = "Billy") #This makes sense?? … -
AWS/Django: 500 internal server error on AWS ec2
I have created an Amazon ec2 instance with "Django powered by Bitnami" AMI. I think the problem is with djando.wsgi. I'm getting the "The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, you@example.com..." I would appreciate helping me solve this. My django.wsgi is as follows: import os import sys sys.path.append('/opt/bitnami/apps/django/django_projects/Project') os.environ.setdefault("PYTHON_EGG_CACHE", "/opt/bitnami/apps/django/django_projects/Project/egg_cache") from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings") application = get_wsgi_application() /opt/bitnami/apps/django/django_projects/Project/conf/httpd.conf: <IfDefine !IS_DJANGOSTACK_LOADED> Define IS_DJANGOSTACK_LOADED WSGIDaemonProcess wsgi-djangostack processes=2 threads=15 display-name=%{GROUP} </IfDefine> <Directory "/opt/bitnami/apps/django/django_projects/Project/testproject"> Options +MultiViews AllowOverride All <IfVersion < 2.3 > Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.3> Require all granted </IfVersion> WSGIProcessGroup wsgi-djangostack WSGIApplicationGroup %{GLOBAL} <IfVersion < 2.3 > Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.3> Require all granted </IfVersion> </Directory> Alias /static "/opt/bitnami/apps/django/lib/python2.7/site-packages/Django- 1.10.2-py2.7.egg/django/contrib/admin/static" WSGIScriptAlias / '/opt/bitnami/apps/django/django_projects/Project/testproject/wsgi.py' -
Django foreign key vs complex query
I have a following Model class Library(models.Model): title = models.CharField(max_length = 255) class Book(models.Model): name = models.CharField(max_length = 255) library_id = models.ForeignKey(Library) class Author(models.Model): name = models.CharField(max_length = 255) book_id = models.ForeignKey(Book) How do I get all Authors that belong to a specific library? Is it more efficient in Author to have a foreign key directly to Library? -
django rest Serializers how to representation
in django models class TableFriend(models.Model): user = models.ForeignKey(User, related_name="main_user", default="newbie") friend = models.ForeignKey(User, related_name="friend_for_user", default="newbie") date = models.DateTimeField(auto_now= True) def __str__(self): return '%s %s %s' % (self.user, self.friend, self.date) django rest code class FriendSerializer(serializers.ModelSerializer): class Meta: model = TableFriend fields = ('user','friend', 'date') output: [{"user":1,"friend":3,"date":"2016-11-10T15:12:33.189570Z"},{"user":1,"friend":2,"date":"2016-11-10T15:11:56.936230Z"}] but i need name of friends i want see "friend":username i want see also str from django model how i can do it? -
django error no module named urls after sitemaps installation
I'm getting the following error: File "/mysite/urls.py" in 7. from commerce.sitemaps import CommerceSitemap File "/mysite/sitemaps.py" in 3. from django.urls import reverse Exception Type: ImportError at / Exception Value: No module named urls Request information: GET: No GET data My installed apps look like: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django.contrib.sites', 'django.contrib.sitemaps', 'commerce', ] My urls.py looks like: sitemaps = { 'commerce': CommerceSitemap, } url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},name='django.contrib.sitemaps.views.sitemap'), Does anyone know what I'm doing wrong? -
Django + Haystack + Whoosh, no results in production
I'm building a Django application using Haystack+Whoosh for search. In the development environment, search works as expected. However, in production, searches consistently return no results. Development: $> python manage.py rebuild_index ... All documents removed. Indexing 8 categories Indexing 4 documents $> python manage.py shell ... >>> from haystack.query import SearchQuerySet >>> SearchQuerySet().all().count() 12 Production: $> dokku run proj python manage.py rebuild_index ... All documents removed. Indexing 8 categories Indexing 4 documents $> dokku run proj python manage.py shell ... >>> from haystack.query import SearchQuerySet >>> SearchQuerySet().all().count() 0 Files/settings: # requirements.txt Django==1.10.3 django-haystack==2.5.1 gunicorn==19.6.0 psycopg2==2.6.2 whitenoise==3.2.2 Whoosh==2.7.4 ... # runtime.txt python-3.5.2 Any guidance on finding the issue? -
Django REST framework receive "bad" DecimalField but don't error out
I'm writing a piece of code that needs to take POSTs from a ColdFusion system which is very inflexible when it comes to JSON, and I don't have much control over it anyhow. I have a problem where sometimes an automated system running on ColdFusion will send "empty" DecimalFields as "". This causes a validation error in Django because DecimalFields cannot be converted from an empty string: TOTAL_DEFECTS = models.DecimalField(max_digits=10, decimal_places=2, null = True) JSON that fails it... "TOTAL_DEFECTS":"", That should just produce a null field, but instead, it errors out, saying that's not valid. Technically it isn't since, of course, you can't do this in Python: import decimal decimal.Decimal("") In order to handle this, I have hacked into the dispatch routine of the viewset. I was wondering if there's a better way to do this. Hack-y code: @csrf_exempt # Because ColdFusion can't handle CSRF headers def dispatch(self, request, *args, **kwargs): repregex = re.compile(r'"",') # This is actually done elsewhere in the real code nbody = repregex.sub('null,', request.body) request._body = nbody request._stream = BytesIO(nbody) a = super(XViewSet, self).dispatch(request, *args, **kwargs) if a.status_code != 201: #log errors here pass return a This works for this specific case but I think is … -
Django db aggregation on timefield
I have timefield in model. class Model(models.Model): name = models.CharField(max_length=10) total_time = models.TimeField(blank=True, null=True) And here i create 2 records: Model.objects.create( name='1', total_time=str(timedelta(seconds=0)) ) Model.objects.create( name='1', total_time=str(timedelta(seconds=100)) ) now when i do records = Model.objects.filter(name='1') for log in signal_logs: print(log.total_time) signal_logs = signal_logs.aggregate(Sum('total_time')) print('Total: ', signal_logs['total_time__sum']) printed values are: 00:00:00 00:01:40 Total: 140 This is not correct, sum needs to be 100 or 00:01:40. -
Can I upload a file to django app using a python script?
I have tried making a post request, which is the way forms in django work. But there is a 403:Forbidden error raised every time I try. I want to upload a file from a desktop to my server. Following is the code : urls.py - the url: ... url(r'^post/$',views.GetFile) ... and the python code - from urllib.parse import urlencode from urllib.request import Request, urlopen url = 'http://127.0.0.1:8000/post/' # Set destination URL here file = open('test.txt', 'rb') post_fields = {'FILES': file } # Set POST fields here request = Request(url, urlencode(post_fields).encode()) json = urlopen(request).read().decode() print(json) views.py has this function : def GetFile(request): if request=='POST': file = request.FILES file1 = open('wtest.txt','w') file1.write(file) -
order_by causing not distinct items
I've implemented a messaging system: class Message(models.Model): user = models.ForeignKey(User, unique=False, related_name = 'messages') conversation = models.ForeignKey('Conversation', related_name = 'messages') body = models.TextField(max_length=750) reads = models.ManyToManyField(User, related_name='read_messages', null=True, blank=True) # Other date_created = models.DateTimeField(auto_now=False, auto_now_add=True, blank=True) date_modified = models.DateTimeField(auto_now=True, auto_now_add=False, blank=True) class Conversation(models.Model): participants = models.ManyToManyField(User, related_name='conversations') type = models.CharField(max_length=1, default="D", choices=config.CONVERSATION_TYPE_OPTIONS) Using Django Rest Framework, I'd like to order a conversation by the last message. class ConversationFilter(filters.BaseFilterBackend): """ Filters to only show by current user """ def filter_queryset(self, request, queryset, view): return queryset.filter( participants=request.user, ).order_by('-messages') However once I add the order_by method, the queries are no longer distinct. Adding distinct() does not work either. What is going on here? -
Django foreign key backreference filter results
I have a model as follows: class Event(models.Model): name = models.CharField(max_length=50, blank=False, verbose_name="Event name", ) date = models.DateField(auto_now=False, auto_now_add=False, ) hall = models.ForeignKey(Hall, on_delete=models.CASCADE, null=True, related_name='events', ) I have a view just for trying out results: @api_view(('GET',)) def get_specific_hall(request, cityId, year = None, month = None, day = None): hall = Hall.objects.filter(city=cityId) testHall = Hall.objects.get(city=cityId) date = year + '-' + month + '-' + day events = [] for event in testHall.events.filter(~Q(date=date)): events.append(event) eventSerializer = EventSerializer(events, many=True) serializer = HallSerializer(hall, many=True) return Response(serializer.data + eventSerializer.data) What I want is: I am passing date as a url parameter. I want to return those Hall objects from a specific city and which do not have any associated event for that date. i.e. only available hall. How can I achieve that? -
Django: dynamic formset with Jquery only save first formset instance
So I have set up the following codes for sample from followed by inline formset of its foreign key, sample detail. I also added some dynamic feature to it so that you could add more rows for the formset via Jquery. views.py def project_detail (request, project_id): project = Project.objects.get(id = project_id) sample_form = SampleForm(request.POST or None, request.FILES or None, instance = project) SampleInlineFormSet = inlineformset_factory(Sample, SampleDetail, form=SampleDetailForm, extra=1, can_delete = False) formset = SampleInlineFormSet(request.POST or None, request.FILES or None, prefix="nested") if request.method == "POST": if 'sampleform' in request.POST: if sample_form.is_valid() and formset.is_valid(): sample_temp = sample_form.save() sample = Sample.objects.get(pk = sample_temp.pk) objects = formset.save(commit=False) for object in objects: object.sample = sample object.save() messages.success(request, "Sucessfully Created New Sample Log" ) return HttpResponseRedirect(reverse('projstatus:project_detail', args=(project_id,))) context = {'project' : project, "sample_form":sample_form, 'formset' : formset} return render(request, 'projstatus/detail.html', context) forms.py <form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %} {% crispy sample_form %} <div id="form_set"> {{ formset.management_form }} {% for form in formset.forms %} <table class='no_error'> {{ form.as_table }} </table> {% endfor %} </div> <input type="button" value="Add More" id="add_more"> <div id="empty_form" style="display:none"> <table class='no_error'> {{ formset.empty_form.as_table }} </table> </div> <script> $('#add_more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> <button type='submit' class='save btn btn-default' … -
Django Import Error when running templates
i am getting this error when i use templates: ImportError: No module named templates.backends.django if i use an HttpResponse the page shows up but i get this error with the render function views.py from django.shortcuts import render def login(request): return render(request,'/test.html') im using python 2.7.12 -
Installing MySQLDB for python 2.7 using pip on Windows 7 64bit
I have spent hours trying multiple approaches to install MYSQLDB module for python, and no success. My python version: 2.7.6 Django - 1.10.3 OS: Windows 7 64-bit MySQL connector - MySQL Connector C 6.0.2 Currently I have an error in my project, namely: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb I have tried to install mysqldb running the following command: pip install mysql-python It ran successfully, but the error still persisted. Then I tried to run pip install MySQL-python and I am getting Cannot open include file config-win.h. I came across this post, but I don't understand the idea of the answer, specifically, I can't figure out where I should look for the mentioned files site.cfg and setup_windows.py. There are no such files in C:\Program Files\MySQL\MySQL Connector C 6.0.2\include Finally, I tried to install MySQLDb using wheels running pip install mysqlclient-1.3.9-cp27-cp27m-win_amd64.whl command, I end up with mysqlclient-1.3.9-cp27-cp27m-win_amd64.whl is not a supported wheel on this platform error. I have lost my hope. Help please !!! -
json object returned by http response
I am using python and django to develop some REST APIs. I have a question about the JSON unicode string returned by the requests call. So, I am doing something like: resp = requests.get(self.url) if resp.status_code is status.HTTP_200_OK: obj = json.loads(resp.json()) With this I can iterate over the entries as: for o in obj: print o This prints something like: {u'pk': 1, u'model': u'aslapp.imagetypemodel', u'fields': {u'type': u'PNG'}} {u'pk': 2, u'model': u'aslapp.imagetypemodel', u'fields': {u'type': u'JPG'}} However, I read that the resp.json() call should call this json.loads() method internally and will take care of the encoding stuff. However, just doing: obj = resp.json() for o in obj: print o Just iterates over each character in the unicode string. So am I supposed to run it through the loads method again if I want to iterate through the JSON entries? What would be the correct way to iterate through all the JSON records returned returned by resp.json(). -
Django multi languages by files
hello i have read lots of stuff about multilingual, translate in Django, but i'm looking for something different, like this: Have files .json or a table with something like: string EN FR PT str-1 login Entrer Entrar str-2 Next Suivant Seguinte ... in code, something like this: {resource.str-1} Someone know any library or method to doing this easily and quickly?