Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django circular import and model issue
I have 2 Django models.py in two 2 different apps. processor app models.py from address.models import Address ...defining clasess class Displayble(models.Model): # It has no DB fields address app models.py from processor.models import Displayable class Address(models.Model, Displayble): ...some fields, stored in DB Is moving Dispalyble class to another file is the only option to resolve this dependency? -
Django Session Management
I am creating a Django based web application. I want to learn how to manage session in that. I browsed several tutorials but not got appropriate reference. I have 3 urls in my urls.py with 3 seperate function to handle it. 1. Login (login.html with login function) 2. Homepage (homepage.html with homepage function) 3. Logout (logout.html). I able to create session on Login page successfully once credential has been verified but I am not able to redirect it perfectly on Homepage and homepage function. So Logout button, on homepage not able to work perfectly. So in sort I want to know how to redirect pages with functional calls, not only HTML page. So homepage function also can work. -
Django - Get Session Username & Passowrd for Paramiko SSH access
I have a web framework built in Django which uses Paramiko Python Library to create ssh sessions across a number of hosts. I am using LDAP Authentication for the unix username and password upon login and I want to access the username & password details to create the ssh session. The username I can get but the password is encryped, is there a solution to decrypt and pass this value onto the ssh session? Get User: def view(request): if request.user.is_authenticated(): user = request.user # do something with user SSH Session import paramiko, datetime, time from django.contrib import messages import sys, os today = datetime.date.today() todaystr = today.isoformat() hostname = "hostname.com" password = "password" username = "username" -
how can show image in html wih python django?
I save path of image in database like 'Image/upload/imageOne.jpg' and Image folder in static directory then i want to show this image in html with this tag: <img src="{% static '{{ product.productImagePath }}' %}" alt="{{ product.productName }}" width="800px" height="300px"> but i have error and can not find path and just show alt how can fix it? Thanks for help -
FontAwesome in Flask-assets
I have Django app. Earlier static files was put in 'static/css', and font awesome dir too. |---static |---js |---img |---css |---mine.css and another css files |---font-awesome-4.7.0 |---css |---font-awesome.css |---font-awesome.min.css |---fonts |---scss |---less Now all css files are composing in packed.css by assets.py All is ok, but I can't turn on font awesome symbols. My assets.py from flask_assets import Environment, Bundle from config import app bundles = { 'packed_js': Bundle( 'js/01.jc', 'js/02.jc', filters='jsmin', output='gen/packed.js'), 'packed_css': Bundle( 'css/01.css', 'css/02.css', 'css/font-awesome-4.7.0/css/font-awesome.css', 'css/font-awesome-4.7.0/css/font-awesome.min.css', filters='cssmin', output='gen/packed.css') } assets = Environment(app) assets.register(bundles) Base page contains: {% assets "packed_css" %} <link href="{{ ASSET_URL}}" media="screen" rel="stylesheet" /> {% endassets %} {% assets "packed_js" %} <script type="text/javascript" src="{{ ASSET_URL }}"></script> {% endassets %} Why font awesome symbols disappear now? What am I missing here? -
django tries to insert duplicate key while forceUpdate == True
When updating a table using an object retrieved with get_or_create, I explicitly set the forceUpdate-flag to True and I still get an "Violation of PRIMARY KEY constraint - Cannot insert duplicate key" error. Any ideas? The model is: class Teamcorrections(models.Model): contestid = models.ForeignKey(Teamcontests, models.DO_NOTHING, db_column='ContestID', primary_key=True) # Field name made lowercase. teamid = models.ForeignKey(Team, models.DO_NOTHING, db_column='TeamID') # Field name made lowercase. round = models.IntegerField(db_column='Round') # Field name made lowercase. vpcorrection = models.DecimalField(db_column='VPcorrection', max_digits=6, decimal_places=2) # Field name made lowercase. impscorrection = models.IntegerField(db_column='IMPScorrection') # Field name made lowercase. This has been auto-generated from an existing database I have to work with. My code: def savehandicap(request,contestId,nRound): oTeamResults=Teamresults.objects.filter(contestid=contestId,round=nRound,hometeam=1 ).all() for result in oTeamResults: [ht,created]=Teamcorrections.objects.get_or_create(contestid_id=contestId,teamid_id=result.teamid_id,round=nRound) ht.impscorrection = result.handicap if created: print ('new ht') ht.save(force_insert=True) else: print ('upd ht') ht.save(force_update=True) I reach the "force_update" line and still get the error... Any hints and help appreciated... -
Django REST Framework: Validate Serialiser List Update (PUT) with no pk and UNIQUE index on two fields
I have spent a few days on this and have read around the houses (i have rtfm several times... perhaps I have not understood tfm though). Come close to a few answers and I fear that in the end it is my knowledge of how Django / Serilizers (sic) work that is the problem. I will start with my base problem to keep things simple, rather than any of the numerous attempts I have made to get this working. I am attempting to do the following: (working) GET a list of values from a Django rest_framework API based on a dual index, one field of which is passed in the URL (control_sys) and multiple values of a second field is passed in (JSON) data submitted to the API (transactionID). (not working) Update (PUT) a list of values based on the same logic as the GET (above). (haven't got this far) Create (POST) a list of values based on the same logic as the GET(above). As indicated, the GET statement is working. The view is retrieving a queryset based on a list of transactionIDs and the control_sys (sysID) passed in the URL. It is passing this to the serialiser and returning … -
Improve end-point Django Rest Framework
I created a new end-point for an API (Django Rest Framework) that generates a PDF from a HTML template. I follow the example form the plugin django-easy-pdf Is working but I would like to improve and to know what could be done in a better way. urls.py url(r'^demo/$', api.DemoPDFView.as_view()), views.py class DemoPDFView(PDFTemplateView): template_name = 'reports/asset.html' pdf_filename = 'asset.pdf' def get_context_data(self, **kwargs): Asset = 5 asset = Asset.objects.get(id=Asset) project = asset.project.name id = asset.id name = asset.title return super(DemoPDFView, self).get_context_data( pagesize='A4', title='Asset', project=project, name=name, id=id, **kwargs ) First thing I would to improve, when I make GET call I always receive: [26/May/2017 14:00:49] "GET /api/demo HTTP/1.1" 301 0 [26/May/2017 14:00:50] "GET /api/demo/ HTTP/1.1" 200 442068 Why I got a 301 (Redirect) first ? Second thing I think I must improve is the Generated file. The name is always Download.pdf -
Using django rest API from inside a webapp
I setup a restful api similar to this (which code I took from someone else). This is simplified version. urls.py url(r'^v1/game/(?P\d+?)$', GameAPIDelete.as_view(), name="gameDelete"), class GameAPIDelete(DestroyAPIView): def delete(self, request, pk): object.delete() return Response(data={'result': "OK"}, status=200) For all practical purposes this works fine from an API standpoint...Now what I am trying t figure out how to do. I want to use the same structure (class GameAPIDelete and url) , inside a webapp. The problem is This class will only respond to DELETE requests. The browser sends a POST request. I am looking for options 1) use Jquery and form the http reponse with a DELETE request (this would work.. I believe) 2) Use a something other than DestroyAPIView. which would accept a POST request and then set something on the button to identify it's a delete and delete the object. But this then defeats the purpose of the DestroyAPIView for use when I can send DELETE request (ie when javascript is used to construct the HTTP request) The idea is to only have access to the data via the API and use django's tools to get the job done. Also use the API calls on the webapp as well as the mobile … -
Python regex to match SQL INSERT statements
I am working on a django website, and I am trying to use the data dumped from a legacy database to create YAML fixtures for django. I am writing a crude SQL parser using regex (I know, I know .. but I can't find anything that will help me do this quickly, so I have to "roll my own" - unless there are better suggestions). Part of the "rolling my own" solution is to parse the SQL statements - these are autogenerated, so the format of the statements will not change. Here are two sample INSERT statements: INSERT INTO ref_geographic_region (continent_id,name) VALUES(8,'Europe (Western)'); INSERT INTO ref_currency_group (name) VALUES('Major'); I want to grok the SQL statements into the following pattern: INSERT INTO <table_name> VALUES (one_or_more_alphanums_separated_by_comma); I then need to match the following values: table_name one_or_more_alphanums_separated_by_comma Here is my regex pattern. It is matching, but the grouping is not quite what I want. pattern_string = r"INSERT INTO ([a-zA-Z\_]+)\s\(((([a-zA-Z\_]+)(\,)*)+)\)\s+VALUES\(([0-9]*)|([a-zA-Z\(\)']+)(\,)*\;" How I can modify (and simplify) the pattern above, so it matches only the tokens I'm interested in? -
asyncio on django RuntimeError: Task <Task pending coro=<future_timer() running got Future <Future pending> attached to a different loop
Task on asyncio running with command line on django. I have setup celery and celery is calling function to create loop on asyncio and it is calling to function which is having await of asyncio but it gives following error. yield self # This tells Task to wait for completion. RuntimeError: Task > got Future attached to a different loop. I am running django with python3 on wsgi and celery on daemon process. Following is code example. import asyncio import datetime @asyncio.coroutine def slow_operation(name, sec): message = '%s started at %s' % (name, datetime.datetime.now()) print(message) yield from asyncio.sleep(sec) return '%s ended at %s after %s seconds' % (name, datetime.datetime.now(), sec) def got_result(future): print(future.result()) def run_process(name, sec): task = loop.create_task(slow_operation(name, sec)) task.add_done_callback(got_result) loop = asyncio.get_event_loop() i = [{'name': 'First Process', 'sec': 7}, {'name': 'Second Process', 'sec': 3}, {'name': 'Third Process', 'sec': 10}, {'name': 'Fourth Process', 'sec': 2}, {'name': 'Fifth Process', 'sec': 2}] for val in i: run_process(val['name'], val['sec']) loop.run_forever() Here i am calling following part from different function as follow. def create_asyncio_future_tasks(): loop = asyncio.get_event_loop() i = [{'name': 'First Process', 'sec': 7}, {'name': 'Second Process', 'sec': 3}, {'name': 'Third Process', 'sec': 10}, {'name': 'Fourth Process', 'sec': 2}, {'name': 'Fifth Process', 'sec': … -
Django - How to create POST with defined ID
I wonder how can I create object POST using users ID. Let's assume that I would like to have such URL /users/{id}/object and I would like to create object for user with defined ID, for example user with ID equals 1. In views I would have something like this - url(r'^users/(?P<myID>[0-9]+)/object/$', views.UserObject) Furthermore my object looks in this way { "id": 2, "id_users": 1, "sth": 123 } My GET: @api_view(['GET', 'POST']) def UserObject(request, myID=None): try: object = Object.objects.get(id=myID) except Object.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = ObjectSerializer(object) return Response(serializer.data) This is my POST which I used to use : elif request.method == 'POST': serializer = ObjectSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) But I don't know where I should define ID of user for whom I would like to create object. In this case ID of user is: "id_users": 1 Any ideas? -
Generate full pdf report based on the search term used for a simple search
I have a 'simple' search in my Django application that produces a list of all hits from the database, matching the search term. I want the user to be able to click a button which will generate a pdf report containing all the information from the hits that are listed in the simple search. Therefore, I was wondering if it's possible to 'store' the queryset that is generated by the search and pass it on to the function that is linked to the button 'Generate PDF report'. The current search.html template: {% extends 'base.html' %} {% block body %} {% if enzyme_list %} <h1>Search Results (matching enzyme terms):</h1> <ul> {% for enzyme in enzyme_list %} <li><a href="{% url 'gts:detail' enzyme.id %}">{{ enzyme.barcode }}, {{ enzyme.enzyme_name }}</a></li> {% endfor %} </ul> <div> <a href="{% url 'gts:pdf_report' %}" class="btn btn-primary">Generate PDF report (WORK IN PROGRESS)</a> </div> {% else %} <h1>No enzyme(s) found matching the specified search term.</h1> {% endif %} {% endblock %} the views.py (both relevant views shown) # The view that is used to generate the initial simplified list (template shown above) class EnzymeList(generic.ListView): context_object_name = 'enzyme_list' template_name = 'gts/search.html' def get_queryset(self): query = self.request.GET.get("q") #queryset_list = Enzymes.objects.filter(barcode='Tt_86') queryset_list = … -
Django Editing Native Register Form
In register.html template if I put {{ form.as_p }} to use native register form it works. But it is very ugly. So I use it as {{ form.username}} {{ form.password1}} But sometimes when an error occurs, I need to check if register form has any errors [example names] {% if form.any_error %} And show the message styled {{ form.errormessage}} or {{ form.errorlist.values}} How to achive this in Django with native form and what are the native form variables let us to do this? -
Django test with pgcrypto failing
I'm using a PostgreSQL database for my Django app with pgcryto extension installed. On the production server I manually create a user and then run CREATE EXTENSION pgcrypto; in order to install the extension. However when I run ./manage.py test it fails because my models are using the EncryptedTextField field from pgcrypto_expressions, the test database that's automatically created does not have the extension installed naturally (since it needs to be enabled explicitly for every database created). How can I 'inject' code / commands between the time Django sets up my test database and begins migrations? Or rather, how can I enable this extension globally in PostgreSQL? -
Does anybody connect Django 1.11 with mongodb?
I tried mongoengine and django-mongodb-engine but it is unsupported. -
coreapi only lists list and read method, even when user is logged
I'm building a Django Rest Framework and want to test the API with coreapi library. I can create an object using coreapi programmatically inside a python script but in command line, I can't create the same object and when I list coreapi endpoints I get a list with only endpoints for reading and listing, even when I add a valid credential. My Schema: { "_type": "document", "_meta": { "url": "http://127.0.0.1:8000/api/schema/", "title": "NEP API" }, "experiments": { "list": { "_type": "link", "url": "/api/experiments/", "action": "get", "fields": [ { "name": "page", "location": "query", "schema": { "_type": "integer", "title": "Page", "description": "A page number within the paginated result set." } } ] }, "create": { "_type": "link", "url": "/api/experiments/", "action": "post", "encoding": "application/json", "fields": [ { "name": "title", "required": true, "location": "form", "schema": { "_type": "string", "title": "Title", "description": "" } }, { "name": "description", "required": true, "location": "form", "schema": { "_type": "string", "title": "Description", "description": "" } }, { "name": "data_acquisition_done", "location": "form", "schema": { "_type": "boolean", "title": "Data acquisition done", "description": "" } }, { "name": "nes_id", "required": true, "location": "form", "schema": { "_type": "integer", "title": "Nes id", "description": "" } }, { "name": "ethics_committee_file", "location": "form", "schema": { "_type": "string", … -
Django static files not served on Heroku production
I have a django web site deployed to Heroku. None of the static or media files are loading when I switch out of debug mode. I have a media folder with images and successfully ran collectstatic and have a static folder with many files. Here is the relevant code: # settings.py MEDIA_URL = '/media/' MEDIA_DIR = 'media' MEDIA_ROOT = join(PROJECT_ROOT, MEDIA_DIR) STATIC_URL = '/static/' STATIC_DIR = 'static' STATIC_ROOT = join(PROJECT_ROOT, STATIC_DIR) # wsgi.py import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sitemoz.settings") from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise application = get_wsgi_application() application = DjangoWhiteNoise(application) -
In python3, after installing mysqlclient, dependancy for MySQLdb persists
I have shifted to python3 and trying to create my web application using django 1.11.1, i.e the latest version. I have virtualenv set up where I have installed all my requirements. As per django-doc, I have opted for the 2nd option i.e installed mysqlclient. Now, when I am trying to migrate my basic django tables, I am getting following error: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/namita/environments/p3_venv/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/home/namita/environments/p3_venv/lib/python3.5/site-packages/django/db/models/base.py", line 124, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/home/namita/environments/p3_venv/lib/python3.5/site-packages/django/db/models/base.py", line 330, in add_to_class value.contribute_to_class(cls, name) File "/home/namita/environments/p3_venv/lib/python3.5/site-packages/django/db/models/options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/home/namita/environments/p3_venv/lib/python3.5/site-packages/django/db/__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/home/namita/environments/p3_venv/lib/python3.5/site-packages/django/db/utils.py", line 211, in __getitem__ backend = load_backend(db['ENGINE']) File "/home/namita/environments/p3_venv/lib/python3.5/site-packages/django/db/utils.py", line 115, in load_backend return import_module('%s.base' % backend_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/namita/environments/p3_venv/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 30, in <module> 'Did you install mysqlclient or MySQL-python?' % e django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'. Did you install mysqlclient or MySQL-python? Did I miss any package ? Plus, when I tried installing mysql-python, it gives ImportError: No module named 'ConfigParser' which is fair as I am using python3. Also I checked the point of … -
How to do right relationships between objects Django
I have two models: Category and Item. Item can have 2 or more categories so I need to have a relationship on categories(maybe one-to-many) from the item I create. But, I also need to fetch that items related to a category(or categories), maybe like this: http://example.com/api/items?category_id=5 Can anyone advice how can I achieve that? Thanks. -
Incrementation in a model doesnt work
I want to increment an attribute of a model recursively. But it does not take the incrementation into account.Here is the code. This part is inside the model function: for objt in CompanyHomePageLogosWaiting.objects.filter(score=2): if self.logo_name==objt.logo_name: if self.test < self.score : num = self.score self.test += 1 #### this is the incrementation if self.test == self.score : objt.score=-1 objt.save() self.test = 0 return num test is an attribute of the model with default=-1. Thanks. -
Why does django create btree indexes on foreign key columns?
Django's makemigrations automatically creates a Btree index for each foreign key defined in the model. This seems strange to me as foreign keys are normally used for equality-based joins and rarely, if ever for sorting. Wouldn't it be better to use Hash index by default in such cases? -
How to get User Data from Github/Facebook in Django social Login?
I have integrated django social-auth for authenticating the users. I want to store user data(profile pic, name etc) in my application. How can i achieve this ? any guidelines please -
I use HTTP Basic Auth in my Django REST application. How can I add authentication to my WebSockets though Channels?
My back end application currently uses HTTP Basic Auth for authentication. I need to add a WebSocket Channel with the Django Channel official plug-in. How would I go about doing this? -
ManyToMany field not getting saved Django
I have an app named billing. Following are models in my app. class ProductType(models.Model): name = models.CharField(max_length=128) unique_id = models.CharField(max_length=128) price = models.DecimalField(max_digits=50,decimal_places=4) class Product(models.Model): type = models.ForeignKey(ProductType,related_name="products") mac_id = models.CharField(max_length=128) product_unique_id = models.CharField(max_length=128) assigned = models.BooleanField(default=False) class BillRecord(models.Model): products = models.ManyToManyField(Product, related_name="billrecords",blank=True) send_sms = models.BooleanField(default=True) send_email = models.BooleanField(default=True) invoice = models.FileField(null=True,blank=True,upload_to='invoices/') def save(self, *args, **kwargs): super(BillRecord, self).save(*args, **kwargs) total_products = Products.objects.filter(assigned=False) self.products.add(*total_products) After saving the BillRecord object and querying the object's products returns me billing.Product.None How can I add products in my save method of BillRecord model.