Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - File being served by view for download is 0 bytes
I am attempting to serve a file for download using the following code def download(request): try: file = "Myfile.dmg" filepath = "/Users/admin/Development/" + file response = HttpResponse(content_type='application/octet-stream') response['Content-Disposition'] = 'attachment; filename=%s' % (file) response['X-Sendfile'] = filepath return response except Exception as e: return HttpResponse(str(e)) However the file being downloaded is 0 bytes. Any suggestions on what I might be doing wrong ? -
Count files each user has uploaded and approved
I am building a Django app for uploading files. I would like to be able to count the number of files a users has and which are approved. I have a model with a Boolean 'approved' field. This model is in admin.py. In admin.py from django.contrib import admin from .models import FileModel from .forms import FileForm class FileModelAdmin(admin.ModelAdmin): form = FileForm fields = ('title', 'description', 'categories', 'pub_date', 'submitted_date', 'author', 'user', 'approved', 'upload', 'vote') # pass list_display = ['title', 'approved', 'author', 'user', 'categories', 'description', 'pub_date', 'submitted_date', 'upload', 'vote'] admin.site.register(FileModel, FileModelAdmin) I would like an integer in another model 'new_user_model', which is in another app, to increase an integer field 'files' by one when a file is approved in the admin site. This way I could keep track of how many files have been approved for each user. class NewUserModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # user = models.ForeignKey(User) files = models.IntegerField(default=0) The model for the files, class FileModel(models.Model): title = models.CharField(max_length=100) description = models.CharField(max_length=255) pub_date = models.DateTimeField('date published') submitted_date = models.DateTimeField('date submitted') author = models.CharField(max_length=255) user = models.ForeignKey(User, default=6) approved = models.BooleanField(default=False) upload = models.FileField()..................... ................................................... So I want the files field in new_user_model to increase by one when a file is … -
Running uwsgi socket only works when I set chmod-socket=666
Is there any way I can get this socket running in 664? uwsgi --socket /etc/nginx/sites-available/TestServer.sock --wsgi-file TestServer/wsgi.py --chmod-socket=666 666 Django runs fine, but 664 and I get a 502 Bad Gateway. Thanks for any help you can provide! -
Can I add custom fields in django-newsletter module?
Can I add addition fields in the django-newsletter subscription ? Like the country and the city ? -
Is there a fork of Python Social Auth that supports Django 1.9 or 1.10 under Python 3.5?
I see a lot of issues and pull requests on the python social auth repo, all of which have not been acted on and the django app itself hasn't been updated in over 2 years. Is there a fork of the project to which the compatibility changes have already been applied? -
Django annotate in template
I am working on a small project in which occupations posted are to be ranked. Ranking is on the basis of the number of times an occupation is posted. I have managed to query the data and rank the occupation. However in the template when I try display the occupations and their percentages, it's only their 'id' which is displayed. I want the occupation's name to appear instead. Below are the flows #models.py class OccupationGroup(models.Model): group=models.CharField(max_length=200) def __str__(self): return self.group class Occupation(models.Model): group=models.ForeignKey(OccupationGroup) occupation=models.CharField(max_length=200) def __str__(self): return self.occupation class OccupationData(models.Model): group=models.ForeignKey(OccupationGroup) #added for testing #occupation=models.ForeignKey(Occupation) occup=ChainedForeignKey(Occupation,chained_field='group', chained_model_field='group',)#added for testing occupation=models.CharField(max_length=500) #county=models.ForeignKey(County) county=models.CharField(max_length=600) date_of_advertisement=models.DateField(verbose_name="Date of Adveertisement") #source=models.CharField(max_length=200,null=True, blank=True, verbose_name="Source") positions=models.CharField(max_length=200, verbose_name="Number of positions") def __str__(self): return self.occupation views.py def demand(request): context_dict={} total_items = OccupationData.objects.count() items = [ {'data': g['occupation'], 'value': g['total'] * 100 / total_items} for g in data ] context_dict={'data':items} return render(request,'labourdemand/demand.html',context_dict) demand.html {% for data in data %} {{data.data }} {{ data.value|floatformat:"2" }}%<br> {% endfor %} Sample Output 1 23% 2 21.22% 3 11.12% Required Output Chemists 23% Lawyers 21.22% Mathematicians 11.12% What am I not getting right to get this work?? -
pdfkit - wkhtmltopdf cannot be found
So I have been banging my head over this issue so far and I understand that SO is filled with issues that resemble this however I tried pretty much most of the suggestions and not sure where i might be going wrong this is my simple test code. I would like to convert html to a pdf options = { 'page-size': 'A4', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', } config = pdfkit.configuration(wkhtmltopdf="/usr/local/bin/") pdfkit.from_string("Hello World","Somefile.pdf",options=options,configuration=config) return HttpResponse("Works") Now I still get the error No wkhtmltopdf executable found: "/usr/local/bin/" If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf Now in order to resolve that issue I installed wkhtml from here for osx as result when I did the following >> which wkhtmltopdf /usr/local/bin/wkhtmltopdf /usr/local/bin >> ls -l wkhtmltopdf -rwxr-xr-x 1 root admin 49508480 Jan 20 2016 wkhtmltopdf This showed me that I installed wkhtmltopdf. Now my question is why am I still getting that error. Any suggestions would be appreciated. -
Can I make desktop application for all platforms using django?
I want to build a desktop application which retrieves data from server and also is easy to implement and deploy on any platform Is django perfect for my use? -
NoReverseMatch: Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] 1 : {% extends "registration/registration_base.html" %} 2 : {% load i18n %} 3 : 4 : {% block title %}{% trans "Register for an account" %}{% endblock %} 5 : 6 : {% block content %} 7 : <form method="post" action=""> 8 : {% csrf_token %} 9 : {{ form.as_p }} 10 : <input type="submit" value="{% trans 'Submit' %}" />` -
When does Django ImageKit create the thumbnail file?
I am trying to understand how Django ImageKit works with respect to creating thumbnail files (for example). I am using the example code: from django.db import models from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill class Profile(models.Model): avatar = models.ImageField(upload_to='avatars') avatar_thumbnail = ImageSpecField(source='avatar', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) I am uploading the avatar image from an app. This works fine with an entry made in the Profile table and the file created in AWS S3. What I am struggling to understand is when/where/how the avatar_thumbnail is created. Do I have to do something explicit to get it stored in AWS S3 along with the avatar image? Or is the avatar_thumbnail only ever created on the fly? I need it stored somewhere for later use. -
Nested objects save in DRF
Models: class Owner(models.Model): name = models.CharField(max_length=255) def __unicode__(self): return self.name class SomeThing(models.Model): own_id = models.IntegerField(unique=True) description = models.CharField(max_length=255, blank=True) owner = models.ForeignKey(Owner, blank=True, null=True) def __unicode__(self): return self.description Serializers: class OwnerNameField(serializers.RelatedField): def to_internal_value(self, data): pass def to_representation(self, value): return value.name def get_queryset(self): queryset = self.queryset if isinstance(queryset, (QuerySet, Manager)): queryset = queryset.all() lista = [Owner(name="------------")] lista.extend(queryset) return lista class OwnerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Owner fields = ('name', 'id') class ThingSerializer(serializers.ModelSerializer): owner = OwnerNameField(queryset=Owner.objects.all()) class Meta: model = SomeThing fields = ('own_id', 'description', 'owner') Basically it works as intended. But when i add some fields to Owner class i would like to see all these fields in output of ThingSerializer (and be able to parse them - string doesn't suit here). I could change field owner to owner = OwnerSerializer() which gives me what i need. But when i want to add SomeThing object (tested in API browser) i also need add new Owner object - and i don't want it, i want use existing Owner object. How can i achieve it? -
"Initializing geometry from JSON input requires GDAL" Error
I'm doing a Django project and I want to save polygons that represent areas of interest in a map. I am trying to use django-leaflet and django-geojson. The model for the shapes is: #models.py ... from django.contrib.gis.db import models as gismodels ... class MushroomShape(gismodels.Model): name = models.CharField(max_length=256) geom = gismodels.PolygonField() objects = gismodels.GeoManager() def __unicode__(self): return self.name def __str__(self): return self.name I'm trying to create the polygon shapes in the admin, using a leaflet widget, to be added to the Database: #admin.py ... from leaflet.admin import LeafletGeoAdmin from .models import MushroomShape ... admin.site.register(MushroomShape, LeafletGeoAdmin) Running the server in my computer, when I draw a polygon in the admin form and try to submit it: The client side reports "Invalid geometry value." and the server side reports: Error creating geometry from value '{"type":"Polygon","coordinates":[[[-87.58575439453125,41.83375828633243],[-87.58575439453125,42.002366213375524],[-86.74942016601562,42.002366213375524],[-86.74942016601562,41.83375828633243],[-87.58575439453125,41.83375828633243]]]}' (Initializing geometry from JSON input requires GDAL.) A little push to help understand where I have to look, to solve this error, would be really awesome. -
A Django field consisting of several fields
I want a "composite" Django fields which corresponds to two (rather than one) database columns. In fact the composite field should consist of two ForeignKey fields. Otherwise it should behave like a normal field. For example it can be used in a form to input data. It seems that Django 1.10.1 does not support this. I may try to write a patch. Any advice? -
Django - queryset disappears after update command
I have a simple Django command like so: order_qs_by_vendor.update(status_id = 2) After this command, the querysets becomes empty ! I am just lost. And can't find any hint in documentation. Can anyone explain what's going on ? -
Using other file names than models.py for Django models?
When creating a reusable app, should I put all models I define into single file models.py or can I group the models into several files like topic1.py, topic2.py? Please describe all reasons pro and contra. -
Django csrf verification fails after switching off https
I am using Django 1.7.1 , I made a single change outside of my django web app , i.e switched off https inside nginx since my django webapp moved within the company firewall. I made no other changes to the webapp , like in any of the django code: I am testing the webapp access via the company vpn. The home page , which is a form loads fine when I go to http://mywebapp.mycompany.com. Now , When I hit submit. I see the CSRF verification failure with a reference to https://mywebapp.mycompany.com! as detailed below. I even get the error in incognito mode to rule out any old cache issues. I wanted to know the source of the error and feel it is outside of my webapp and within some vpn configuration/ browser cache / some other cache. I have checked the possible reasons for CSRF failure given in the django message , and am not doing any of those "bad" things. Any ideas on how to troubleshoot this. I want to know whether this is a VPN config problem , an nginx config problem or a django "best practices" problem. Forbidden (403) CSRF verification failed. Request aborted. Help Reason given … -
Django Official Tutorial Poll: How do you manage Choice in Admin Panel?
The official tutorial (Part 2) makes it easy to add and delete Questions in the admin panel by adding admin.site.register(Question) into admin.py. https://docs.djangoproject.com/en/1.10/intro/tutorial02/ However I am curious how to manage the answers, the Choice object, too. naturally I import and add admin.site.register(Choice) into admin.py. So it works. But I have these concerns: A. Questions and Choice are managed separately. B. In the Choice index menu, it doesnt show which Question (Key) a Choice is assigned to, not unless you click into each of the records to show a drop down menu of Keys you can choose from. I would like to know how: A. to manage Question and Choice in a more hierarchal structure, i.e. you click into a Question item and you can edit not only the Question itself but also the Choices it is affiliated with. B. In the Choice index table menu, is it possible to list another column to show the Key object(Question) to the item? Or if there are any other more intuitive way to do admin management? The official Django tutorial in my opinion isn't really well explained, it took me quite sometime to google around to figure out what is really happening. It … -
Creating a Django model that can have a many-to-many relationship with itself
I'm trying to write a Django model that can have a many-to-many relationship with itself. This is my models.py: class Apps(models.Model): name = models.CharField( verbose_name = 'App Name', max_length = 30 ) logo = models.ImageField( verbose_name = 'Logo' ) description = models.TextField( verbose_name = 'Description' ) google_url = models.URLField( verbose_name = 'Google Play Link', null = True ) apple_url = models.URLField( verbose_name = 'Apple AppStore Link', null = True ) youtube_url = models.URLField( verbose_name = 'Youtube Video Page', null = True ) similar_apps = models.ManyToManyField( 'self', through = 'SimilarApps', related_name = 'similar_apps', verbose_name = 'Similar Apps', help_text = 'Similar Apps', symmetrical = False ) def __unicode__(self): return u'%s' % (self.user.name) class SimilarApps(models.Model): primary = models.ForeignKey( Apps, verbose_name = 'Primary App', related_name = 'primary_app', help_text = 'First of 2 similar Apps.', ) secondary = models.ForeignKey( Apps, verbose_name = 'Matched App', related_name = 'matched_app', help_text = 'Second of 2 similar Apps.', ) When I run manage.py makemigrations I get the following error <class 'appsrfun.admin.SimilarAppsInline'>: (admin.E202) 'appsrfun.SimilarApps' has more than one ForeignKey to 'appsrfun.Apps'. appsrfun.Apps.similar_apps: (fields.E302) Reverse accessor for 'Apps.similar_apps' clashes with field name 'Apps.similar_apps'. HINT: Rename field 'Apps.similar_apps', or add/change a related_name argument to the definition for field 'Apps.similar_apps'. appsrfun.Apps.similar_apps: (fields.E303) Reverse … -
Custom django permissions based on user profile field(s)
I have extended the django User model by adding a company field: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company = models.ForeignKey(Companies, on_delete=models.CASCADE, null=True, blank=True) Now assume another model that holds data across companies: class Product(models.Model): name = models.CharField(max_length=256, null=True, blank=True) tags = TaggableManager(blank=True) company = models.ForeignKey(Companies, on_delete=models.CASCADE, null=True, blank=True, editable = False) Note that the company field here is not editable, as I have overridden save_model(), to get users' company field from their profiles: class ProductAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): if getattr(obj, 'company', None) is None: obj.company = request.user.profile.company obj.save() Sample permissions requirements: Users should only be able to edit product fields related to their own company. Exception: Users from all companies can add/edit the tag product field Users should be able to create new users only with their company in the new user's profile field Thanks in advance -
Django Rest Framework,
Suppose a user has an address as a foreign key A typical PrimaryKeyRelatedField would represent foreign key by id: { id: 3, first_name: eugene, last_name: kim, address: 9 # here 9 is address's id } I'd like to change the default representation of foreign key field changed as in the following example. (Hopefully without me defining serializer for every foreign key field) { id: 3, first_name: eugene, last_name: kim, address: { id: 9 # difference here, } } -
Installing zlib1g-dev in django app on Windows 10
I am having issues installing zlib1g-dev (dependent for pillow). I am using a windows 10. I am getting this error. project>pip install zlib1g-dev Collecting zlib1g-dev Could not find a version that satisfies the requirement zlib1g-dev (from versions: ) No matching distribution found for zlib1g-dev -
Django Unitest: Table doesn't exist
I created a simple test case like this: from unittest import TestCase import user_manager class UserTest(TestCase): def test_register(self): email = "dung7@gmail.com" password = "123456" result, user = user_manager.setup_new_user(email, password) self.assertEqual(result, CodeID.SUCCESS) Then I run the testcase: python manage.py test users And here is the log: Creating test database for alias 'default'... /Users/admin/Projects/MyApp/venv/lib/python2.7/site-packages/django/db/backends/mysql/base.py:112: Warning: Table 'mysql.column_stats' doesn't exist return self.cursor.execute(query, args) Creating test database for alias 'myapp_log'... .FE ====================================================================== ERROR: test_register (users.tests.UserTest) ---------------------------------------------------------------------- Traceback (most recent call last): ... ProgrammingError: (1146, "Table 'test_myapp.user' doesn't exist") So it created a test database but seem like it didn't create the tables. Here is my DATABASES setting: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "myapp", 'USER': "root", 'PASSWORD': "", 'HOST': '127.0.0.1', 'PORT': '', }, 'myapp_log': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "myapp_log", 'USER': "root", 'PASSWORD': "", 'HOST': '127.0.0.1', 'PORT': '', }, } And my model: class User(BaseModel): uid = models.IntegerField(primary_key=True) email = models.CharField(max_length=200) password = models.CharField(max_length=200) create_time = models.IntegerField() update_time = models.IntegerField() status = models.IntegerField() social_token = models.CharField(max_length=200) social_app = models.IntegerField() class Meta: db_table = 'user' Anyone know why the table 'user' is not created? -
Django - Delay in creating database entry
I have a Django app where I create a db entry in the view. I then want to perform background processing on the new entry. Instead of sending the created object to the task, I send the object's id then the background task can fetch the db object as explained here. Below is my code: # In tasks.py @shared_task def my_task(model_id): my_model = MyModel.objects.get(pk=model_id) # Do stuff with my_model # In views.py: def some_view(request): if request.method == 'POST' and request.is_ajax(): instance = MyModel.objects.create(**kwargs) tasks.my_task.delay(instance.id) .... However, when I try to get the object in the background task, I get matching query does not exist error. If I add sleep(1) before getting the object, it works as excepted. I do not understand why I'm getting this error, since the object should be in the DB? Does anybody know how to solve this? I don't really want to add a sleep command everywhere. I'm using Postgres as my DB. -
submit one of multiple forms on one page sharing the same action
I have a django project which renders a page with a timeline that contains stories. Each story has a comment text input to add comments. each text input has an id of the comment number as <input type="text" id="comment-{{comment.id}}-{{story.id}}> I want to use jQuery Ajax calls to submit the comments $(document).on('submit', #theId, function() { e.preventDefault(); $.ajax({...}); }) How can i make select #theId of the submitted form to trigger the Ajax in that case. i can't hard code #theId but i want it to be discovered by the click. or if there is a better way to go about rendering the text input so i can trigger the action separately from the other text inputs. -
How can I select and order items based on a subquery?
I have the following models in Django: class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() country = models.ForeignKey(Country) class Book(models.Model): name = models.CharField(max_length=300) pages = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) rating = models.FloatField() authors = models.ForeignKey(Author) pubdate = models.DateField() How can I get a queryset of Authors sorted by the first time they published a book? In SQL, I could do this using: SELECT * FROM ( SELECT author_id , MIN(pubdate) as date FROM books GROUP BY author_id HAVING MIN(pubdate)) AS first_published JOIN author ON author.id = first_published.author_id LIMIT 15 OFFSET 15 ORDER BY first_published.author_id It's been a while with Django and I haven't been able to figure out how to do this.