Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework mulitplechoicefield - int not iterable
I am beginning to use and implement the Django Rest Framework and I have an issue with the multiple choice field. My variable "CHOICES" looks like the following (('0', 'Read Only'), ('5', 'Operator 1'), ('7', 'Operator 2'), ('100', 'Supervisor 1'), ('102', 'Supervisor 2'), ('255', 'Administrator')) and the line that sets the field looks like access = serializers.MultipleChoiceField(choices=CHOICES, allow_blank=False) but I get the following error File "C:\Python27\lib\site-packages\rest_framework\fields.py", line 1348, in to_representation self.choice_strings_to_values.get(six.text_type(item), item) for item in value TypeError: 'int' object is not iterable when going into fields.py and printing the value, it is just a 255 I have tried explicitly iterating the current list and adding the items to a new array, but same problem. What am I missing? -
No input fields in Django when making a form
I'm new to django and I'm trying to create forms, but whenever I run this I end up with a submit button with no input fields. If you see any other mistakes, don't hesitate to tell me. views.py from django.shortcuts import render from django.http import HttpResponse from .forms import * def form(request): if request.method == 'POST': form = forma(request.POST) if form.is_valid(): return HttpResponseRedirect('index.html') else: form = forma() return render(request, 'action.html', {"form":form}) def action(request): return render(request, 'action.html') **forms.py ** from django import forms class forma(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) index.html <body> <section id = "sec"> <h1>... </h1> <h3> ... </h3> <h4> ... <h4> <a href = "/papas"> <button> ... </button> </a> <p>{{hola}} alo {{darwich}}</p> <form action= "action.html" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> </section> <body> -
Pass argument to django class-based view via url string
I can't find out how to do this in the documentation. I have a view that looks like: from django_datatables_view.base_datatable_view import BaseDatatableView class ListJson(BaseDatatableView): #... Using class from https://bitbucket.org/pigletto/django-datatables-view and my urls url(r'^list/datatable/(?P<model_name>\w+)/$', login_required(views.ListJson.as_view()), name='list_json'), I have tried accessing the model_name with self.kwargs['model_name'] in the view (to no avail) -
How to get datetime as string from mysql database in django model query
I am using below query to get fields from mysql database in django 1.9. event_dict_list = EventsModel.objects.filter(name__icontains = event_name).values('sys_id','name', 'start_date_time', 'end_date_time', 'notes') now in the result event_dict_list, start_date_time and end_date_time are appearing in python date time object format as below 'end_date_time': datetime.datetime(2016, 9, 26, 10, 48, 35, tzinfo=<UTC>) I want it as a string in YYYY-mm-dd HH:MM:SS format. One way would be to iterate over the event_dict_list and get date field and then convert it into desired string format. But I wanted to know if there is any way I can specify something in query so that I get the converted date in query output only? Related question - what is preferred way to store date/datetime in database - as python date time or as string. Way 1 or way 2. (1) end_date_time = models.DateTimeField(null=False, blank=False) (2) end_date_time = models.CharField(max_length= 128, null=False, blank=False) -
Random net::ERR_CONNECTION_REFUSED
I'm serving a web application with Google Cloud Container Engine which use Kubernetes. I have a pod with a container running nginx and an other container running a django application with gunicorn. My issue is I keep having net::ERR_CONNECTION_REFUSED on random requests without being able to figure why and when it appends. Do you know what can cause net::ERR_CONNECTION_REFUSED issues ? Thank you for any help. -
Why is adding routes for static files recommended in development?
I have a little project using some static files in my applications and everything works fine. But in development, it seems recommended to add something like this : urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) In my urls.py. But in development (DEBUG=True), runserver seems able to serve static files even if I don't run collectstatic. So I assume it serves it directly from the statics application's subdirectories. So why is recommended to add a static() call to the urls.py file if we can do without it? Plus static() won't work with DEBUG=False anyway. -
POST requests error for Django many-to-many models
I'm receiving the following error when trying to make a POST request to create a particular model within the sqlite3 database: "<Article>" needs to have a value for field "article" before this many-to-many relationship can be used. I'm building a REST API using the Django REST Framework and I have two models with a many-to-many relationship as follows: class Publication(models.Model): title = models.CharField(max_length=30) class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) The corresponding extract in views.py for an Article is as follows: class ArticleList(mixins.ListModelMixin, mixins.CreateModelMixin): queryset = Publication.objects.all() serializer_class = PublicationSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) I'm assuming the issue is that the article doesn't get saved before the POST request is finished as I'm able to perform all CRUD operations fine using Django's database API. What's the best approach to solving this issue? -
How do i verify user in database in google appengine app ( can anyone recommend the best way to do user authentication for google appengine app)?
I have following code in models.py i can sort database by only key but not by string ? from google.appengine.ext import ndb class Roles(ndb.Model): name = ndb.StringProperty() owner = ndb.KeyProperty(kind='User') created = ndb.DateTimeProperty(required=True, auto_now_add = True) class RESTMeta: user_owner_property = 'owner' include_output_properties = ['name'] class Users(ndb.Model): name = ndb.StringProperty() email = ndb.StringProperty() password = ndb.StringProperty() roles = ndb.KeyProperty(kind='Roles') owner = ndb.KeyProperty(kind='User') created = ndb.DateTimeProperty(required=True, auto_now_add = True) class RESTMeta: user_owner_property = 'owner' include_output_properties = ['name'] And the following in api.py app = webapp2.WSGIApplication([ RESTHandler( '/api/roles', # The base URL for this model's endpoints models.Roles, # The model to wrap permissions={ 'GET': PERMISSION_ANYONE, 'POST': PERMISSION_ANYONE, 'PUT': PERMISSION_OWNER_USER, 'DELETE': PERMISSION_ADMIN }, # Will be called for every PUT, right before the model is saved (also supports callbacks for GET/POST/DELETE) put_callback=lambda model, data: model ), RESTHandler( '/api/users', # The base URL for this model's endpoints models.Users, # The model to wrap permissions={ 'GET': PERMISSION_ANYONE, 'POST': PERMISSION_ANYONE, 'PUT': PERMISSION_OWNER_USER, 'DELETE': PERMISSION_ADMIN }, # Will be called for every PUT, right before the model is saved (also supports callbacks for GET/POST/DELETE) put_callback=lambda model, data: model )],debug=True, config = config) I can successfully get by key in api\users?q=roles=key('key') How do i get specific user by String … -
How to configure Django settings for different environments in a modular way?
I have already searched on the web on this doubt, but they don't really seem to apply to my case. I have 3 different config files - Dev, Staging, Prod (of course) I want to modularize settings properly without repetition. So, I have made base_settings.py and I am importing it to dev_settings.py, stg_settings.py etc. Problem - How to invoke the scripts on each env properly with minimal changes? Right now, I'm doing this (taking dev env as an example)- python manage.py runserver --settings=core.dev_settings This works so far, but I am not convinced on how good workaround is this. Because wsgi.py and a couple of other services have - os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') I am looking to do something without changing the config files of other services. Thank you everyone in advance. PS - I've tried to be as clear as possible, but please excuse me if anything is unclear. -
A numbered list with some equal positions in a Django template?
In my Django template I have a chart built from a QuerySet, ordered descending by score, something like this (omitting any HTML tags): {% for player in players %} {{ forloop.counter }}. {{ player.name }} ({{ player.score }}) {% endfor %} However, if adjacent players have equal scores, I want their positions to be the same, i.e.: 1. Bob (100) 2=. Thelma (95) 2=. Terry (95) 4. Audrey (90) Am I right in thinking there's no way to do this using Django's standard template tags (I'm not using Jinja)? Would the best way be to loop through the QuerySet in the view (or wherever it comes from) and calculate these positions there, adding them to each item before they get to the template? -
Restrict access virtual URI by IP address
I'm trying to get a Django application running on my shared web server (hosted with DreamHost). There's one interface I'd like to lock down based on a white-list of IP addresses, but I'm having trouble figuring out how to do it. This interface lives at a virtual URL (in other words, there are no physical files on the server that correspond to the URL; the Django internals serve up the right thing based on the URL passed in). My shared host uses Apache as the web server, which then passes all necessary requests to Passenger. I currently have an .htaccess file with the following contents in the root of my site: SetEnvIf Request_URI ^/manage require_auth=true AuthUserFile /home/myuser/.htpasswd AuthName "Who Goes There?" AuthType Basic order deny,allow deny from all Satisfy any Require user my_web_user Allow from env=!require_auth When I visit the /manage URL at my site, I get prompted for credentials just like I would expect. Visiting any other URL doesn't prompt me, so this rule set seems to work. However, I can't figure out how to add the IP address white list into the mix. I'm aware that the Satisfy any directive is essentially a logical OR of the statements … -
Base64 Encoded URL Parameter "+" Missing in Django HTTP GET
I have sent an GET WSGIRequest to django server with an Base64 encoded parameter. The encoded parameter has a "+" character inside. Django 1.9.6 gets the url correctly, but when it builds the url into GET QueryDict, the parameter is incorrectly built: the "+" is replaced with SPACE. Is this possibly a bug of Django, or it intentionally parsed the parameter this way? Is there any solution please? A screenshot is provided here for your better reference. Screenshot of IDE Debuger -
Should I try using OOP when building a PHP website?
I recently tried out Django/Python and noticed it pretty much forces you into making your web application object oriented. Is this the best way to web program? Or is it just like a style choice thing? -
Couldn't import Django, even when I activate virtualenv
Error I tried to run Django app using virtualevn. But I always get the above error. How to run the app?? -
error passing more that one parameter
Hi everyone I have this in my URLS.py file url(r'^cpuProjects/(?P<project_name>[a-zA-Z0-9]+([,][a-zA-Z0-9]+)?)$', views.findProjectbyname, name='findProjectbyname'), And work perfectly, now I want to add other parameter to this url and call to other function in my view. #url(r'^cpuProjects/(?P<project_name>[a-zA-Z0-9]+([,][a-zA-Z0-9]+)?)/(?P<status>[a-zA-Z0-9]+)$', views.findProjectbytype, name='findProjectbytype'), my function in the view is like this def findProjectbytype(request, project_name, status): pass any idea why I receive this error. AttributeError: 'module' object has no attribute 'findProjectbytype' Thanks in advance! -
DB Design for a show tracker
I'm designing a page which will allow me to track my TV shows. I got the DB models down, but there's one thing which I'm not sure of. I want it so that if a user has watched an episode, they can just mark the episode as watched, but I don't know if it should be a ForeignKey/ManyToMany or what due to the fact that some users can have the episode watched, others don't.. :\ Does anyone have any suggestions for this problem? I'm thinking of making a new model, called episodeWatched but it's not very efficient to duplicate a model just simply for this.. -
403 CSRF errors when trying to login to Django Admin over an SSH tunnel
I am trying to login to the admin panel of a Django application via another server (say 123.123.123.123). I have a ssh tunnel open like ssh -L 3000:my.website.com:443 user@123.123.123.123. I can then go to https://localhost:3000/admin/login/ and see the login page for the Django admin of the server running on my.website.com. Whatever credentials I put in, results in a HTTP 403 'CSRF verification failed. Request aborted.` error page. I do not get this error when going directly to my.website.com/admin/login/. What settings might help to allow login via an SSH tunnel? I have already tried adding 'localhost' to ALLOWED_HOSTS. The CSRF cookies are secure (only available via HTTPS, which I'm always using) and have the HTTPOnly flag set. -
Authenicating static files with WSGI
To authenticate users before accessing some static files I am using the wsgi Authentication from django.contrib.auth.handlers.modwsgi import check_password. This causes the user to be prompted with a drop down login. I want users who already are logged in with csrf token to be given access instead of being re-prompted for a password. -
How to make an HTTP request into an application within an opened session? (Django/Python)
Here's the deal: I've modified an open-source platform API to retrieve some information I needed (some basic info of registered users to create a user profile page). The user must be authenticated to use it. I need to make a request to the API to retrieve that info, but how do I do it within that session? I'm using Python's request method into my page, but apparently it creates a new session, since I'm getting 401 errors whenever I use it. -
How setup gunicorn to read custom settings with systemd
I migrated a server I had to Ubuntu 16.04 and systemd replaced upstart. I have three developing environments: Production, Staging and Development. Only the latter one uses a local database, the other two use a remote one. So, in order to handle the deployment and the service I managed to create the following systemd service file: [Unit] Description=Gunicorn service for Project After=network.target [Service] User=projuser WorkingDirectory=/home/projuser/sites/Project/source ExecStartPre=/usr/bin/env DJANGO_SETTINGS_MODULE=v3.settings_staging ExecStart=/home/projuser/sites/Project/env/bin/gunicorn --bind 127.0.0.1:8090 --workers 6 --access-logfile ../access.log --error-logfile ../error.log v3.wsgi:application [Install] WantedBy=multi-user.target The service starts, but it seems to ignore this line: ExecStartPre=/usr/bin/env DJANGO_SETTINGS_MODULE=v3.settings_staging. I can see in the logs the following: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Mostly because it is using my default settings.py file, which I use for development. How can I make sure it loads the staging settings.py file? -
How to test React/Django app
I have an app that is based on front-end on React and on back-end with Django. Which approach is proper to test that kind of app? Of course I mean functional tests. Standard Selenium for Python or something more sophisticated (especially for React)? -
Django(X)Admin base has_delete_permission on current updateView of object
I am working on absence overview/request module in django-xAdmin. In the update view of an object I want to be able to show or hide the delete button based on the current object and the request.user's permission. I want to be able to determine if the user will see the button in the has_delete_permission method. If the object's booleanField approved is True, and the user has no permission to modify objects which have the field approved=True, the method has_delete_permission must return False - which results in the button being hidden. However, I have no object to work within has_delete_permission. The parameter obj is available (as far as I know) when the user actually submitted the delete request. How can I access the current object which I am updating? As an alternative I could get the PK from the request, and get the object manually to work with. But that does not feel very clean. Any tips or suggestions how to approach my issue? Thank you. -
CSS not linking to HTML
I have a HTML file and a CSS file in the same directory, but when I run the project, the CSS is not loaded and just the HTML appears. Below is the HTML code: <link rel="stylesheet" type="text/css" href="/afc/Templates/afc/afc.css"> I tried using just the filename, it works if I just load that particular page but when I run the project, CSS does not get loaded. <link rel="stylesheet" type="text/css" href="afc.css"> I also tried loading using CTRL+F5 to reload without cache, but didn't work. EDIT: I am getting this on the terminal: Not Found: /afc/afc.css [11/Oct/2016 18:55:30] "GET /afc/afc.css HTTP/1.1" 404 2853 I am using Django. -
gcloud.exceptions.Forbidden: 403 Missing or insufficient permissions
I am a new to Google Cloud Platform. I have setup a Google VM Instance. I am facing an authentication issue on Local Machine while running the command: python manage.py makemigrations Can you please suggest some tips/steps to resolve the same ? Error Trace File "/constants.py", line 18, in <module> table_data = datastore_fetch(project_id, entity_kind) File "/datastore_helper.py", line 23, in datastore_fetch results = list(query.fetch()) File "/venv/local/lib/python2.7/site-packages/gcloud/datastore/query.py", line 463, in __iter__ self.next_page() File "/venv/local/lib/python2.7/site-packages/gcloud/datastore/query.py", line 434, in next_page transaction_id=transaction and transaction.id, File "/venv/local/lib/python2.7/site-packages/gcloud/datastore/connection.py", line 286, in run_query _datastore_pb2.RunQueryResponse) File "/venv/local/lib/python2.7/site-packages/gcloud/datastore/connection.py", line 124, in _rpc data=request_pb.SerializeToString()) File "/venv/local/lib/python2.7/site-packages/gcloud/datastore/connection.py", line 98, in _request raise make_exception(headers, error_status.message, use_json=False) gcloud.exceptions.Forbidden: 403 Missing or insufficient permissions. Other Info: gcloud auth list Credentialed Accounts: - user_account@gmail.com ACTIVE To set the active account, run: $ gcloud config set account `ACCOUNT` gcloud config list Your active configuration is: [default] [core] account = user_account@gmail.com disable_usage_reporting = True project = user_project Input: (Standalone Python Function) from gcloud import datastore project_id = settings.GOOGLE_PROJECT_ID client = datastore.Client(project_id) print(vars(client.connection.credentials)) Output: {'scopes': set([]), 'revoke_uri': 'https://accounts.google.com/o/oauth2/revoke', 'access_token': None, 'token_uri': 'https://www.googleapis.com/oauth2/v4/token', 'token_info_uri': None, 'token_response': None, 'invalid': False, 'refresh_token': u'1/t-V_pZicXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 'client_id': u'3XXXXXXXX9.apps.googleusercontent.com', 'id_token': None, 'client_secret': u'ZXXXXXXXXXXXXXXXXXXX2', 'token_expiry': None, 'store': None, 'user_agent': 'Python client library'} VM Details Firewalls Allow HTTP … -
Django request.session is not passed to the next view
I am working with Django and I need to send data through request.session. I have two simple views : One that computes and displays the results to the user One that saves the informations once the user has hit the "Validate" button Here they are : def import_trunk_con(request) : request.session.flush() trunks = [] connections =[] if request.method == 'POST': form = ExcelFileForm(request.POST, request.FILES) print(form.errors) if form.is_valid(): [trunks, connections] = handle_trunk_file(request.FILES['excel_import_file']) else: form = ExcelFileForm() context = { 'form': form, 'trunk_list' : trunks, 'connection_list' : connections } request.session['import_trunks'] = trunks request.session['import_connections'] = connections print(request.session['import_trunks']) #Prints the right result print(request.session['import_connections']) #Prints the right result template = loader.get_template('confWeb/import/import_trunk_con.html') return HttpResponse(template.render(context, request)) And def import_recap_trunks(request): print('import_trunks' in request.session) #Result is False print('import_connections' in request.session) #Result is False if 'import_trunks' in request.session and 'import_connections' in request.session : print(request.session['import_trunks']) #Do some stuff with what's inside the session del request.session['import_trunks'] del request.session['import_connections'] The problem is that it is correctly stored in the session before trying to access the second view, but when we enter the second view, it's as if the session has been flushed. I also realize that maybe I shouldn't use request.session for doing this, as I pass pretty big JSON objects. Maybe it's the …