Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django gunicorn sock file not created by wsgi
I have a basic django rest application in my digital ocean server (Ubuntu 16.04) with a local virtual environment. The basic wsgi.py is: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "workout_rest.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application) I have followed step by step this tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 When I test Gunicorn's ability to serve the project with this command: gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application All works well. So I've tried to setup Gunicorn to use systemd service file. My /etc/systemd/system/gunicorn.service file is: [Unit] Description=gunicorn daemon After=network.target [Service] User=ben Group=www-data WorkingDirectory=/home/ben/myproject ExecStart=/home/ben/myproject/myprojectenv/bin/gunicorn --workers 3 --bind unix:/home/ben/myproject/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target My Nginx configuration is: server { listen 8000; server_name server_domain_or_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ben/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/ben/myproject/myproject.sock; } } I've changed listen port from 80 to 8000 because 80 give me a err_connection_refused error. After starting the server with this command: sudo systemctl restart nginx When I try to run … -
Django/Python: Show pdf in a template
I'm using django 1.8 in python 2.7. I want to show a pdf in a template. Up to know, thanks to MKM's answer I render it in a full page. Do you know how to render it? Here is my code: def userManual(request): with open('C:/Users/admin/Desktop/userManual.pdf', 'rb') as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') response['Content-Disposition'] = 'inline;filename=some_file.pdf' return response pdf.closed -
Django form validation, how to show messages on the fields?
I am building a register form, but I am having some trouble with its validation. I would like to see the error message showing up at the field, but instead I am getting a error on the browser saying : The User could not be created because the data didn't validate. Request Method: POST Request URL: http://127.0.0.1:8000/account/register/ Django Version: 1.9.8 Exception Type: ValueError Exception Value: The User could not be created because the data didn't validate. Exception Location: C:\Python34\lib\site-packages\django\forms\models.py in save, line 446 This is my forms.py class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='Password', required=False ,widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat password', required=False ,widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'first_name', 'email') def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') #cd = self.cleaned_data if not password2: raise forms.ValidationError("Fill out the password2 .") if password1 != password2: raise forms.ValidationError("The two password fields didn't match.") return password2 This is my view register def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid: new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data['password']) new_user.save() return render(request, 'account/register_done.html', {'new_user': new_user}) else: print (user_form.errors) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form': user_form}) my htmls - register.html {% extends "account/base.html" %} {% block title %}Create an account{% endblock %} {% block content … -
Error while processing route: home No model was found for 'App.undefined'
DEBUG: Ember : 1.7.1 DEBUG: Ember Data : 1.0.0-beta.12 DEBUG: Handlebars : 1.1.2 DEBUG: jQuery : 1.10.2 Having an issue with what I believe is the belongsTo attribute on my user model. (This happens on my other belongsTo attributes within my application as well). I have a Django backend which returns a response when I comment out the network: attribute. { email: "test@test.com", first_name: "Test", global_code: "daht64q691zy4k887ch", global_id: "GBID-USER-dat64q6917zy4k887ch", institution_gbid: "GBID-GINS-567j53ey0lojsu2kys", institution_name: "Some University", last_name: "Testing", network: { }, view_policy: { capability: "system:view", description: "Anyone can view a user", hold: true, id: "daht64q691y4k887ch:system:view", values: "" } } Code for the User Model: App.User = DS.Model.extend({ first_name: DS.attr('string'), last_name: DS.attr('string'), global_id: DS.attr('string'), network: DS.belongsTo('basicgrouping') }): Code for Basic Grouping model: App.Basicgrouping = DS.Model.extend({ global_id: DS.attr('string'), name: DS.attr('string'), gbid_code: function(){ return getGBIDCode(this.get('global_id')); }.property('global_id') }); Debugging ember-data I placed a console.log() within the following code: relationshipsByName: Ember.computed(function() { var map = Map.create(); this.eachComputedProperty(function(name, meta) { console.log(name, meta); if (meta.isRelationship) { meta.key = name; var relationship = relationshipFromMeta(this.store, meta); relationship.type = typeForRelationshipMeta(this.store, meta); map.set(name, relationship); } }); This seems to show that the type of the object that it belongs to is not being found (Basicgrouping) as it's returning App.undefined. My theory is it … -
Django 1.9 to 1.10 raises NoReverseMatch: u'en-gb' is not a registered namespace
I am trying to update my 1.9 application to 1.10 and I am getting the following error on running all my unit tests: NoReverseMatch: u'en-gb' is not a registered namespace My setting.py file contains the following: LANGUAGE_CODE = 'en_gb' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True TIME_ZONE = 'Europe/London' What am I missing? -
How to send table info to template via post?
From django view.py, I generate a table that will be rendered in my html template. This table contains general related info in each row, and also a button which should submit a value back to my view. The view, after receiving this parameter, should render another template. How could I send this parameter via POST considering each row has a different value for the parameter? Here is the code: My view.py: def list_members(request): if request.method == 'GET': #Does some search else: form = ListMembersForm(request.POST) if form.is_valid(): search_parameter = form.cleaned_data['search_parameter'] urn = request.POST.get('urn') if(search_parameter != ''): #Does the search and renders a table with some info, including 'urn' if(urn): # Renders another template, based on the 'urn' parameter. return render(request, 'portal/list_members.html', context) My template: <table class="table"> <tr> {% for header in members.headers %} <th>{{ header }}</th> {% endfor %} </tr> <tbody> {% for member in members.rows %} <tr> {% for value in member %} <td>{{ value }}</td> {% endfor %} <td> <!-- I should set here the value of **urn = request.POST.get('urn')**--> <button type="submit" class="btn btn-primary">Details</button> </td> </tr> {% endfor %} </tbody> </table> -
Prevent Gunicorn from loading slowly after an inactive period?
My Django project is running on gunicorn. Some times the same page loading (and oracle procedures calls related) takes a lot of time instead a fraction of second. This occurs when the server remains inactive for some minutes. How do I prevent Gunicorn from loading slowly after an inactive period? wsgi.py import os import site import sys from whitenoise.django import DjangoWhiteNoise # Add the site-packages of the chosen virtualenv to work with site.addsitedir('/new_esmart/esmart_env/lib/python2.7/site-packages') # Add the app's directory to the PYTHONPATH sys.path.append('/new_esmart/esmart2') sys.path.append('/new_esmart/esmart2/esmart2') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "esmart2.settings") # Activate your virtual env activate_env = os.path.expanduser("/new_esmart/esmart_env/bin/activate_this.py") execfile(activate_env, dict(__file__=activate_env)) from django.core.wsgi import get_wsgi_application application = get_wsgi_application() application = DjangoWhiteNoise(application) -
Django select from related model
i have 3 django models: class Property(object): name = ... class Object(object): text = ... data_related = models.ManyToManyField('Property',related_name='property_related', through="ObjectProperty") class ObjectProperty(object): extra_data = ... i need to select object that has at least 2 properties at the same time. How can i do it? For example, Object = [lamp, table, car, pen,...] Property = [round, red, white, invisible, soft,...] I want to find white round and soft object. -
django pages and access to parent object
i am running django 1.9, and i have these two simple models: #models.py class Question(models.Model): question_title = models.CharField(max_length=50) question_text = models.CharField(max_length=500) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer_text = models.CharField(max_length=500) and this simply view for the answers: # views.py class QuestionView(generic.DetailView): model = Question template_name = 'forum/question.html' but now i want to build pages into the views: # models.py updated class QuestionView(generic.ListView): model = Question template_name = 'forum/question.html' paginate_by = 10 def get_queryset(self): return Question.objects.get(id=self.kwargs['pk']).answer_set.all() but this creates a problem, i have no longer access to the question object in the template: #template.html {{ question.question_title }} how can i have both pages and access to the question object? Or do i want something now which is simply impossible? ps. i import everything i need (generic and more), i just left them out for readability. -
Django Rest: Correct data isn't sent to serializer with M2M model
I have a simple relational structure with projects containing several sequences with an intermediate meta model. I can perform a GET request easily enough and it formats the data correctly. However, when I want to post the validated_data variable does not contain data formatted correctly, so I can't write a create/update method. The data should look like: {'name': 'something', 'seqrecords': [{ 'id': 5, 'sequence': 'ACGG...AAAA', 'name': 'Z78529', 'order': 1 }, { 'id': 6, 'sequence': 'CGTA...ACCC', 'name': 'Z78527', 'order': 2 }, } But instead it looks like this: {'name': 'something', 'projectmeta_set': [ OrderedDict([('order', 1)]), OrderedDict([('order', 2)]), OrderedDict([('order', 3)]) ] } Serializers: class ProjectMetaSerializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField(source='sequence.id') name = serializers.ReadOnlyField(source='sequence.name') class Meta: model = ProjectMeta fields = ['id', 'name', 'order'] class ProjectSerializer(serializers.HyperlinkedModelSerializer): seqrecords = ProjectMetaSerializer(source='projectmeta_set', many=True) class Meta: model = Project fields = ['id', 'name', 'seqrecords'] ReadOnlyField = ['id'] def create(self, validated_data): project = Project(name=validated_data['name']) project.save() # This is where it all fails for seq in validated_data['seqrecords']: sequence = SeqRecord.objects.filter(id=seq['id']) meta = ProjectMeta(project=project, sequence=sequence, order=seq['order']) meta.save() return project class SeqRecordSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = SeqRecord fields = ['id', 'name', 'sequence'] read_only_fields = ['id'] Models: class SeqRecord(models.Model): name = models.CharField(max_length=50) sequence = models.TextField() class Project(models.Model): name = models.CharField(max_length=50) sequences = models.ManyToManyField(SeqRecord, through='primer_suggestion.ProjectMeta') class … -
Make navbar item active in Django Template
i'm creating menu with forloop and i need to add active class after click. {% for menu in TopMenu %} <li><a href="/content/{{menu.slug_link}}">{{menu.title}}</a></li> {% endfor %} i tried to use django template inheritance but it didn't work. any solutions? {% for menu in TopMenu %} <li {%if activeflag == '{{menu.slug_link}}' %} class="active" {%endif%} ><a href="/content/{{menu.slug_link}}">{{menu.title}}</a></li> {% endfor %} -
how to run cgi scripts within django server
im using django 1.9. im new to django. i had tried many solutions but i didn't find right answer. like in this post Django - routing to non-django script? (e.g. simple WSGI/CGI application) we can redirect normal django request to non-django scripts. but the thing is we cant redirect with post parameters. tell me if is there any way to run CGI scripts within django server or not? if yes, please help me out.. -
push data to google chart from django template
i've been trying to made a chart from polls app i made with django to show the result but nothing's happen here's the code <ul class="result"> <li data-thumbnail="Awesummmm" data-caption="7"></li> <li data-thumbnail="niceeeee" data-caption="5"></li> </ul> <script type="text/javascript"> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var $resultDataWrap = $('.result'), $results = $resultDataWrap.find('li'), $slides = []; $results.each(function(){ var dataThumbNail = $(this).data('thumbnail'), dataCaption = $(this).data('caption'); $slides.push([dataThumbNail, dataCaption]); }); var data = google.visualization.arrayToDataTable([ ['Task', 'Hours per Day'], $slides, ]); var options = { title: 'Result Chart' }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } </script> however if i change the $slides.push([dataThumbNail, dataCaption]); and just change it into a variable $slides = [dataThumbNail, dataCaption]; it's show me a result but only one data appear screenshot would you please tell me where i did wrong? any help or direction would be appreciated, thanks in advance -
Rest api call from rest api clients failing even without entering the called Django function
I am trying to make a rest api call using postman and morzilla rest-client. But I keep getting the following error: Traceback (most recent call last): File "/private/var/www/djenv/lib/python2.7/site-packages/django/core/handlers/base.py", line 164, in get_response response = response.render() File "/private/var/www/djenv/lib/python2.7/site-packages/django/template/response.py", line 158, in render self.content = self.rendered_content File "/private/var/www/djenv/lib/python2.7/site-packages/rest_framework/response.py", line 59, in rendered_content ret = renderer.render(self.data, media_type, context) File "/private/var/www/djenv/lib/python2.7/site-packages/rest_framework/renderers.py", line 99, in render separators=separators File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 251, in dumps sort_keys=sort_keys, **kw).encode(obj) File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode return _iterencode(o, 0) File "/private/var/www/djenv/lib/python2.7/site-packages/rest_framework/utils/encoders.py", line 61, in default return super(JSONEncoder, self).default(obj) File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: MultiValueDictKeyError("'name'",) is not JSON serializable The main function I wrote is not being called at all. Even if i am passing a dummy json input it is still throwing the same response. Can someone help me identifying the problem? -
Model.save() not called on update()
I added a save() method to my Model, to update some timestamps: class Order(models.Model): deliveredtime = models.DateTimeField(blank=True, null=True, default=None) status = models.CharField(default='NEW', max_length=20) def save(self, *args, **kw): if self.status == "DELIVERED" and self.deliveredtime is None: self.deliveredtime = timezone.now() super(Order, self).save(*args, **kw) But I found out this method is not called when calling update on a list of objects: Order.objects.filter(status='WAITING FOR DELIVERY').update(status='DELIVERED') How can I trigger this update on any change on any object of the Order class? -
how to form create methods to save the data to the database using django rest framework
i am trying to save the data from the JSON file to the Database using the Deserialization the serializers in Django using the drf and these are my models from django.db import models class elements(models.Model): id=models.CharField(primary_key=True,max_length=100) slug=models.CharField(max_length=100) name=models.CharField(max_length=100) courseType=models.CharField(max_length=100) def __str__(self): return "%s %s %s %s" % (self.id, self.slug,self.name, self.courseType) class types(models.Model): elements=models.ForeignKey(elements, on_delete=models.CASCADE) and the serializer files are as follows: from rest_framework import serializers from serial.models import elements,types class elementserializer(serializers.ModelSerializer): class Meta: model = elements field=('id','name','slug','courseType') class courseserial(serializers.ModelSerializer): elements=elementserializer(many=True) class Meta: model = types field=('elements') the create methods that i use keeps giving errors even when i tried using the documentation http://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers can anyone tell me a better way to write the create methods to save the data to the database using the serializers. the create method that i use is as follows: def create(self, validated_data): elements_data = validated_data.pop('elements') types = types.objects.create(**validated_data) for elements_data in elements_data: elements.objects.create(types=types, **elements_data) return types -
In Django create a dummyuser (on startup?)
My goal is to have one dummyuser in the database. I already wrote the following function def get_test_user(): user, created = get_user_model.objects.get_or_create(username=TESTUSER_USERNAME) user.set_password(TESTUSER_PASSWORD) user.save But where and how should I call it to achieve my goal. I am aware that testing django will create its own database and that there are functions for creating test users. But this should actually run in the production database as well. -
Django's CreateView and foreign keys
In my models I have something like this: class Course(models.Model): ... class CourseYear(models.Model): course = models.ForeignKey(Course) ... Then, in the view, I have subclassed Django's generic.edit.CreateView to create a view that takes a Course pk (in the url) and creates a new CourseYear object which refers to the Course object corresponding to the given pk. class CourseNewYearView(generic.edit.CreateView): model = CourseYear fields = [] template_name = 'course_new_year.html' def form_valid(self, form): form.instance.course = Course.objects.get(pk=self.kwargs['pk']) self.success_url = reverse('index') return super(CourseNewYearView, self).form_valid(form) However, for some misterious reason, this view also seems to create a new Course object with the same pk as the already existing one! (the new CourseYear object is also created, as expected) By "seems to create" I mean that, in the Django admin, there are two copies of the same Course object (with the same pk). Also, Course.objects.all() returns a list with duplicate elements. How can this happen? -
What's the best way to get continuous data from another program in Django?
Here's the setup: On a single-board computer with a very rudimentary linux I'm running a Django app. This app is, when a button is pressed or as a response to the data described below, supposed to call either a function from a library written in C, or a compiled C program, to write data to system memory at a specified address, poke/peek like. (Python doesn't seem to be able to do that natively.) The Django app should also display data, continuously, which is being read from the memory from the same library / program. My question now is how to even begin with setting up the scenario described above. Is this even possible with a web app? Is a Django or more fundamentally any web framework even the right approach here? I'm at a bit of a loss here, since I've spent quite a few hours now trying to figure out how to do this while not getting the most basic starting point... Disclaimer: I'm pretty new to the entire web framework thing, and more importantly web development in general, so sorry if this is a bad question as in, I could have easily found information on this topic online, … -
Detect if a DateTime field is not set
I have this (part of a) model: class Order(models.Model): d_time = models.DateTimeField() def save(self, *args, **kw): if self.status == "delivered": self.d_time = timezone.now() super(Order, self).save(*args, **kw) I want the d_time only to be set when status changes to "delivered", and the d_time is not set yet. How can I do that? -
gulp and running django server with logging
I'm trying to run a django server from gulp. Although I've now managed (roughly) to activate the virtual env and then start the server, none of the output/errors from the django server appears. How can I get this to appear when using gulp? gulpfile.js var pjson = require('./package.json'); // Run django server var cmd = 'workon switcher5' gulp.task('runServer', function() { exec('~/virtualenvs/' + pjson.name + '/bin/python manage.py runserver', function (err, stdout, stderr) { console.log(stdout); console.log(stderr); }); }); Note although the server runs fine. I am getting the error in the console: /bin/sh: /Users/User/virtualenvs/switcher5/bin/python: No such file or directory (Running the django server not via gulp works as normal. ) -
Space in sentence with german letters like ß, ö, ü in django template
I'm using the django-haystack search, and I have the problem of German letters in a sentence. The point is that there are spaces in the sentence the German letters, safe filter does not help. This is my code, but doesn't work: <p>{% highlight obj.text with search_query html_tag "b" max_length 100 %}</p> Here is another solution, also doesn't work: {% with obj.text|safe as text %} {% highlight text with search_query html_tag "b" max_length 100 %} {% endwith %} -
Error on large JSON object in DropZone response
I'm trying to upload large CSV files from Dropzone to my Python app. I may also need to send the contents of those files back to client in JSON format for user's viewing. For size testing purposes, I'm using following code to test how large of a JSON list can I send back to client without any errors. res = {} jsonLst = [] print("start loop") for i in range(0, 9000): print(str(i)) jsonLst.append({ "Name" : "ABC XYZ" + str(i), "Age" : i, "Account No" : "274328948923", "Ref No" : "2323432"}) res['status'] = False res['msg'] = jsonLst print("loop done") return JsonResponse(res) I found that it goes up to 9000 records before Dropzone starts dropping the error Server responded with 0 code. The uploaded files can contain millions of record and it doesn't even cross 10,000! How do I fix it? -
Test 200 code in python/django
I'm trying to test my project and I want to get a 200 status code with the following test: import requests def test_200(self): url_csrftoken = 'http://127.0.0.1:8000/login/' url = 'http://127.0.0.1:8000/' url_login = 'http://127.0.0.1:8000/login/signin' client = requests.session() client.get(url_csrftoken) csrftoken = client.cookies['csrftoken'] login_data = dict(inputUser='admin', inputPassword='mypass', csrfmiddlewaretoken=csrftoken, next=url) client.post(url_login, data=login_data) r = client.get(url) self.assertEqual(r.status_code,200) It stops at: client.get(url_csrftoken) and gives the following error: Traceback (most recent call last): File "tests2.py", line 115, in test_networking csrftoken = client.cookies['csrftoken'] File "/home/user/project/env/lib/python2.7/site-packages/requests/cookies.py", line 327, in __getitem__ return self._find_no_duplicates(name) File "/home/user/project/env/lib/python2.7/site-packages/requests/cookies.py", line 398, in _find_no_duplicates raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path)) KeyError: "name='csrftoken', domain=None, path=None" -
Django models: foriegn key or multiple data in a field
Actually, this question has puzzled me for a long time. Say, I have two models, Course and CourseDate, as follows: class Course(models.Model): name = model.CharField() class CourseDate(models.Model): course = modelds.ForienKey(Course) date = models.DateField() where CourseDate is the dates that a certain course will take place. I could also define Course as follows and discard CourseDate: class Course(models.Model): name = models.CharField() dates = models.CharField() where the dates field contains dates represented by strings. For example: dates = '2016-10-1,2016-10-12,2016-10-30' I don't know if the second solution is kind of "cheating". So, which one is better?