Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run debug in view django with Atom python-debugger?
I'm using Atom for development python. I created a simple project with python and Django. I have already installed python-debugger But how can I run debug it in view of django. -
Celery Crash Solution
I'm not good at celery so I need opinions Is it possible in Celery where the task is chasing for example I have a task that is supposed to run for every 2 minutes so the last task is 10:52 which means the next task should run in 10:54 however it crashed in the 10:53 mark and restored at 10:57 Is it possible that my celery node will catch up and still send the supposed to be sent task on 10:54 and 10:56? Or are there any workarounds? Like immediate restore after crash? PS I'm Using Redis as a broker Code: @periodic_task(run_every=timedelta(minutes=2)) def sample(**kwargs): <do something here> CLI commands used: celery -A proj beat -l info; celery -A proj worker -l info; -
Django installation in venv and system-site-packages
I am installing Django framework in my virtual environment in Ubuntu 16.04 LTS. Need to decide whether to inherit the system-site-packages for my virtual environment. Are their any any potential conflicts of the system wide python3 packages with the Django installation? -
How to make a Django+Ember application run on a domain name and a certain port number
I want to run a Django+Ember website on my website on a certain port number (eg. 54321), for example: domain-name.com:54321. I got the Django+ember application working on my domain name (without the port number specified) like domain-name.com. I can not get it working with the command: python3 manage.py runserver domain-name.com:54321 Do I need to add anything to my /etc/httpd/conf/httpd.conf file? I know my current configuration for the httpd.conf file is correct because it works without a port number. But what am I missing to make it work on a certain port number? -
How to turn generic classes to models in django? is it a good idea to use pickle?
In Django, sometimes there are classes can do what we want, but they are not model, means their instances could only exist in memory, since we want to save some instances in database, and use it next, what could I do? somebody told me this way may work: class People: def __init__(self, age=0): self.age = age def set_age(self, age): self.age = age def get_age(self): return self.age import cPickle class MPeople2(models.Model): people = models.CharField(max_length=200, default=cPickle.dumps(People())) def set_age(self, age): people = self.get_people() people.set_age(age) self.save_people(people) def get_age(self): people = self.get_people() return people.age def get_people(self): return cPickle.loads(self.people) def save_people(self, people): self.people = cPickle.dumps(people) self.save() Is it has any disadvantage? Or any other ideas? -
nginx & uwsgi not redirecting to subpath, getting 404
I have an nginx setup to redirect any calls to the URL to a django application served via uwsgi. For some reason everything works fine for the root of the page, but as soon as I try to access any subpath I get a 404 error message. Example: https://my-domain.de/ Works fine, I get the index page I want to see. https://my-domain.de/dashboard/ Does not work, I only get a 404 error from nginx. I tried about every possible solution I was able to find via Google for about 3h now and I have absolutely no idea why this does not work. Can anyone tell me what my config is missing that causes this behavior? System information: OS: Ubuntu 14.04 nginx/1.10.1 Python 2.7.6 The django application is served with the following command: uwsgi --socket 127.0.0.1:8000 -b 32768 --file path/to/app/wsgi.py The nginx server configuration looks like this: upstream myapp { server localhost:8000; } # Enforce HTTPS server { listen 80; server_name my-domain.de; return 301 https://$server_name$request_uri; } server { listen 443 ssl; ssl_certificate /etc/ssl/certs/my-domain.de.crt; ssl_certificate_key /etc/ssl/private/my-domain.de.key; root /var/www; index index.html index.htm index.php; server_name my-domain.de; underscores_in_headers on; location = / { include uwsgi_params; uwsgi_pass myapp; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Host … -
Check for variable in Django template
I'm new to Django and coming from a PHP background. When I was dealing with pages to enter content and later be able to edit it (and the pages rely on some JS files), I would just set a variable from the controller and let my view (view in the PHP MVC sense) handle it based on the variable being set. For example /some_view_file.html <?php if(isset($editing) && $editing == true){ ?> <script>var editing = true; </script> <?php } else{ ?> <script>var editing = false; </script> <?php } ?> Then I could use the same JavaScript file and easily be able to distinguish if the user was editing or creating new content, rather than having 2 nearly identical JS files with only a few small differences. Since Django seems to be focused on templating rather than being able to intermittently write Django/HTML like you can with PHP/HTML, is there any way to accomplish what I've shown above? I suppose a better question is how do Django programmers typically handle situations like this? Thanks -
Join annotations in Django without raw SQL
I have a model that has arbitrary key/value pairs (attributes) associated with it. I'd like to have the option of sorting by those dynamic attributes. Here's what I came up with: class Item(models.Model): pass class Attribute(models.Model): item = models.ForeignKey(Item, related_name='attributes') key = models.CharField() value = models.CharField() def get_sorted_items(): return queryset.annotate( first=models.select_attribute('first'), second=models.select_attribute('second'), ).order_by('first', 'second') def select_attribute(attribute): return expressions.RawSQL(""" select app_attribute.value from app_attribute where app_attribute.item_id = app_item.id and app_attribute.key = %s""", (attribute,)) This works, but it has a bit of raw SQL in it, so it makes my co-workers wary. Is it possible to do this without raw SQL? Can I make use of Django's ORM to simplify this? I would expect something like this to work, but it doesn't: def get_sorted_items(): return queryset.annotate( first=Attribute.objects.filter(key='first').values('value'), second=Attribute.objects.filter(key='second').values('value'), ).order_by('first', 'second') -
Django Serializer returns curried method instead of value for get_FOO_display
I use DRF's Model Serializer class to (de)serialize my models, and until staring a new project today I was always able to return a Choice Field's display name like so: class StatusSerializer(serializers.ModelSerializer): status = serializers.ChoiceField(source='get_status_display', choices=Status.STATUS_CHOICES) class Meta: model = Status fields = ('id', 'status') My simple example Status model looks like class Status(models.Model): STATUS_PROCESSING = 0 STATUS_COMPLETE = 1 STATUS_ERROR = 2 STATUS_CHOICES = ( (STATUS_PROCESSING, 'Processing...'), (STATUS_COMPLETE, 'Processing Complete'), (STATUS_ERROR, 'Processing Error')) status = models.IntegerField(choices=STATUS_CHOICES, default=STATUS_PROCESSING) in the Django shell I do the following: >>> s = Status.objects.create(status=0) >>> s.get_status_display() # this works 'Processing...' >>> StatusSerializer(s).data # returns the method itself {'status': <bound method curry.<locals>._curried of <Status: Status object>>, 'id': 1} I can see why this would be happening (the serializer is not invoking the source attribute but instead just referencing it), but this used to work in the past! I am running a virtual env with Python 3.5.2 on Mac OSX Sierra 10.12.1 Django==1.10.2 djangorestframework==3.5.1 -
Django REST - Run field validation from within custom to_internal_value for serializer
I am trying to serialize a JSON like this: { "Some URL": "https://helloworld.com/", "Some Integer": 12 "Some Dictionary": { "Nested Array": [...] "Nested Dictionary": {...} } } Writing a serializer with fields with spaces is not allowed (of course because of Python variables), so I'm attempting to subclass BaseSerializer. class MyNestedSerializer(serializers.BaseSerializer): def to_internal_value(self, data): nested_array = data.get('Nested Array') nested_dictionary = data.get('Nested Dictionary') # Validation .... .... return { 'Nested Array': nested_array, 'Nested Dictionary': nested_dictionary } def to_representation(self, instance): return { 'Nested Array': instance['Nested Array'], 'Nested Dictionary': instance['Nested Dictionary'] } class MySerializer(serializers.BaseSerializer): def to_internal_value(self, data): some_url = data.get('Some URL') some_integer = data.get('Some Integer') some_dictionary = data.get('Some Dictionary') # Validation .... nested_serializer = MyNestedSerializer(data=some_dictionary) nested_serializer.is_valid(raise_exception=True) .... return { 'Some URL': some_url, 'Some Integer': some_integer, 'Some Dictionary': some_dictionary } def to_representation(self, instance): return { 'Some URL': instance['Some URL'] 'Some Integer': instance['Some Integer'] 'Some Dictionary': instance['Some Dictionary'] } Now normally, I would define the field type in a serializer (not BaseSerializer) like this: class BasicSerializer(serializers.Serializer): some_integer = serializers.IntegerField(min_value=0) some_dictionary = serializers.DictField(child=serializers.CharField()) and field validation would occur. What I want is to have these validators run inside my implementation of to_internal_value, instead of writing my own validation. It doesn't make sense to rewrite what has … -
How can I convert json response to string?
I want to receive a post in the format: { "event_type": "test", "event_info": { "key": "value" } } I'm not finding a good way to do this. It doesn't like {} I get returned "Not a valid string." I haven't found a good way to accept the json object. I could just store the json as a string but I can't figure out how to convert it to a string either. I have views.py: from django.shortcuts import render from .models import Task, Subscription from .Serializers import TaskSerializer, SubscriptionSerializer from rest_framework import viewsets from django.http import HttpResponse class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all().order_by('-date_created') serializer_class = TaskSerializer http_method_names = ['get', 'post', 'delete'] class SubscriptionViewSet(viewsets.ModelViewSet): queryset = Subscription.objects.all().order_by('-date_created') serializer_class = SubscriptionSerializer http_method_names = ['get', 'post', 'delete'] models.py from __future__ import unicode_literals from django.db import models class Task(models.Model): task_name = models.CharField(max_length=20) task_desc = models.TextField(max_length=20) date_created = models.DateTimeField(auto_now=True) class Subscription(models.Model): event_type = models.TextField(default='Failed to set') event_info = models.TextField(default='Failed to set') date_created = models.DateTimeField(auto_now=True) Serializers.py from rest_framework import serializers from .models import Task, Subscription class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ('id', 'task_name', 'task_desc') class SubscriptionSerializer(serializers.ModelSerializer): class Meta: model = Subscription fields = ('id', 'event_type', 'event_info') -
What are the Benefits of using django rest framework over plain django?
I have a Django service setup for my current project it receives inputs from Angular2 frontend and gives back data in XML format. Do I get any special benefits if I move it to Django Rest Framework? -
CSRF validation does not work on django-rest with angular on different sub-domains
The problem: Error message: CSRF Token: CSRF missing or incorrect. This error occur occasionally on POST operations. After login, almost every time that we logout, it goes wrong. We believe that problem occurs in the connection between Angular and Django System architecture: We are using Angular 1.5.6 and Django 1.9.8 using the django REST framework. The Angular is our front-end part and the django REST is our back-end part. We have a server for the django backend and one NODE.JS server for the Angular. The communication between services is done by CORS mechanism. The Django server and the Angular server are totally independent. Another important thing to mention is that both servers are running on different sub-domains: Django REST: djangoback.bluemix.net Angular: angularfront.bluemix.net How we do: In the front-end side, we do a GET operation before each POST to get the CSRF token from the back-end, because there is no other way to get this. Then, for each request we make to the back-end, we also send the CSRF token of the session, which we got when the user logged in. The requests that goes wrong are the ones that need authentications (POST, PUT, DELETE; views with access permissions). What we … -
How to save a io.bytesio object to a filefield in django?
I'm trying to convert a io.Bytesio() object to a file so it can be set as a filefield in a model. import os, io from django.core.files import File from xlsxwriter.workbook import Workbook out = io.BytesIO() wb = Workbook(out, {'in_memory': True}) worksheet0 = wb.add_worksheet('Dashboard') worksheet0.write('A1', 400) worksheet0.write('A2', 200) wb.close() out.seek(0) f = out.read() report_instance.__setattr__('report_file', f) report_instance.save() But I got an error message below at the last save. The 'report_file' is a filefield. AttributeError: 'bytes' object has no attribute '_committed' Does anyone know how to convert the bytesio object to a valid file so I can save it in the filefield? thanks -
Django MySQL query output error while passing parameters
cur=connection.cursor() def fillDoctors(key_bodyloc,proportion): bodyloc_specialty_query="select distinct Speciality from body_speciality where body_location in (%s) " #cur.execute(bodyloc_specialty_query) data1=([key_bodyloc]) #print(bodyloc_specialty_query,data) cur.execute(bodyloc_specialty_query,data1) results=cur.fetchall() specialities=[x[0] for x in results] condition="" for speciality in specialities: print(str(speciality)) condition=condition+"'%"+speciality+"%'"+" or Speciality like " #print(speciality) #print(condition) specialty_doctors_query="select DoctorName,Speciality,ClinicName from Doctors where Speciality like %s limit %s" data2=([condition,proportion]) print(specialty_doctors_query,data2) cur.execute(specialty_doctors_query,data2) final=cur.fetchall() print(final) The line final=cur.fetchall() returns an empty tuple in each iteration. I've verified that the table Doctors isn't empty and the code works fine when the 'condition' is hard-coded. The code is supposed to print the doctor details for each speciality. Can anyone tell me why this is happening ? -
Django session loses complex object in production, but not in dev
So I am successfully storing a complex object (non-model) in my session in development. I've tried every session engine and cache type and they are all working in development (Pycharm). However, when I move the code to production, while no error are thrown, the session losses the object. Here is the method I use to set the session object: def instantiate_command_object(request): try: ssc = request.session['specimen_search_criteria'] logger.debug('found ssc session variable') except KeyError: logger.debug('failed to find ssc session variable') ssc = SpecimenSearchCommand() return ssc Then in a method that runs asynchronously via an ajax call I start making changes to the object in the session: def ajax_add_collection_to_search(request): ssc = instantiate_command_object(request) collection_id = request.GET.get('collection') collection = Collection.objects.get(pk=collection_id) if collection and collection not in ssc.collections: ssc.collections.append(collection) # save change to session request.session['specimen_search_criteria'] = ssc # refresh search results ssc.search() return render(request, '_search.html') All this works as far as it goes. However, if I then refresh the browser, the session is lost. Here is a snippet from the template: {% with criteria=request.session.specimen_search_criteria %} <div class="search-criteria" id="search-criteria"> <div class="row"> Sesssion: {{ request.session }}<br/> Search: {{ request.session.specimen_search_criteria }}<br/> Created: {{ request.session.specimen_search_criteria.key }}<br/> Collections: {{ request.session.specimen_search_criteria.collections }}<br/> Again, in development I can refresh all day and the same … -
Django Rest Framework serializer returning decimal in scientific notation format
I'm running drf 3.5 with django 1.10.2 and the regular end point view is working just fine, other than the fact my decimals are being converted to scientific notation format. I've made sure to define the decimal in the serializer to coerce_to_string=False. So if I have a decimal like 0.000001 it will come down in json like 1e-06. but I have other decimals 0.032230 that come down from the server just fine. I'd prefer to not receive my decimals in scientific notation since I'd have to write some code on the fronted to convert the incoming decimals anytime i pull the data. -
Best practice for including custom javascript in Django?
Still new to Django. I am trying to incorporate a calendar widget into date input as shown in this tutorial. The following test.html works fine: {% extends "base_alt_simple.html" %} {% block title %}Schedule{% endblock %} {% block main_content %} <div class="container"> <h3>Building name</h3> </div> <div class="container"> <div class="bootstrap-iso"> <div class="container-fluid"> <div class="row"> <div class="col-md-6 col-sm-6 col-xs-12"> <form method="post"> <div class="form-group "> <label class="control-label " for="date"> Date </label> <div class="input-group"> <div class="input-group-addon"> <i class="fa fa-calendar"> </i> </div> <input class="form-control" id="date" name="date" placeholder="MM/DD/YYYY" type="text"/> </div> </div> <div class="form-group"> <div> <button class="btn btn-primary " name="submit" type="submit"> Submit </button> </div> </div> </form> </div> </div> </div> </div> </div> <script> $(document).ready(function(){ var date_input=$('input[name="date"]'); //our date input has the name "date" var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent() : "body"; date_input.datepicker({ format: 'mm/dd/yyyy', container: container, todayHighlight: true, autoclose: true, }) }) </script> But, if I would like to keep the javascript in a custom.js, how would I load this? I read here that I should do the following: <script src="yourscript.js"></script> But this does not work. I am clearly misunderstanding something here. Thanks for any advice. Also, base_alt_simple.html has: <!-- Include jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <!-- Include Date Picker --> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/> At the … -
django templates - passing variables between templates
I have one template that includes a popup page. I loop through all values in a list that I get from the view and want to include information from each element of the list in the popup. page1.html: {% include "popup.html" %} ... {% for element in someList %} <div class="col s3 some-button"><a onclick="$(showPopup('popup'));">More Info</a></div> {% endfor %} showPopup is a Javascript function that will show the popup. In popup.html I reference element from the for loop above: popup.html ... {{ element }} ... But the popup.html template does not seem to be able to find the element from the for loop, since nothing is shown. Is there a way to make it so the popup.html is able to reference element? -
Real-time connection in django ajax or websocket
How do I connect ajax in django? to just do like change the text button to "liked" and communicate the backend of this action and how do I make a notification system in "real-time" to show the latest notifications without the user give refresh the page ? Using websockets or ajax? is there any package PIP for this? I wanted something simple because i a newbie in django Thank you -
Include javascript widget into django template
Still new to django so I may be overlooking something here. I would like to replicate a basic datepicker widget into a template. Right now I have a base.html and the test.html where I would like to include the widget. In the example, I can get it to work if my test.html replicates the source. Also, any recommendations on a better way to insert a calendar widget are welcome. Thanks. This test.html works: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery UI Datepicker - Default functionality</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { $( "#datepicker" ).datepicker(); } ); </script> </head> <body> <p>Date: <input type="text" id="datepicker"></p> </body> </html> But what I want to do is store the datepicker widget in a custom.js so I can reuse across multiple templates. So I added <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> to my <head> in the base.html so it looks like: {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>{% block title %}Name{% endblock title %}</title> <!-- Bootstrap core CSS --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Custom … -
Does django support Teradata as a back end database?
I want to make a django powered intranet web app. Need to know that does django support Teradata as a back-end database? as there is some requirement where my web app has to make connection with Teradata to get and process data and send it back to Teradata database. -
AttributeError at /home/: 'ActionCodeForm' object has no attribute 'is_bound'
I'm creating a home page for my Django webapp, outside of Django admin. I'd like the home page to have a very simple ModelForm that when submitted, writes to the database. I'm getting the following error at /home/ currently and not sure how to resolve it. AttributeError at /home/ 'ActionCodeForm' object has no attribute 'is_bound' I know about bound and unbound forms and have read the docs, but I am not sure how to actually implement them. Here is my model: class ActionCode(models.Model): action_code = models.CharField(blank=False, max_length=10, verbose_name="Action Code") Here is my ModelForm: class ActionCodeForm(ModelForm): class Meta: model = ActionCode fields = ('action_code',) def __init__(self, *args, **kwargs): super(ActionCodeForm).__init__(*args, **kwargs) Here is my view: def action_code_form(request): if request.method == 'GET': form = ActionCodeForm() else: form = ActionCodeForm(request.POST) if form.is_valid(): action_code = form.cleaned_data['action_code'] form.save() else: form = ActionCodeForm() return render('action_code_form.html', {'form': form}, context_instance=RequestContext(request)) And here is my template, action_code_form.html: <form method="post" action=""> {% csrf_token %} <table> {{ form }} </table> <input type="submit" value="Submit"/> </form> And urls.py: from home.views import action_code_form urlpatterns = [ url(r'^home/', action_code_form, name="home"), ] -
Conditionally change background color of cell in django admin list_filer
Looking to find an elegant way to conditionally change the background color of a cell in list_filter. If I don't have a conditional, it works fine for one status but need to change the color of background based on different status. django version 1.10, python 3.5 Model.py class PlayBook(TimeStampModel): minor = 'MINOR' normal = 'NORMAL' important = 'IMPORTANT' critical = 'CRITICAL' SEVERITY = ( (minor, 'Minor'), (normal, 'Normal'), (important, 'Important'), (critical, 'Critical'), ) low = 'LOW' high = 'HIGH' PRIORITY = ( (low, 'Low'), (normal, 'Normal'), (high, 'High'), ) new = 'New' in_progress = 'In_Progress' needs_info = 'Needs Info' postponed = 'Postponed' closed = 'Closed' STATUS= ( (new, 'New'), (in_progress, 'In Progress'), (needs_info, 'Needs Info'), (postponed, 'Postponed'), (closed, 'Closed'), ) subject = models.CharField(max_length=200, unique=True) description = models.TextField(blank=True, help_text="Business purpose of the application") manager = models.ForeignKey(User, on_delete=models.CASCADE) severity = models.CharField(max_length = 100, choices=SEVERITY, default=normal) priority = models.CharField(max_length = 100, choices=PRIORITY, default=normal) status = models.CharField(max_length = 100, choices=STATUS, default=new) def __str__(self): return "{}".format(self.subject) class Meta: ordering = ('severity',) @property def short_description(self): return truncatechars(self.description, 35) Admin.py from django.utils.html import format_html class PlayBookAdmin(admin.ModelAdmin): list_display =['severity','priority', 'subject', 'status_colored','created','updated', 'short_description'] def status_colored(self, obj): color = 'yellow' if obj.status == 'Closed': color = 'green' return format_html( '<b … -
Django sitemap with alternate language pages and other advanced features
Does anyone know how to do this? Standard django sitemap has i18n parameter, which is pretty dumb (it just creates loc element for every language): https://docs.djangoproject.com/en/1.10/ref/contrib/sitemaps/#django.contrib.sitemaps.Sitemap.i18n I'd also like to add other sitemap data like image/video content. Is there standard django way of doing this or do I have to implement on my own? Couldn't find any standard way or good app.