Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Empty download file from django view
I am using django 1.11.2 and I want to have view with downloadable file. After click on link the file is downloading but file is empty and instead of png, I recieved empty txt file. def download_file(request, uuid): response = HttpResponse(content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(models.DownloadLink.objects.get(uuid=uuid).download_file.file) response['Content-Length'] = 'http://{}{}'.format(Site.objects.get_current(), models.DownloadLink.objects.get(uuid=uuid).download_file.file.url) return response EDIT: value here response['Content-Length'] is http://127.0.0.1:8000/media/filer_public/49/54/4954a7bb-8ad3-4679-9248-bffc7d186ca8/photo-105221.jpeg -
Using Javascript to insert url into Django template
I made a map application using Mapbox, where a user can click on a feature and a popup shows with details about the feature. I would also like to provide a link in the popup to the DetailView of the object using Javascript, but I'm having trouble generating the anchor tag. So far I have new mapboxgl.Popup() .setLngLat(e.lngLat) .setHTML('<a href="{% url app_name:view pk=foo %}">To Detail View</a>') .addTo(map); But when I try it out on the development server, it gives me a 404 error with a request url of http://127.0.0.1:8000/map/%7B%25%20url%20app_name:view%20pk%3Dfoo%20%25%7D How do I get it to pass the correct url? I've also tried inserting the link into a normal HTML div and I get the same problem. -
Fast moving average computation with Django ORM
We run Postgres 9.6.5 and Django 2.0. We have a Model with fields created_at and value. We need to calculate a 90-day moving average for a certain date_range. This is how we do this: output = [] for offset in range(len(date_range)): output.append( Ticket.objects.filter( created_at__date__range=(date_range[offset]-timezone.timedelta(days=90), date_range[offset]), ).aggregate(Avg('value'))['value__avg'].days ) This uses Avg aggregate function, so it's reasonably fast, however we need one query for every date in date_range. For longer ranges this means a lot of queries. Postgres can do this in a single query. My question is - can we somehow do this in a single query using Django ORM? (I know that I can execute raw SQL with Django ORM, but I wanted to avoid that if possible, that's why I'm asking...) -
Iterate through model instance variables in Django
Consider a model defined as below: class ProblemVerificationModel(CreateUpdateDateModel): problem = models.ForeignKey(Problem, related_name="problem_survey") verifier = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="verified_problem") is_problem_properly_formated = ... # BooleanField some_field = ... #BooleanField some_other_field = ... #BooleanField I need to find sum of all integer-like values (True->1, False->0) of a ProblemVerificationModel model instance. I can add these values by accessing each field using instance.field and add them all. However, I want to know if there is more clean way of doing this. -
Post methods doesn't work in Django 1.8, Python3 TypeError: can't concat bytes to str
When I try to use forms with a POST method, I'm getting a TypeError: can't concat bytes to str. It's not only happening when I use my forms, but when I input login/password for admin panel too. Environment: Request Method: POST Request URL: http://photofresh.site/blog/post_new/ Django Version: 1.8 Python Version: 3.5.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'blog'] Installed Middleware: ['django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response 125. response = middleware_method(request, callback, callback_args, callback_kwargs) File "/usr/local/lib/python3.5/site-packages/django/middleware/csrf.py" in process_view 174. request_csrf_token = request.POST.get('csrfmiddlewaretoken', '') File "/usr/local/lib/python3.5/site-packages/django/core/handlers/wsgi.py" in _get_post 137. self._load_post_and_files() File "/usr/local/lib/python3.5/site-packages/django/http/request.py" in _load_post_and_files 272. self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict() File "/usr/local/lib/python3.5/site-packages/django/http/request.py" in body 233. self._body = self.read() File "/usr/local/lib/python3.5/site-packages/django/http/request.py" in read 292. return self._stream.read(*args, **kwargs) File "/usr/local/lib/python3.5/site-packages/django/core/handlers/wsgi.py" in read 51. result = self.buffer + self._read_limited() Exception Type: TypeError at /blog/post_new/ Exception Value: can't concat bytes to str -
How do I make an object out of a dict in python?
I currently have a dict, where: one_result = {'name':'Acme', 'description': 'Fun time', 'results': {'fun_status': 'Extra', 'fun_title': 'Foo' } } I access the values of this dict in many places in my code and also put many of the results in an array and store it in DB: class Record(models.Model): results = JSONField(default=[], null=True, blank=True) I would like to keep things DRY and make a Python object out of the result, so I can access the attributes directly, instead of via key_names: result.name VS result['name'] Is there a way that I can create an object that is backed by a dict(), and easily serialized/deserialized into JSON in my db? -
Django app and Wordpress page on same VServer but different domains
I have on virtual server with 2 domains configured. One domain should host a wordpress page and the other domain will be a django web application. I did some research, but I am confused. I know that for Wordpress Apache is the way to go. But for Django I often read that Nginx is the best setup. My question is: What is the best practice in terms of web server setup when hosting 2 domains on the same (virtual) server, where one domain hosts a wordpress page and the other domain hosts a django web application? -
Check if the field value was changed in save method
I've got model, which has 'active' field, I'd like to do action if it's value has changed class Good(TimeStampedModel): active = models.BooleanField(default=True) def save(self, **kwargs): #if self has changed: #do_something() super().save(self, **kwargs) -
can we run django applications without virtual environment? how?
I am completely new to Django framework, I want to create Django application without using the virtual environment, is it possible? If yes please explain how? -
Django - registering an Admin model view in one app from another app
I'm slightly confused as how I'm meant to do this, partly because the documentation is translated a little poorly from Chinese, partly because I am just getting my head around class based views. I have the following directory structure: Project manage.py db.sqlite3 /docs /static /templates /main_app __init__.py settings.py urls.py * wsgi.py /apps /xadmin adminx.py * /survey admin.py * And the following URL mappings in main_app.urls: from django.conf.urls import url, include from django.contrib import admin import xadmin xadmin.autodiscover() urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^survey/', include('survey.urls')), url(r'xadmin/', include(xadmin.site.urls)), ] The survey.admin has it's classes, e.g. class SurveyAdmin(admin.ModelAdmin): list_display = ('name', 'is_published', 'need_logged_user', 'template') list_filter = ('is_published', 'need_logged_user') inlines = [CategoryInline, QuestionInline] actions = [make_published] admin.site.register(Survey, SurveyAdmin) I know my Survey app's models are working properly, because when I check db.sql3, I can see my dummy entries in there. When I log into 127.0.0.1:8000/admin, I can see that the SurveyAdmin view is registered and available. When I log into 127.0.0.1:8000/xadmin however, SurveyAdmin isn't registered. From the xadmin docs I get that I have to register admin class views in xadmin.adminx. The admin class views I want to register already exist in survey.admin. I believe all I need to get this working is to … -
django tastypie field filtering using ```and```
In tastypie docs you can do the below subjects = fields.ToManyField(SubjectResource, attribute=lambda bundle: Subject.objects.filter(notes=bundle.obj, name__startswith='Personal')) I'm trying to create an and filter in there. subjects = fields.ToManyField(SubjectResource, attribute=lambda bundle: Subject.objects.filter(notes=bundle.obj, name__startswith='Personal' and date__isnull=False)) If I do. subjects = fields.ToManyField(SubjectResource, attribute=lambda bundle: Subject.objects.filter(notes=bundle.obj, name__startswith='Personal', date__isnull=False)) It creates and or filter. and raises as syntax error. How do I create the and? Cheers -
Saving attachments from Sendgrid Parse
Im using sendgrid parse to send emails to a webhook. This is delivered to a url in my django application. Im not sending the RAW message. This is my view: @csrf_exempt def parse_sendgrid(request): if request.method == "POST": print request.FILES["attachment1"].read() open('tisiscool.jpg', 'wb').write(request.FILES["attachment1"].read()) For some reason, the image is not displaying, like its corrupted? ITs an image I attach to an email, so the image is fine. The content of the image is just gibberish, I thought it would be base64? Is the image encoded or something by SendGrid? -
A method that is called when the databases are updated via the admin panel
the idea is that I will not need to, each time enter some data, the value of which depends on the value of other data. For example. class Example(models.Model): 1_score_team_1 = models.IntegerField() 2_score_team_1 = models.IntegerField() 1_score_team_2 = models.IntegerField() 2_score_team_2 = models.IntegerField() total_score_of_team_1 = models.IntegerField() total_score_of_team_2 = models.IntegerField() def function: total_score_of_team_1 = 1_score_team_1 + 2_score_team_1 total_score_of_team_2 = 1_score_team_2 + 2_score_team_2 return update total score of two teams This method should be called every time I enter data through the admin panel. -
Add an extra total row in admin - Django
admin.py for an app is: from django.contrib import admin from django.db.models import Subquery, Sum, OuterRef from .models import GoodsItem, FinishedGoodsItem, SoldGoodsItem @admin.register(SoldGoodsItem) class SoldGoodsItemAdmin(admin.ModelAdmin): fields = ('date', 'goods_item', 'weight') list_display = ('date', 'goods_item', 'weight') @admin.register(FinishedGoodsItem) class FinishedGoodsItemAdmin(admin.ModelAdmin): fields = ('date', 'goods_item', 'weight') list_display = ('date', 'goods_item', 'weight') @admin.register(GoodsItem) class GoodsItemAdmin(admin.ModelAdmin): list_display = ('__str__', 'finished_good', 'sold_good', 'stock_available') def get_queryset(self, request): qs = super(GoodsItemAdmin, self).get_queryset(request) qs = qs.annotate( finished_good = Subquery(FinishedGoodsItem.objects.filter(goods_item=OuterRef('pk'))\ .values('goods_item_id').annotate(sum=Sum('weight')).values('sum')[:1]), sold_good = Subquery(SoldGoodsItem.objects.filter(goods_item=OuterRef('pk'))\ .values('goods_item_id').annotate(sum=Sum('weight')).values('sum')[:1]) ) return qs def finished_good(self, obj): return obj.finished_good def sold_good(self, obj): return obj.sold_good def stock_available(self, obj): finished_good = 0 if self.finished_good(obj) is None else self.finished_good(obj) sold_good = 0 if self.sold_good(obj) is None else self.sold_good(obj) return '-' if (finished_good == 0 and sold_good == 0) else finished_good - sold_good admin.site.site_header = 'Rajeshwari Steels' For GoodsItemAdmin, I want to display an extra row with the totals at the bottom of the records table. The total row should display the total for all three columns, which are finished_good, sold_good and stock_available. Here all three columns are displayed using methods in GoodsItemAdmin and are annotated on queryset by overriding get_queryset method. I found this question, while searched for the solution. The answers for that question suggest to override admin template … -
Django and mongoengine connection MongoCR Failed authentication
I am using Django 1.9 and mongoengine to connect to my mongo back-end database and having difficulties connecting to the default database. I am doing it this way: DBNAME = 'admin' _MONGODB_USER = 'bobO' _MONGO_PASSWD = '1234' _MONGO_HOST = 'localhost' _MONGODB_NAME = 'test' _MONGO_DATABASE_HOST = \ 'mongodb://%s:%s@%s/%s' \ % (_MONGODB_USER, _MONGO_PASSWD, _MONGO_HOST, _MONGODB_NAME) mongoengine.connect(DBNAME, host=_MONGO_DATABASE_HOST) I am getting this error from pycharm and the mongod cmd: pyCharm raise ConnectionError("Cannot connect to database %s :\n%s" % (alias, e)) mongoengine.connection.ConnectionError: Cannot connect to database default : command SON([('authenticate', 1), ('user', u'johnO'), ('nonce', u'fae6a365d185a4cd'), ('key', u'1ef81a71166f8878a02b3c7c297e2959')]) failed: auth failed CMD-running Mongod Failed to authenticate johnO@test from client 127.0.0.1:56458 with mechanism MONGODB-CR: AuthenticationFailed: MONGODB-CR credentials missing in the user document 2018-02-14T13:45:50.701+0000 I NETWORK [conn4] end connection 127.0.0.1:56458 (1 connection now open) Any guidance on properly connecting them together would be great. I dont seem to understand this MONGODB-CR. Have i missed something crucial on my credentials? I do have an admin database and have created a user. Thanks -
Why is evaluating a Django QuerySet in a Boolean context slower than calling `exists` on it?
So the Django docs state the following: And to find whether a queryset contains any items: if some_queryset.exists(): print("There is at least one object in some_queryset") Which will be faster than: if some_queryset: print("There is at least one object in some_queryset") Why is that though? What good reason is there? Often when evaluating a QuerySet in a Boolean context, all a user cares about is whether there's at least one item which presumably is why exists is faster. Why can't __bool__ on QuerySet simply do the same amount of work as exists? Look at the source code, there seems to be a bit of work involved: def __bool__(self): self._fetch_all() return bool(self._result_cache) But no documentation providing context on why. For me, simply calling if some_queryset: is much cleaner and more Pythonic. -
Need Help: Google Django All-Auth Redirect not working with EC2 AWS in Production
I'm trying to connect the Django All-Auth Google App with the Google credentials for AWS in production. EC2 Gunicorn and Nginx. Google does not accept URLS without a .org or .com. My training program only taught us to deploy Django using the IPv4 Public IP and not the amazonaws.com IP version. Example screenshot: So I got a .org domain from noip.com to point to a public AWS IP but it's not working in production. I've tried every URL in creation and NOTHING is working: http://travelbuddy.hopto.org/accounts/google/login/callback https://travelbuddy.hopto.org/accounts/google/login/callback http://travelbuddy.hopto.org/oauth2callback https://travelbuddy.hopto.org/oauth2callback I was tried to get the code from settings.py on AWS to post here, BUT now the file is read-only for some reason. I can't even edit it. I have wasted countless HOURS and an entire day on this! Help please. -
pip3 install couchdbkit. install failed with "Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-_302m_0e/couchdbkit/"
Unable to install couchdbkit in ubuntu. Command: pip3 install couchdbkit Giving this following error: Collecting couchdbkit Using cached couchdbkit-0.6.5.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 1, in File "/tmp/pip-build-_302m_0e/couchdbkit/setup.py", line 25, in long_description = file( NameError: name 'file' is not defined ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-_302m_0e/couchdbkit/ Please guide me if there any other way to install couchdbkit in ubuntu. -
Django queryset retrieve nothing but the instance exist
I'm facing an issue with Django that I have never seen. When I try to make a query to filter a user the result is empty, but the user really exists. I don't know if Django has some issue when the database is hugue. I don't know how to start to understand how can I fix it. Here is an example copied directly from my shell: In [18]: from django.contrib.auth.models import User In [19]: User.objects.get(pk=22247).email Out[19]: u'person@example.com' In [20]: User.objects.filter(email='person@example.com') Out[20]: [] How can it be possible? Somebody can give some guidance to fix it? Thanks a lot! Usefull data: Im using Python 2.7.14 and Django 1.8.16 Also this bug doesn't happen all the time, sometimes it retrieve the instance correctly but the 80% of the queries retrieve nothing. -
403 Forbidden Angular4-Django
I'm building a website with books using Angular 4 and Django. When the user gets on the landing page (not logged in) he should be able to see a section with the books that were recently added. However, the books aren't loading and in my console I keep getting this error GET http://127.0.0.1:8000/api/books 403 (Forbidden) When the user logs in he's able to see the books just fine. My view in Django (have already imported permissions): class BookList(generics.ListCreateAPIView): permission_classes = (permissions.AllowAny,) serializer_class = BookSerializer def get_queryset(self): queryset = Book.objects.all() category = self.request.query_params.get('category', None) if category is not None: queryset = queryset.filter(category__contains = category) return queryset -
django-simple-captcha always showing invalid capcha in wizardview from django formtools
I am using django-formtools to split the registration form. I have added django-simple-captcha for captcha verification. The captcha is invalid always. I think it is becuase the form field name is '1-captcha_0' in django form wizard. Is there any way to fix this? -
OpenEDX how to complete invisible registration with OAuth?
I'm setting up OpenEDX with specific parameters. First of all, I don't want it to be full open to people, so I've disabled the registration form by setting ALLOW_PUBLIC_ACCOUNT_CREATION to false in lms.env.json. Then I wanted it to only be accessible through my OAuth2 service. I've set up a python module according to this documentation page The login part works fine, but then OpenEDX is stuck to the registration page, because my OAuth2 service doesn't give the user's Country field, which is a mandatory field for OpenEDX. I just want this part to work flawlessly, so here are my questions: Is there a way to remove the "Country" field from the list of the mandatory fields for registration? If there's no way to do so, can my python module give a default country information about the user so the registration completes in an invisible way ? If there's still no way, can I enable the registration form but disable the integrated login form to leave only the OAuth way ? Finally, if none of the solutions above work, what can I do? Thanks in advance for the precious help everyone here is giving! -
Numerical operation with absulute value in Django
I tried to add three different absolute value in my template but I got always 0. I try to explain it: My values: a=-7 b=8 c=10 I tried this method with Django mathfilter: {{a|abs|add:b|abs|add:c|abs}} I always got 0 because I think the mathfilter can't handle many abs value. Could anyone give me an advice which help me to do this operation? Thnak you in advance! -
Path Specific Cookie in Django
i want to create cookie based authentication depends on path , so simply for testing i have create two views and set cookies respectively View 1 Cookie With globalLy available View 2 Cookie With Specific But the problem in both view only global cookie is available View 1 View 2 You can see both cookie have same name but different path, but when we get cookies only global cookie is available if i display request.META.get('HTTP_COOKIE')) then all cookie are display but not in request.COOKIES.get('last_visit') please help, i have tested in php , it works fine but not in python django -
fatal error: portaudio.h: No such file or directory error: command 'gcc' failed with exit status 1
i am using windows 10 and when i am running the commang - git push heroku master getting this erro please solve my problem from 4 days i am searching the solution but didn't get Running setup.py install for PyAudio: started remote: Running setup.py install for PyAudio: finished with status 'error' remote: Complete output from command /app/.heroku/python/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-build-qx34haso/PyAudio/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-mydedmjn-record/install-record.txt --single-version-externally-managed --compile: remote: running install remote: running build remote: running build_py remote: creating build remote: creating build/lib.linux-x86_64-3.6 remote: copying src/pyaudio.py -> build/lib.linux-x86_64-3.6 remote: running build_ext remote: building '_portaudio' extension remote: creating build/temp.linux-x86_64-3.6 remote: creating build/temp.linux-x86_64-3.6/src remote: gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/app/.heroku/python/include/python3.6m -c src/_portaudiomodule.c -o build/temp.linux-x86_64-3.6/src/_portaudiomodule.o remote: src/_portaudiomodule.c:29:23: fatal error: portaudio.h: No such file or directory remote: compilation terminated. remote: error: command 'gcc' failed with exit status 1 remote: remote: ---------------------------------------- remote: Command "/app/.heroku/python/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-build-qx34haso/PyAudio/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-mydedmjn-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-qx34haso/PyAudio/ remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to shoppingwave. remote: To https://git.heroku.com/shoppingwave.git ! …