Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
djangorestframework browsable api: how to show all available endpoints urls?
In djangorestframework, there is a browsable api. But how do I show a user an entire bird's eye view of all the possible API calls that he/she can make? I can only see one at a time right now and the user would have to already know the correct URL beforehand i.e., http://localhost:8000/users http://localhost:8000/books http://localhost:8000/book/1/author Thank you! -
Django Read png image from url then pass it to HttpResponse
I want to to read png image from private url then write it to HttpResponse. I have this view that will get a layer from geoServer as a png image then open it and read it then return it as HttpResponse: def get_layer(request): #this url will return png image url='https://example.com/geoserver/layer/wms?.......' r = requests.get(url) with open(r, "rb") as fp: img = Image.open(fp) return HttpResponse(img) I am getting an error: Exception Type: TypeError Exception Value: invalid file: Response [200] /main/views.py in test1 with open(r, "rb") as fp: ... ▼ Local vars Variable Value r <Response [200]> request <WSGIRequest: GET '/test/'> url 'https://example.com/geoserver/layer/wms?.......' All want I want is get the png file from the url then pass it the the HttpResponse so when one call my view, he/she will get the image only with my Django path. I do not want to save the image locally I just want to assign it to a variable and pass it. I am using: Django 1.11, python3.5. -
Django model's field default function references unmigrated model
I have two models, one with a foreign key to another. It uses a function to give a dynamic default value to the foreign key. A simplified example: class Model_1(models.Model): x = models.PositiveSmallIntegerField(default=0) def __str__(self): return "Model 1" class Model_2(models.Model): model_1 = models.ForeignKey(Model_1, on_delete=models.CASCADE, default=get_model_1) def __str__(self): return "Model 2" get_model_1 does things like initialize Model_1 if necessary, and dynamically add values to it as needed. In it, I need to run a query: Model_1.objects.filter(model_2=None). My problem is with migrations. I originally did this in two steps (as I added the relevant models and fields). First I added Model_1, then migrated, then added the foreign key with the function. The problem is that I have to build this app on a different machine, so I ran makemigrations and migrate. makemigrations completes sucessfully, but migrate gives an error relating to get_model_1 referencing an nonexistant Model_1. psycopg2.ProgrammingError: column webclient_Model_2.model_1_id does not exist. My question is how to do this without any extra work like temporarily replacing the function with a different one for migration then switching back to this one. -
Cant save the data from excel to database in django
I am new to programming. I have uploaded an excel and wanted to save the data in to database. But i m getting various errors when i try to solve it by checking with stackoverflow. Here is my code MY view: def createSchool(request): if request.method == 'POST' and request.FILES['excel']: localvar= kidDetailsForm(request.POST) myfile = request.FILES['excel'] book = xlrd.open_workbook(myfile.name) sheet = book.sheet_by_index(0) for r in range(1, sheet.nrows): if localvar.is_valid(): temp = localvar.save(commit = False) temp.childname = sheet.cell(r,0).value temp.dob = sheet.cell(r,1).value temp.sex = sheet.cell(r,2).value temp.save() return render(request, 'littleStar/createSchool.html') return render(request, 'littleStar/createSchool.html') my form: class kidDetailsForm(forms.Form): class Meta(): model = kidDetails fields = ("childname","dob","sex") my Model: class kidDetails(models.Model): childname= models.CharField(max_length=245) sex = models.CharField(max_length=245) dob = models.DateField(max_length=245) def __str__(self): return self.childname But when i print the form. i see required errors. Is there a way to bypass the form. I would like to upload the excel and save the data to database. Any help would be great and much appreciated, Thanks. -
Django model create expire date
I would like to automatically create an expire date in my model based on the create date. Say 60 days? class Something ( models.Model ): created = models.DateTimeField ( auto_now_add = True ) expires = models.DateTimeField ( ) What is the best way to accomplish this? Thanks! -
InterfaceError when using Celery's pytest plugin
I'm using Celery's pytest plugin when writing integration tests for a Django app. In development, everything works as intended. However, when I run a sample test, I get an InterfaceError whenever my test uses the plugin. Haven't been able to make much headway on it and would love any advice. Sample code: @pytest.mark.django_db def test_does_become_stale_with_no_messages(self, auth_client, periodic_tasks, celery_session_worker, user_factory, message_factory, session_factory): original_time = datetime.now(pytz.timezone('UTC')) - timedelta(minutes=29, seconds=59) user = user_factory(is_bot=False) session = session_factory(time_start=original_time) message = message_factory(session=session, author=user, time=original_time) wait_until(condition=lambda: Session.objects.get(pk=session.id).is_stale, timeout=5) assert Session.objects.get(pk=session.id).is_stale Sample stacktrace: > user = user_factory(is_bot=False) tests/func/questions/test_monitoring_sessions.py:15: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ venv/lib/python3.6/site-packages/factory/base.py:69: in __call__ return cls.create(**kwargs) venv/lib/python3.6/site-packages/factory/base.py:623: in create return cls._generate(True, attrs) venv/lib/python3.6/site-packages/factory/base.py:548: in _generate obj = cls._prepare(create, **attrs) venv/lib/python3.6/site-packages/factory/base.py:523: in _prepare return cls._create(model_class, *args, **kwargs) venv/lib/python3.6/site-packages/factory/django.py:181: in _create return manager.create(*args, **kwargs) venv/lib/python3.6/site-packages/django/db/models/manager.py:82: … -
How to copy a Django Polymorphic object?
Using the django-polymorpic module has been a great way of simplifying object inheritance where a number of subclasses all inherit from, and share several attributes with, a base class. But while almost everything works pretty much like a normal object, the method of wiping out the .pk and calling save() doesn't work? I've tried: o = MyPolymorphicSubTable.objects.first() print(o.pk) # 22 o.pk = None o.save() print(o.pk) # still 22 -- still the same object And also tried: print(o.id) # 22 o.id = None o.save() print(o.id) # still 22 anyone have an answer? -
django.db.utils.ProgrammingError: column *name* does not exist
So, my Django app was working just fine when I used the default sqllite database. I then switched to postgres database for heroku deployment but now nothing works. My model looks like this: class Post(models.Model): name = models.CharField(max_length=15) temperature = models.IntegerField() condition = models.CharField(max_length=20) date = models.DateTimeField() now nothing loads and I get the errors like: django.db.utils.ProgrammingError: column weather_post.name does not exist LINE 1: ... AS "temperature__max" FROM "weather_post" WHERE ("weather_p... -
Django how to save user info in model came though API
I'm making a webapp which is connected with an API. When user authorizes my webapp to use 3rd party API, the API send information relating to user. I want to save that information in my model to use it for future. I'm not sure how to save that information in the model against the user already logged in. Here is my code: views.py: from .models import UserInfo def auth_finish(request): app_session = request.session try: oa_auth = auth_flow(app_session).finish(request.GET) if request.method == 'GET': UserInfo.user = request.user # How to save this model? UserInfo.access_token = oa_auth.access_token # How to save this model? UserInfo.account_id = oa_auth.account_id # How to save this model? UserInfo.dbx_user_id = oa_auth.user_id # How to save this model? return render(request, 'index.html') except oauth.BadRequestException as e: return HttpResponse(e) models.py from django.contrib.auth.models import User class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) access_token = models.CharField(max_length=20, blank=False) account_id = models.CharField(max_length=10, blank=False) dbx_user_id = models.CharField(max_length=10, blank=False) The information is coming to my views correctly and I'm able to build a dictionary with it in the views.py. How can I save this information? def auth_finish(request): app_session = request.session try: oa_auth = auth_flow(app_session).finish(request.GET) user_auth_info = dict() user_auth_info['access_token'] = oa_auth.access_token user_auth_info['account_id'] = oa_auth.account_id user_auth_info['user_id'] = oa_auth.user_id user_auth_info['app_user'] = request.user print(user_auth_info) return … -
Understanding hallo-image plugin
I'm working to extend the wagtailembedvideos adding the properly hallo.js plugin: https://github.com/SalahAdDin/wagtail-embedvideos I have this embed-video-chooser.js: function createEmbedVideoChooser(id) { var chooserElement = $('#' + id + '-chooser'); var previewEmbedVideo = chooserElement.find('.preview-image img'); var input = $('#' + id); var editLink = chooserElement.find('.edit-link'); $('.action-choose', chooserElement).click(function() { ModalWorkflow({ 'url': window.chooserUrls.embedVideoChooser, 'responses': { 'embedVideoChosen': function(embedVideoData) { input.val(embedVideoData.id); previewEmbedVideo.attr({ src: embedVideoData.preview.url, width: embedVideoData.preview.width, height: embedVideoData.preview.height, alt: embedVideoData.title }); chooserElement.removeClass('blank'); editLink.attr('href', embedVideoData.edit_link); } } }); }); $('.action-clear', chooserElement).on('click', function() { input.val(''); chooserElement.addClass('blank'); }); } And this is the plugin: (function() { (function($) { return $.widget('IKS.halloembedvideos', { options: { uuid: '', editable: null }, populateToolbar: function(toolbar) { var button, widget; widget = this; button = $('<span class="' + this.widgetName + '"></span>'); button.hallobutton({ uuid: this.options.uuid, editable: this.options.editable, label: 'Videos', icon: 'icon-media', command: null }); toolbar.append(button); return button.on('click', function(event) { var insertionPoint, lastSelection; lastSelection = widget.options.editable.getSelection(); insertionPoint = $(lastSelection.endContainer).parentsUntil('.richtext').last(); return ModalWorkflow({ url: window.chooserUrls.embedVideoChooser + '?select_format=true', responses: { embedVideoChosen: function(embedVideoData) { var elem; elem = $(embedVideoData.html).get(0); lastSelection.insertNode(elem); if (elem.getAttribute('contenteditable') === 'false') { insertRichTextDeleteControl(elem); } return widget.options.editable.element.trigger('change'); } } }); }); } }); })(jQuery); }).call(this); The button works, the chooser appears and i can upload or select the video, but i'm getting this error: rangy-core.js:33 Uncaught TypeError: Cannot read property … -
Template filter for generating product by category
I have a django project where I am displaying products in the template. I wanted to ask on what is the best possible way of displaying the product by category using some sort of template filter. For instance, on the template if I want to display Breads by category Hovis. At the moment all the products in the database will be displayed. <tr> <td><h5>{{ product.name }}</h5></td> <td><p><strong>{{ product.price }}</strong></p></td> </tr> Thanks in advance. -
How to connect to my heroku database from localhost?
I'm new in django and trying to connect to my heroku database from my localhosted django app. I've followed the instructions on heroku website but it's seems django won't understand that i'm trying to access an external database. i get this error relation "myAppName_user" does not exist LINE 1: INSERT INTO "myAppName_user" ("title", "content") VALUES ('Beat... However i never created or never intented to create a table named myAppName_user I'm just trying to access the table user in my heroku postgres db but i don't know why it tries with myAppName_user i just explicitly added myAppName in the INSTALLED_APPS config as django throws an error if it's not the case. My DATABASE config : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } DATABASES['default'] = dj_database_url.config(default='postgres://xxxxx') I want to test my database from my localhost. I'm doing this easily with Node JS but i can't find the solution in django. Any suggestions ? -
PyCrypto encryption/decryption error client/server and CHIL engine
I have two sides: one or more clients, running Python 2.7.10, Pycrypto 2.6.1 one server, running the same all running on: django 1.11.2, Centos 6.9, OpenSSL 1.0.1e-fips the server holds an HSM-backed private key and the corresponding public key. the clients have the public key at their disposal, and use it to encrypt before sending the encrypted data to the server. Client-side code to encrypt: from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA from Crypto.Hash import SHA256 def encrypt_RSA(public_key_loc, clear_text): key = open(public_key_loc, "r").read() rsakey = RSA.importKey(key) cipher = PKCS1_OAEP.new(rsakey, hashAlgo=SHA256) encrypted = cipher.encrypt(clear_text) return encrypted.encode('base64') Client-side code to send: import json import requests from .crypt import encrypt_RSA r = requests.post( settings.THE_URL, data=json.dumps({ 'text': encrypt_RSA(settings.PUBLIC_KEY, 'clear text'), }), headers={'content-type': 'application/json'}, timeout=5 ) This works -- apparently. When received server-side, the following happens: engine "chil" set. RSA operation error 140648313706312:error:0407106B:rsa routines:RSA_padding_check_PKCS1_type_2:block type is not 02:rsa_pk1.c:190: 140648313706312:error:04065072:rsa routines:RSA_EAY_PRIVATE_DECRYPT:padding check failed:rsa_eay.c:674: This is the code handling decryption, after going through a layer of validators such as django REST framework. def decrypt_RSA_CHIL(private_key_loc, encrypted_text): print private_key_loc print '######### BEFORE ##########' print encrypted_text # using base64 in order to avoid saving byte string to DB (in varchar) encrypted_text = base64.b64decode(encrypted_text) print '######### AFTER ##########' print encrypted_text … -
Django 404 via wsgi.py
I'm using a baremetal server on scaleway and I'm trying to write the first django app from django tutorial. Since I'm using a remote server I can't use manage.py startserver than i trying to use wsgi.py. this is my apache conf file: WSGIScriptAlias /test-app /usr/local/django-apps/testApp/testApp/wsgi.py WSGIPythonPath /usr/local/django-apps/testApp <Directory /usr/local/django-apps/testApp/testApp> <Files wsgi.py> Require all granted </Files> </Directory> the project it's been created with django-admin as the example. If I use curl http://127.0.0.1:8000 from console, I can see "It's works!". I added the server IP (and 127.0.0.1) to ALLOWED_HOST, as suggested the first time I tried to browse http://myserverip/test-app Now curl to loopback still work, but the browser via public IP report: Page not found (404) Request Method: GET Request URL: http://mypublicip/test-app/ Using the URLconf defined in testApp.urls, Django tried these URL patterns, in this order: admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Any suggestion? thanks. -
In the Django REST framework, how are the default permission classes combined with per-view(set) ones?
I'm reading http://www.django-rest-framework.org/api-guide/permissions/ and trying to relate it to the OAuth2 toolkit documentation, http://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html. The latter has an example in which in settings.py one specifies REST_FRAMEWORK = { # ... 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } and in addition, IsAuthenticated is also specified added to the permission_classes list of a ModelViewSet: class UserViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] queryset = User.objects.all() serializer_class = UserSerializer Do I infer correctly from this example that the DEFAULT_PERMISSION_CLASSES are not prepended / postpended to a ModelViewSet's permission classes, but are instead replaced by it? -
Django css isn't working
I have added some bootsstrap to my django template and that works fine - but yet when I add my own css and it doesn't have an effect on the page; no errors are produced. I have a personal web app with a dir static/personal/images/bg01.png The image isn't loading and the ul isn't being put inline. <!DOCTYPE html> <html lang="en"> <head> <title>Deps</title> <meta charset="utf-8" /> {% load staticfiles %} <link rel="stylesheet" href="{% static 'personal/css/bootstrap.min.css' %}" type = "text/css"/> <meta name="viewport" content = "width=device-width, initial-scale=1.0"> <style type="text/css"> html, body { height:100% } background-image:url('{{ STATIC_URL }} personal/images/bg01.png'); li{ display:inline; } </style> </head> <body class="body" style="background-color:#f6f6f6"> <div class="container-fluid" style="min-height:95%; "> <div class="row"> <div class="col-sm-2"> <br> <center> <img src="{% static 'personal/images/bg01.jpg' %}" class="responsive-img" style='max-height:100px;' alt="face"> </center> </div> <div class="col-sm-10"> <br> <center> <h3>Programming, Teaching, Entrepreneurship</h3> </center> </div> </div><hr> <div class="row"> <div class="col-sm-2"> <br> <br> <!-- Great, til you resize. --> <!--<div class="well bs-sidebar affix" id="sidebar" style="background-color:#fff">--> <div class="well bs-sidebar" id="sidebar" style="background-color:#fff"> <ul class="nav nav-pills nav-stacked"> <li><a href='/'>Home</a></li> <li><a href='/blog/'>Blog</a></li> <li><a href='/contact/'>Contact</a></li> </ul> </div> <!--well bs-sidebar affix--> </div> <!--col-sm-2--> <div class="col-sm-10"> <div class='container-fluid'> <ul> <li>1</li> <li>2</li> <li>3</li> </ul> <br><br> {% block content %} {% endblock %} </div> </div> </div> </div> <footer> <div class="container-fluid" style='margin-left:15px'> <p><a href="#" … -
How do I check if queryset is empty for multiple objects in django?
So, my template is receiving an object that has generic foreign key relations with 3 other models and now I need to check if all three of these exist or not to show the user a custom message based on what exists and doesn't exist. Here's some perspective: Person Object has 3 different models attached to it: Address Email Phone If all 3 don't exist, then I want the template to say `No contact details found, you may add new contact info" But, even if either of the three exist, then don't show the message. I tried this: {% if person.address.all and person.email.all and person.phone.all %} <!-- Do something here to show the details of each object --> {% else %} <!-- Show the default message --> {% endif %} But what happens here is that if Address exists, but Phone and Email do not, it'll show the message - which is not what I want. How do I achieve my desired result? Can I check for Null? -
Django Foreign Key select in admin dashboard
Not quite sure how to accomplish this. I have a Post model which references a foreign key to the Category model. class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='feature_posts') body = models.TextField("Body") lead_in = models.CharField("Lead In", max_length=500, default='', blank=True) is_featured = models.BooleanField("Is Featured?", default=False) likes = models.IntegerField(default=0, blank=True) views = models.IntegerField(default=0, blank=True) category = models.ForeignKey('Category', null=True, blank=True) class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() parent = models.ForeignKey('self',blank=True, null=True ,related_name='children') class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "categories" All works as intended pretty nicely, except for this in the admin dashboard: Can anyone give me the pro-tip to avoid this...? It's probably line 1 of the Django admin handbook but I can't for the life of me find line 1! :D Looked through Django 1.11 admin documentation in models, foreignkey fields, admin etc etc but to no luck. N.B. It might be worth noting that I am using wagtail, if there are any subtle differences -
Combining Regex and Django Rest Framework Routing to Detailed Model View
I'm setting up a url using Django Rest Framework viewsets and routers, and I'm trying to get the url to accept two values: first, to filter objects by a user id, and then by the object's id. (In my case, the objects are from a model called Request.) For example, mysite.com/api/requests/1A/ would return all Request objects for user 1A, and mysite.com/api/requests/1A/23/ would return Request object with pk=23 for user 1A. Right now I have: # urls.py from django.conf.urls import url, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'requests/(?P<user_id>.+?)(?=\/)', viewset=views.RequestsByUser, base_name='request') urlpatterns = [ url(r'^', include(router.urls)), ] # views.py class RequestsByUser(viewsets.ModelViewSet): serializer_class = RequestsSerializer def get_queryset(self): u_id = self.kwargs['user_id'] return Request.objects.filter(user_id=u_id) This works well for listing all Request objects when the url is passed in only the user_id. But when I try to go to mysite.com/api/requests/1A/23/, I get an empty returned result. So the url will properly filter by user_id, but won't properly serve the detailed view of an object when given its primary key. (It looks like the proper page for a detailed view, except it's missing the data for the object.) Django debugging says that the following four url patterns are in my URLConf: … -
Error in migrate.py file in Django
I am continuously getting the following error when I try running python manage.py runserver File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax Following other comments I have activated the virtual env and run on Python version 2.7.10 and Django version 1.11.9. Attached below is my manage.py program. #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dataContractCreator.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv). I even tried removing from exc but that still gives me errors. -
Multi-user web application Django
I am looking exploring new architectures for my multi-user web application. Currently I have a base model, for whatever model I want to restrict for belonging to a user: class UserModel(models.Model): owner = models.ForeignKey(User, on_delete=models.DO_NOTHING) class Meta: abstract = True For whatever task on my system, which I manipulate models which descend from UserModel I want to make sure the only data it touches is its own data. What I am doing now is passing around the logged User. But I am looking for a more robust architecture, to avoid some contributor eventually forget about filtering the data (or filling in the correct user). Is there any Django package or technique which is already extensively tested for this pretty common situation? -
How do I pass in a python pandas.Dataframe object as an argument to a celery task?
I would like to pass a pandas dataframe object as an argument to a celery task. Is there a way I can achieve this? I understand that dataframe objects are not JSON serializable and therefore cannot be used as arguments based on my current setup. -
Django password_reset email through app-engine mail api
I'm trying to figure out how to get the built-in password_reset view to leverage appengine's mail api instead. Is this possible? I've got several of my own custom views leveraging appengine's mail api just fine, but the default password_reset view I'm guessing tries to use regular send_mail and expects valid smtp settings. I'd prefer not to put my google user/pass in local_settings.py. Is it possible to override send_mail in password_reset? -
Redirection within Django using Classbased (generic) views
I have created a functional Django (1.11.5) system which allows me to add numerous Bikes to Manufacturer due to the foreign key capabilities. Unfortunately I can't get my head around how I correctly can redirect user to (PrimaryKey) Manufacturer after the user has updated the Bike information. My views uses Class Based Views for deleting, creating, and updating both the Manufacturer and Bikes. Below I have displayed both the views.py and URL.py I have within my App. views.py from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from .models import Manufacturer, Review class ReviewUpdate(UpdateView): model = Bike fields = ['bike_body'] success_url = reverse_lazy('manufacturers:index') URLs.py url(r'bike/(?P<pk>[0-9]+)/$',views.BikeUpdate.as_view(), name="bike-update"), -
Change text in Django / Python and website get down
im editing a Django/Python website, i just want to change the text of one word and upload but the website falls when i change any text. The website is using Amazon Beanstalk and RDS.