Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display an html div block differently depending on the extended page using django templatin
I'm building a webpage using the extend templating feature of django. I thus have a base.html where I have search fields that I want to display differently depending on the webpage that is extending base.html. Here are the fields that I want to show: The corresponding code is: <div class="row"> <div class="container-fluid col-md-offset-9 col-md-3"> <a href="../posts/newpost/" class="btn btn-info" role="button"> <span class="glyphicon glyphicon-education" aria-hidden="true"></span> Buton </a> </div> </div> <div class="container-fluid"> <h1 id="Titre" align="center">Title </h1><br> </div> <div class="col-md-12" style="height:100px;"></div> <form class="form-inline text-center" action="{% url 'posts:postsearch' %}" id="form-searchLessons"> <div class="form-group"> <input type="text" class="form-control input-lg" id="typeCours" list="matieres" placeholder="Keyword" name="discipline" autocomplete="off"> </div> <div class="form-group"> <input type="text" class="form-control input-lg" id="Localisation" placeholder="Lieu." name="localisation" onFocus="geolocate()"> </div> <button type="submit" class="btn btn-default btn-lg" id="btn-getLessons"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Trouver ! </button> </form> </div> In case of page1, I want the fields to appear like the image above. Then if I extend base.html from page2, this should like this: Which currently I write a complete different page: <div class="container-fluid"> <div class="row reduced_search-bar"> <div class="col-lg-9"> <form class="form-inline"> <div class="form-group"> <input type="text" class="form-control" id="typeCours" placeholder="Keyword"> </div> <div class="form-group"> <input type="text" class="form-control" id="Localisation" placeholder="Lieu"> </div> <button type="submit" class="btn btn-default"> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> Trouver ! </button> </form> </div> <div class="col-lg-3"> <a href="{% url 'posts:add' … -
Second series not displaying in Highcharts
I am trying to create a graph to display performance of a system. My issue is that Higcharts, for some reason, won't recognize that I have more than one series. The first series displays perfectly, however the second is no where to be seen. I am using Django 1.8 to loop the data from dictionaries. My series code: series: [ {% for ID, run in attDict.items|sort %} { yAxis: 0, id: "Run" + {{forloop.counter}}, name: "RunID " + {{ID}}, color: getLineColor({{ID}}), data: {{run}}, marker: { fillColor: getFillColor({{forloop.counter}}), }, visible: false }, {% endfor %} {% for key, task in TaskE.items|sort %} { yAxis: 1, id: "during", linkedTo: "Run" + {{forloop.counter}}, name: "RunID " + {{key}} type: 'area', color: '#12e000', fillOpacity: 0.3, data: {{task}}, visible: fasle }{% if forloop.last %}{% else %},{% endif %} {% endfor %} ] The output look like this: series: [ { yAxis: 0, id: "Run" + 1, name: "RunID " + 250, color: getLineColor(250), data: [0, 0, 0, 0, 0, 0, 6, 33, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 83, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, … -
Django change dynamically field name in Annotate with a variable
I need to rename output field name with incoming variable value. There is a function: def metric_data(request, test_id, metric): metric_name = metric data = ServerMonitoringData.objects. \ filter(test_id=test_id). \ annotate(timestamp=RawSQL("((data->>%s)::timestamp)", ('timestamp',))).\ annotate(metric=RawSQL("((data->>%s)::numeric)", (metric,))). \ values('timestamp', "metric") So in this case no matter what value comes with the variable metric the output is looking like: {"timestamp": "0:31:02", "metric": "8.82414500398"} I need to have an output with a key names equals to metric variable (if metric == 'CPU_iowait'): {"timestamp": "0:31:02", "CPU_iowait": "8.82414500398"} Tryed to use something like this: metric_name = metric ... annotate(metric_name=F('metric')).\ values('timestamp', metric_name) But it is trying to find 'CPU_iowait' column when exists 'metric_name'. So is there any way to pass field name as a variable ? -
use `SplitArrayField` instead of `SimpleArrayField` in ModelForm
I have model with ArrayField and I want use ModelForm. Django by default use SimpleArrayField but I need SplitArrayField. I get my data from json and I use form only for validation and I don't need input widgets. (I use client side rendering) class Profile(models.Model): phone = ArrayField(CharField(max_length=20, validators=[some_validator])) class ProfileForm(ModelForm): class Meta: model = Profile form = ProfileForm(data={"phone":["555-5555","444-4444"]}) form.validate() How I can use SplitArrayField in ModelForm? -
Setting up Apache to serve the django admin files
In my apache.conf file (see code below°), VirtualHost port 80 configuration works fine. However, in the port 443, the Alias /admin/media/ /usr/local/lib/python2.7/site-packages/django/contrib/admin/media/ shows two issues: my settings.py has : STATIC_URL = '/m/' and ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' my admin directory is : /home/user/project/virtual-environment/lib/python2.7/site-packages/django/contrib/admin/static/admin/ When I put Alias /m/admin/ /home/user/project/virtual-environment/lib/python2.7/site-packages/django/contrib/admin/static/admin/ it shows error 403 access forbidden. When I add: <Directory "/home/user/project/virtual-environment/lib/python2.7/site-packages/django/contrib/admin/static/admin/"> Require all granted </Directory> <Directory "/home/user/project/"> <Files django.wsgi> Require all granted </Files> </Directory> It shows error 404 not found with error_log saying :[wsgi:error] Target WSGI script '/home/user/project/django.wsgi' does not contain WSGI application 'application' Could you please help me configure my apache virtualhost port 443 to server django admin app? °My apache.conf file is as below: #The following two directories must be both readable and writable by apache WSGISocketPrefix /var/run/apache2/wsgi #WSGIPythonEggs /var/python/eggs # the following directory must be readable by apache WSGIPythonHome /home/user/project/virtual-environment/local/ # NOTE: all urs below will need to be adjusted if # settings.FORUM_SCRIPT_ALIAS is anything other than empty string (e.g. = 'forum/') # this allows "rooting" forum at http://domain-name/forum, if you like #replace default ip with real IP address <VirtualHost 127.0.0.1:80> ServerAdmin you@domain-name DocumentRoot /home/user/project/ ServerName domain-name # aliases to serve static media directly Alias /m/ /home/user/project/static/ … -
Django Programming Error while runing server
I am running a GIS application while getting this error. I have attached error snapshot . Can Someone guide where is error ? If need to see code . Let me know which file you need. -
md5 not support in python 3.6 and django 1.10
I want to decrypt response received from CCavenue.In their refrence code they use md5 library but for django 1.10 with python 3.6 not supported. import md5 ModuleNotFoundError: No module named 'md5' -
Hide Django rest framework Routers Api View Page
I am using DjangoRestFramework 3.3.2 for Routing in my django application. I have 6 different folders for 6 apps and 1 main project app. I have include all 6 apps urls into main url file. Following is my main url file. from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^vpc/', include('vpc.urls')), url(r'^dss/', include('dss.urls')), url(r'^rds/', include('rds.urls')), url(r'^compute/', include('compute.urls')), url(r'^iam/', include('iam.urls')), ] And this is my one of app url file. from django.conf.urls import url from rest_framework import routers import views.instance_views as instance import views.snapshot_views as snapshot router = routers.SimpleRouter() router.register(r'instance', instance.IntanceViewSet, base_name='instance') router.register(r'snapshot', snapshot.SnapshotViewSet, base_name='snapshot') urlpatterns = [] urlpatterns += router.urls Now my problem is when I open urls in browser, I can see whole url hierarchy. Which is not required. How do I hide these rendered views. I don't want to show any extra information I was able to hide view using: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } But I am still getting all urls under 1 app. {"instance":"http://127.0.0.1:8000/compute/instance/","keypair":"http://127.0.0.1:8000/compute/keypair/","volume":"http://127.0.0.1:8000/compute/volume/","image":"http://127.0.0.1:8000/compute/image/","snapshot":"http://127.0.0.1:8000/compute/snapshot/"} -
Call signal only for the current object
I'm working with django 1.6 with signals. I have model Events with field is_cyclic and I want to run signal only for one, current object. But it seems that my code goes through all objects and I get an error: maximum recursion depth exceeded while calling a Python object Here is my signal @receiver(post_save, sender=Events) def my_callback(sender, created, instance, *args, **kwargs): db_name = args[0] if len(args) else 'events' print('using %s' % db_name) list = loader.get_template('events/event_list_item.html') list_small = loader.get_template('events/event_list_item_small.html') setattr(instance, 'is_cyclic', list.render(Context({'e': instance}))) setattr(instance, 'is_cyclic', list_small.render(Context({'e': instance}))) instance.save(using=db_name) -
LoginRequiredMixin fails but user is authenticated
I am using django rest framework token authentication for authenticating a user. When I hit a request with react-native-fetch-blob with header as { Authorization : token, 'Content-Type' : 'multipart/form-data', 'Range' : 'bytes=22976-' } and use LoginRequiredMixin in my server code it fails and redirects. If I remove the LoginRequiredMixin it passes and request.user.is_authenticated() gives True. How do I authenticate the user with the restriction that the user is logged in? Is there any specific header that I am missing from the request? -
ruby - rails > python - django ??????? thoughts?
I've learnt programming 0 to 100 in python, but recently had experience with ruby on rails. Never tried django. Question is, which is more convenient/faster to use in terms of development and deployment? (may be some controversy, but why not ask). Thanks in advance -
How to sync photos automatically with database in Django?
I'm new to Python and Django. I'm working on a project which requires Django. In this project, a program captures photos via camera continuously , and stores them in pathC:\Users\admin\Pictures. Now I want a Django APP to sync these photos with database automatically, rather than log in Django admin site and upload them manually. How to do that correctly in Django? Here is models.py from __future__ import unicode_literals from django.db import models from django.conf import settings from django.utils.encoding import python_2_unicode_compatible # Create your models here. @python_2_unicode_compatible class Image(models.Model): title = models.CharField(max_length=250, blank=True) original = models.ImageField(upload_to=settings.IMAGE_PREFIX, default='/tmp/none.jpg') def __str__(self): return self.title I wrote the script just trying to sync these photos: import os import django django.setup() from gallery.models import Image path = r"C:\Users\admin\Pictures" for filename in os.listdir(path): filePath = os.path.join(path, filename) thisFile = open(filePath, 'rb') new_img = Image(original=thisFile, title=filename) new_img.save() But I got error messages as follow: Error Message I guess there must be something missed when I tried to pass thisFile to Image(), but I just don't know how to fix it. Thanks a lot ! -
mod_wsgi-express slow performance
I ve tried to configure mod_wsgi to integrate apache web server with my django 1.9 (pythno 3.5) application. I am working on Centos7. It works fine but the customer complains performances are slow. It takes sometime to load the homepage. Is there any setting configuration i am missing to improve the performance? I have read on google that modwsgidaemonprocess should have better fermormance and that it is recommended configuration? Thgerefore I changed the httpd.conf adding the follwoing lines: Alias '/static' '/home/elastic/workspace/ES_Brevetti/static' <Directory '/home/elastic/workspace/ES_Brevetti/static'> <IfVersion < 2.4> Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.4> Require all granted </IfVersion> </Directory> <Directory '/home/elastic/workspace/ES_Brevetti/ES_Brevetti'> <IfVersion < 2.4> Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.4> Require all granted </IfVersion> </Directory> WSGIDaemonProcess ES_Brevetti python-path=/home/elastic/workspace/ES_Brevetti:/home/elastic/anaconda3/lib/python3.5/site-packages WSGIProcessGroup ES_Brevetti WSGIScriptAlias / /home/elastic/workspace/ES_Brevetti/ES_Brevetti/wsgi.py but have noticed that the mod_wsgi-express_80 script has already modified httpd.conf and cannot return back. Indeed when I try to start apache with the command systemctl start apache i get the error : AH00111: Config variable ${MOD_WSGI_MODULES_DIRECTORY} is not defined httpd: Syntax error on line 3 of /etc/httpd/conf/httpd.conf: Cannot load ${MOD_WSGI_MODULES_DIRECTORY}/mod_version.so into server: /etc/httpd/${MOD_WSGI_MODULES_DIRECTORY}/mod_version.so: cannot open shared object file: No such file or directory Any help please?? Rgds valerio -
making djangocms url resolvers less greeady
I have a high traffic djangocms site. On the same site there is a also an additional developed django app with a restful api. I have following urls.py urlpatterns = [ url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': {'cmspages': CMSSitemap}}), url(r'^taggit_autosuggest/', include('taggit_autosuggest.urls')), url(r'^select2/', include('django_select2.urls')), url(r'^api/', include('api.urls')), ] urlpatterns += i18n_patterns( url(r'^admin/', include(admin.site.urls)), url(r'^', include('cms.urls')), ) The issue is that if the api returns a 404 an application level for one its urls (e.g for /api/post/15) the last line in the urls.py definitions intercepts the 404, and return a 302, making a redirect to /en/api/post/15 (supposing English is the default langauge). This behaviour is fine for all cms URIs but not for api, where it just increases the traffic. How can I avoid that the djangocms url does not intercept the 404 from the api. -
Heroku gettext installation
I want to install gettext in Heroku. I have added: https://github.com/lexifdev/heroku-buildpack-gettext.git into the buildpacks section of my app. However, when I run heroku run python manage.py compilemessages -l en I get the error message: CommandError: Can't find msgfmt. Make sure you have GNU gettext tools 0.15 or newer installed. -
Django cannot delete single object after rewriting model.Manager method
I am trying to rewrite get_by_natural_key method on django manager (models.Manager). After adding model (NexchangeModel) I can delete all() objects but single - cannot. Can: SmsToken.objects.all().delete() Cannot: SmsTokent.objects.last().delete() Code: from django.db import models from core.common.models import SoftDeletableModel, TimeStampedModel, UniqueFieldMixin class NexchangeManager(models.Manager): def get_by_natural_key(self, param): qs = self.get_queryset() lookup = {qs.model.NATURAL_KEY: param} return self.get(**lookup) class NexchangeModel(models.Model): class Meta: abstract = True objects = NexchangeManager() class SmsToken(NexchangeModel, SoftDeletableModel, UniqueFieldMixin): sms_token = models.CharField( max_length=4, blank=True) user = models.ForeignKey(User, related_name='sms_token') send_count = models.IntegerField(default=0) -
DisallowedRedirect Django
I am doing a tutorial regarding django and I have two errors: When I try to create a plant that plant is saved in the data but I get this error: Exception Type: DisallowedRedirect Exception Value: Unsafe redirect to URL with protocol 'data' when I try to edit then I get this error Exception Type: NoReverseMatch Exception Value: Reverse for 'plants' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Looking forward to find my mistake. views.py: def create_plant(request): if not request.user.is_authenticated(): return render(request, 'data/login.html') elif request.method == "POST": form = PlantForm(request.POST) if form.is_valid(): plant = form.save(commit=False) plant.save() return redirect('data:plants.html', slug = plant.slug) else: form=PlantForm() template = 'data/create_plant.html' context = {'form': form, } return render(request, template, context) def edit_plant(request, slug): plant = get_object_or_404(Plant, slug=slug) if request.method=="POST": form = PlantForm(request.POST, instance=plant) if form.is_valid(): plant = form.save(commit=False) plant.save() return redirect('data:plants') else: form = PlantForm(instance=plant) template = 'data/create_plant.html' context = {'form': form} return render(request, template, context) ######################################################################´ urls.py: from django.conf.urls import url from . import views app_name = 'data' urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^plants/$', views.index, name='index'), url(r'^create_plant/$', views.create_plant, name='create_plant'), url(r'^logout_user/$', views.logout_user, name='logout_user'), url(r'^login_user/$', views.login_user, name='login_user'), url(r'^register/$', views.register, name='register'), url(r'^plants/(?P<slug>[-\w]+)/$',views.detail, name='detail'), url(r'^plants/(?P<slug>[-\w]+)/edit/$', views.edit_plant, name='edit_plant'), url(r'^(?P<plant_id>[0-9]+)/delete_plant/$', views.delete_plant, name='delete_plant'),] -
Viewset to access external API (elastic search)
So I'm trying to use my ElasticSearch api via Django as a viewset. This is my attempt, which doesnt work. I don't get errors, but the URL doesn't actually even appear which makes me think my viewset is broken services.py import json def get_items(id, title): url = 'http://localhost:9200/_search' params = json.loads(request.body) r = requests.get('http://localhost:9200/_search', params=params) items = r.json() # books_list = {'books':books['results']} item_list = ['results'] views.py import services class ElasticViewSet(viewsets.ViewSet): def get(self,request): return render(item_list) urls.py router.register(r'elastic', ElasticViewSet, base_name='Elastic') -
How to deal with users as foreign key and deletion
How do I deal with foreign keys like users or usernames that could one day be deleted? My best guess would be a CharField with Choices limited to the Referennced Field, since deleting a ForeignKey would lead to cascade deletion. I want to conserve eg the Name of the User related to the object even if the original User object was deleted. -
Client Side Validation not working in django.
**I am a newbie to Django and jQuery. I want client side validations in my django project. This simple project is uploading a file and displaying the contents. I am currently just checking that the file field is not empty but it is not working. Moreover, I want to add the code to validate the file such that it can only upload .txt and image files as well as the maximum size of file must not exceed 500KB. How can I add these validations in my .js file?** Template {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'FormStyle.css'%}"/> <script type = 'text/javascript' href="{% static 'validateForm.js' %}" > </script> <div class = "formArea"> <div class = "fileForm"> <form enctype="multipart/form-data" method="post"> {% csrf_token %} <div class = "formFields"> <label for = "file"> {{ form.file.label }} </label> {{ form.file }} {{ form.file.errors }} </div> <div class = "formFields"> <input type="submit" value="Submit"> </div> </form> </div> </div validateForm.js $(document).ready(function() { $('#form').validate({ rules: { file: { required: true } }, messages: { file: { required: 'Please Upload a File!' } } }); }); Form.py from django import forms class fileForm(forms.Form): file = forms.FileField(label = 'Upload File' ) Views.py from django.shortcuts import render_to_response, HttpResponse from .forms … -
ADL LRS saves statement but responds with HTTP 500
I've installed ADL LRS following README.txt on https://github.com/adlnet/ADL_LRS. I'm testing it with TincanJS (https://github.com/RusticiSoftware/TinCanJS) with following code, statement gets saved but response code is 500. lrs = new TinCan.LRS( { ////// This works well endpoint: "https://cloud.scorm.com/tc/public/", username: "<Test User>", password: "<Test Password>", allowFail: false ////// This returns Internal Error(500) endpoint: "my.server:8000/xapi/", username: "<My User>", password: "<My Password>", allowFail: false } ); var statement = new TinCan.Statement( { actor: { "name": "Ac Tor", "account": { "homePage": "http://act.or", "name": "actor" } }, verb: { id: "http://adlnet.gov/expapi/verbs/experienced" }, target: { id: "http://rusticisoftware.github.com/TinCanJS" } } ); lrs.saveStatement( statement, { callback: function (err, xhr) { //... } } ); Thanks in advance. -
View to use external URL
I want to access ElasticSearch securely via a Django URL. From this request, I will lookup the user's token to get their primary key. Then I will only show ES results that match. For now, I just want to connect to my ElasticSearch URL. It would kind of work like a "proxy". Anyway, the following returns the bottom traceback. How do I set it up correctly? Do I need a serialiser views.py from django.http import HttpResponseRedirect class ElasticViewSet(viewsets.ModelViewSet): def my_view(request): if True: return HttpResponseRedirect('http://localhost:9200/_seach') urls.py router.register(r'elastic', ElasticViewSet, base_name='Elastic') Traceback Traceback: File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/viewsets.py" in view 83. return self.dispatch(request, *args, **kwargs) File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 477. response = self.handle_exception(exc) File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception 437. self.raise_uncaught_exception(exc) File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 474. response = handler(request, *args, **kwargs) File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/mixins.py" in list 40. queryset = self.filter_queryset(self.get_queryset()) File "/Users/mac1/Dev/A51/Backend/NewDJ/venv/lib/python2.7/site-packages/rest_framework/generics.py" in get_queryset 67. % self.__class__.__name__ Exception Type: AssertionError at /2042watkin/elastic/ Exception Value: 'ElasticViewSet' should either include a `queryset` attribute, or override the `get_queryset()` method. -
Install django-extensions in requirements.pip
I am working in a team of programmers. I would like to install werkzeug and django-extensions in our main Django project. I know I have to insert something confusing for me in requirement.pip in such a way we could simply do pip install -r requirements.py. Could anyone have an idea what do I have to insert in that file? -
'WSGIRequest' object has no attribute 'build_absoulte_uri'
AttributeError at /blog/8/share/ 'WSGIRequest' object has no attribute 'build_absoulte_uri' Request Method: POST Request URL: localhost Django Version: 1.8.6 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'build_absoulte_uri' Traceback: File "/home/shaik/code/my_env/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/shaik/code/mysite/blog/views.py" in post_share post_url=request.build_absoulte_uri(post.get_absolute_url()) Exception Type: AttributeError at /blog/8/share/ Exception Value: 'WSGIRequest' object has no attribute 'build_absoulte_uri' -
Calling a Django file as a startup service in Ubuntu 14.04
I'm a newbie here. How can i use a python file in my Django application that will be used in startup for my Ubuntu server. Please help me. Thanks