Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot resolve keyword 'XXX' into field
I have the following class class Advert(models.Model): ... title = models.TextField ( verbose_name = 'Job Title', ) advertiser = models.TextField ( verbose_name = 'Advertiser', ) first_advert = models.DateField ( verbose_name = 'First Advertised', default = datetime.date.today ) last_advert = models.DateField ( verbose_name = 'Last Advertised', default = datetime.date.today ) def posted_once(self): return (self.last_advert == self.first_advert) posted_once.short_description = 'Posted Once' Within admin.py I'm trying to use posted_once for a filter class AdvertAdmin(admin.ModelAdmin): list_display = ['first_advert','last_advert',] ordering = ['-last_advert','first_advert'] actions = [extract,] list_filter = ('posted_once',) But I get the Cannot resolve keyword 'posted_once' into field error. Help me please. -
Forbidden (403) CSRF verification failed. Request aborted using django
hello i am user python and Django. i will follow this question(Can I have a Django form without Model) but for my task i need images. i will try to run my code and i have this error Forbidden (403) : any idea how to fix that ? Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests. views.py from django.shortcuts import render from django.shortcuts import render_to_response from django.template import RequestContext from blog.forms import MyForm # Create your views here. def form_handle(request): form = MyForm() if request.method=='POST': form = MyForm(request.POST) if form.is_valid(): cd = form.cleaned_data #now in the object cd, you have the form as a dictionary. a = cd.get('a') return render_to_response('blog/calc.html', {'form': form}, RequestContext(request)) urls.py from django.conf.urls import url from . import views forms.py from django import forms class MyForm(forms.Form): #Note that it is not inheriting from forms.ModelForm a = forms.ImageField() #All my attributes here urls.py urlpatterns … -
aggregate or annotate with condtion in django
I am new to django and SQL queries. I am trying some annotation with distinct in django. but unable to get results. My table looks like +-----------------------+-----------+---------------------+ | email | event | event_date | |-----------------------+-----------+---------------------| | hector@example.com | open | 2017-01-03 13:26:13 | | hector@example.com | delivered | 2017-01-03 13:26:28 | | hector@example.com | open | 2017-01-03 13:26:33 | | hector@example.com | open | 2017-01-03 13:26:33 | | tornedo@example.com | open | 2017-01-03 13:34:53 | | tornedo@example.com | click | 2017-01-03 13:35:22 | | tornedo@example.com | open | 2016-09-05 00:00:00 | | tornedo@example.com | open | 2016-09-17 00:00:00 | | sparrow@example.com | open | 2017-01-03 16:05:36 | | tornedo@example.com | open | 2017-01-03 20:12:15 | | hector@example.com | open | 2017-01-03 22:06:47 | | sparrow@example.com | click | 2017-01-09 19:46:26 | | sparrow@example.com | open | 2017-01-09 19:47:59 | | sparrow@example.com | open | 2017-01-09 19:48:28 | | sparrow@example.com | delivered | 2017-01-09 19:52:24 | +-----------------------+-----------+---------------------+ Model is like: class EmailEvent(models.Model): event = models.TextField(blank=True, null=True) email = models.TextField(blank=True, null=True) event_date = models.DateTimeField(blank=True, null=True) I want distinct count for different event column values. For example EmailEvent.objects.filter(event='open').distinct('email').count() results 3 EmailEvent.objects.filter(event='click').distinct('email').count() results 2 EmailEvent.objects.filter(event='delivered').distinct('email').count() results 2 how to get result with aggregate or … -
enable disable a textfield on the selection of dropdown value in Django
I have a register page in Django which contains some textfield and a dropdown value. models.py class UserInformation(models.Model): firstName = models.CharField(max_length=128) lastName = models.CharField(max_length=128) emailAddress = models.EmailField(max_length=128) phoneNumber = models.CharField(max_length=128) orchidNumber = models.CharField(max_length=128) institution = models.CharField(choices = [("Inst1","Inst1"), ("Inst2","Inst2"),("Other","Other")], max_length=128) otherInstitute = models.CharField(default="N/A",max_length=128) cstaPI = models.CharField(max_length=128) Currently all the fields are displaying on my register page. But the field otherInstitute should be displayed only when a user selects **Other** in institution dropdown. register.html {% extends "base.html" %} {% block title %}User Registration{% endblock %} {% block head %}User Registration{% endblock %} {% block content %} <form method="post" action=".">{% csrf_token %} <table border="0"> {{ form.as_table }} </table> <input type="submit" value="Register" /> </form> {% endblock %} views.py @csrf_protect def register(request): if request.method == 'POST': form = UserInformationForm(request.POST) form.save() return HttpResponseRedirect('/register/success/') else: form = UserInformationForm() variables = { 'form': form } return render(request, 'registration/register.html',variables) I am not sure how to implement the logic and where I should implement the logic in Django. -
Django- Create a downloadable excel file using pd.read_html & df.to_excel
I currently have a python script that uses pd.read_html to pull data from a site. I then use df.to_excel which sets 'xlsxwriter' as the engine. I am trying to find a way to incorporate this into a django webapp. However, I am lost as how to do this or even know if possible. I've seen a few ways to create downloadable excel files in django but none that have pandas as the driving force of creating the data in the excel file. My python code for creating the excel file without django is somewhat long so not sure what to show. -
How to do the search engine for my application in django
Hello friends I'm doing my first web application, I need to implement a search engine. I want a user to type the name of a city to display the list of events in that city. At the end I leave an image of my app and the models of the database: class Ciudad (models.Model): nombre = models.CharField(max_length=30) departamento = models.ForeignKey(Departamento) def __str__(self): return self.nombre class Evento (models.Model): nombre = models.CharField(max_length=30) descripcion = models.CharField(max_length=100) fecha = models.DateField() hora = models.TimeField() lugar = models.CharField(max_length=30) ciudad = models.ForeignKey(Ciudad) imagen =models.FileField(blank=True, null=True) #imagen =models.ImageField(upload_to='images/', blank=True, null=True) def __str__(self): return self.nombre -
pass object primary key across templates django
new to python/django. I am using class based views. I have objects named Video that I want to be able to create ratings for. I have a DetailView for the Video, and on that same page I have a link that brings you to another page to rate the Video that was on the DetailView (because I have not wanted to mess with Mixins yet to have it all on the same page). How can I keep/get the reference to the DetailView Video object so when I submit the rating it knows that the rating is for Video object that was on the DetailView? models.py class Video(models.Model): title = models.CharField(max_length=100, default="Community Video ") class Rating(models.Model): rate_choice = ((1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5')) rate_value = models.IntegerField(default=5, choices=rate_choice) video = models.ForeignKey('Video', related_name='video', null=True, default=1) views.py class VideoView(DetailView): model = Video template_name = 'video_view.html' class RatingView(CreateView): model = Rating template_name = 'rating_create.html' fields = ['rate_value', 'video'] Basically I want the primary key of the Video to go with me when I go from the video_view to rating_create template. I am thinking of just using function based views, class views are confusing me. -
Nginx gunicorn redirect not working and empty files
I am setting up a production server with nginx and gunicorn. I used the nginx.conf from the gunicorn examples pages and modified it: worker_processes 1; user mypolls webapps; # 'user nobody nobody;' for systems with 'nobody' as a group instead pid /var/run/nginx.pid; error_log /webapps/mypolls/logs/nginx.error.log; events { worker_connections 1024; # increase if you have lots of clients accept_mutex off; # set to 'on' if nginx worker_processes > 1 # 'use epoll;' to enable for Linux 2.6+ # 'use kqueue;' to enable for FreeBSD, OSX } http { # fallback in case we can't determine a type default_type application/octet-stream; access_log /webapps/mypolls/logs/nginx.access.log combined; sendfile on; upstream app_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response # for UNIX domain socket setups server unix:/webapps/mypolls/run/gunicorn.sock fail_timeout=0; # for a TCP configuration # server 192.168.0.7:8000 fail_timeout=0; } server { # if no Host match, close the connection to prevent host spoofing listen 80 default_server; return 444; } server { # use 'listen 80 deferred;' for Linux # use 'listen 80 deferred;' for Linux # use 'listen 80 accept_filter=httpready;' for FreeBSD listen 80; client_max_body_size 4G; # set the correct host(s) for your site server_name 192.168.1.17; … -
Django File Upload Run a function on a file and store in a database?
So I am uploading files into my database in django. To do this I am using django-database-files. What I want to do though is to run a function on the uploaded file so I won't have to read the file every time and so I can query some information. I want one table with just the stored files (so this doesn't have to be queried often) and another table that is populated by reading and parsing the file. Here is a basic overview of how I have my models setup: class Report(models.Model): #Machine Run File report = models.FileField(upload_to='not required') class Report_Info(models.Model): start_time = models.DateTimeField() ... I have more fields that are calculated from the file file = ForeignKey(Report) I am wondering how I can upload the file and also populate the Report_Info model based on the file that was uploaded? -
Adding non-field args to GraphQL queries in graphene
I have an object type that includes latitude and longitude. I'd like to implement a query node that allows me to query objects based on these fields, something like: { nearbyAirports(country: "US", lat: 40.123, lng: 80.234, dist: 10.0, unit: "mi") { edges { node { name code } } } } where the resolver looks like: def resolve_nearby_airports(self, args, context, info): qs = Airport.objects for attr in ['country', 'subdivision', 'airport_type']: terms = getattr(self, attr) if len(terms) == 1: qs = qs.filter(**{attr: terms[0]}) elif len(terms) > 1: query = None for t in terms: if query is None: query = Q(**{attr: t}) else: query = query | Q(**{attr: t}) qs = qs.filter(query) if all(map(lambda x: getattr(self, attr, None) is not None, ['dist', 'unit', 'lat', 'lng'])): dist = Dimension(value=self.dist, unit=self.unit).convert('km') point = 'POINT({} {})'.format(self.lng, self.lat) origin = GEOSGeometry(point) qs = qs.filter(point__distance_lte=( origin, D(km=dist.value))).annotate(dist=Distance('position', origin)) return qs to retrieve the names and codes of airports that are within the US and within 10 miles of the given point. The problem is that dist and unit aren't fields in AirportNode so the query node doesn't accept them as elements in the args parameter of the resolver. How do I tell the query that these … -
Django best practice. Forms
I have a question related to forms in django(i'm new on it) Look. Here i have form that looks like: class ProccessAgentForm(forms.Form): agent_id = forms.HiddenInput() main_name = forms.IntegerField() company_name = forms.CharField(max_length=60) company_state = forms.CharField(max_length=60) company_city = forms.CharField(max_length=60) company_country = forms.CharField(max_length=60) company_post_code = forms.IntegerField() agent_first_name = forms.CharField(max_length=60) agent_last_name = forms.CharField(max_length=60) agent_phone = forms.CharField(max_length=60) agent_fax = forms.CharField(max_length=60) agent_email = forms.EmailField() agent_city = forms.CharField(max_length=60) agent_post_code = forms.IntegerField() agent_state = forms.CharField(max_length=60) agent_country = forms.CharField(max_length=60) signer_first_name = forms.CharField(max_length=60) signer_last_name = forms.CharField(max_length=60) signer_title = forms.CharField(max_length=60) And i parsed it like(i know it's not the best choice): form = ProccessAgentForm(request.POST) if form.is_valid(): .... designated_company = DesignatedCompany() designated_company.pdf_link = copyright_agent.pdf_link designated_company.name = request.POST['company_name'] designated_company.address = company_address designated_company.city = request.POST['company_city'] designated_company.post_code = request.POST['company_post_code'] designated_company.state = request.POST['company_state'] designated_company.country = request.POST['company_country'] designated_company.save() agent = DesignatedAgent() agent.company = designated_company agent.first_name = request.POST['agent_first_name'] agent.last_name = request.POST['agent_last_name'] agent.email = request.POST['agent_email'] agent.address = agent_address agent.city = request.POST['agent_city'] agent.country = request.POST['agent_country'] agent.post_code = request.POST['agent_post_code'] agent.state = request.POST['agent_state'] agent.fax = request.POST['agent_fax'] agent.phone = request.POST['agent_phone'] agent.save() and so on... How can i make it more readable? Should i split logic to forms ? I know about model Forms, but here i have foreign keys as you saw. I'd appreciate for more detailed response :) -
How can I Solve => ValueError No JSON object could be decoded [ Django server ]
ValueError at /message/ No JSON object could be decoded Request Method: GET Request URL: http://MY_IP:8000/message/ Django Version: 1.8 Exception Type: ValueError Exception Value: No JSON object could be decoded Exception Location: /usr/lib/python2.7/json/decoder.py in raw_decode, line 384 Python Executable: /usr/bin/python Python Version: 2.7.6 Python Path: ['/var/www/html/kakaohaksik', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', 'usr/local/lib/python2.7/dist-packages'] python 2.7 , Django 1.8 installed. Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view return view_func(*args, **kwargs) File "/var/www/html/kakaohaksik/dguhaksik/views.py" in answer received_json_data = json.loads(json_str) File "/usr/lib/python2.7/json/init.py" in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py" in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python2.7/json/decoder.py" in raw_decode raise ValueError("No JSON object could be decoded") Exception Type: ValueError at /message/ Exception Value: No JSON object could be decoded --------------------------------------------------------------------- python 2.7 , Django 1.8 installed. when i enter to ./message, it was occured. How can I solve it? -
How to implement server side paginaiion in django with bootstrap-table (http://issues.wenzhixin.net.cn/bootstrap-table)
i have elastic search project, in which there are more than millions of records. Currently I have used bootstrap table(http://issues.wenzhixin.net.cn/bootstrap-table/#options/client-side-pagination.html) client side pagination, i required to use server side pagination to load limited data. My views.py if request.method == 'GET': data = machine.objects.all() RECORDS_PER_PAGE = request.GET.get('records') if not RECORDS_PER_PAGE: RECORDS_PER_PAGE = 10 else: RECORDS_PER_PAGE = int(RECORDS_PER_PAGE) print RECORDS_PER_PAGE page = request.GET.get('page') if not page: page = 1 else: page = int(page) column = ['name',firstname,'lastname',etc] total_records = len(data) pagination_list = paginate_algo(total_records, page,RECORDS_PER_PAGE) limit = page * RECORDS_PER_PAGE obj = data[limit - RECORDS_PER_PAGE:limit] return render(request, 'template/display.html',{"paginate_list": pagination_list,"per_page" :RECORDS_PER_PAGE,"total":total,"page_list":page_list, "data_list" :obj,"column":column}) My display.html: <div class="box" > <table class = "pull-left table table-no-bordered" data-toggle="table" data-search="true" data-filter-control="true" data-pagination="true" data-filter-show-clear="true" data-show-export="true" data-show-columns="true" data-height="800"> <thead> {%for thead in column%} <th data-field="{{thead}}" data-filter-control="input" datasortable="true" data-visible="true" >{{thead}}</th> {%endfor%} </thead> <tbody> {%for item in data_list%} <tr> <td>{{item}}</td> </tr> {%endfor%} </tbody> </table> Above client side pagination works well, I want to conevert it to server side pagination , what i need to do for that. -
Receiving "NOT NULL constraint failed: home_page._order" error in Django model
I keep receiving the above error and I am still not sure what component of my code is violating this. Below is my modely.py: def get_image_path(instance, filename): return os.path.join('photos', str(instance.id), filename) # Create your models here. class Textbook(models.Model): founder = models.CharField(max_length=256) title = models.CharField(max_length=256) cover = models.ImageField(upload_to=get_image_path, blank=True, null=True) def __str__(self): return self.title class Page(models.Model): textbook = models.ForeignKey(Textbook,related_name="pages",blank=True, null=True) page_title = models.CharField(max_length = 256,blank=True, null=True) page_num = IntegerRangeField(min_value=0,max_value=256, blank=True, null=True) def getTextID(self): return self.textbook.id def __str__(self): return self.page_title def iterSave(self): pages = self.textbook.pages MAX_PAGE = pages.aggregate(Max('page_num')) try: cpy = pages.get(page_num = self.page_num) for page in pages: if page.page_num >= self.page_num: obj,created = Page.objects.update_or_create(page_title = page.page_title, page_num = page.page_num+1, textbook = page.textbook) except: if self.page_num > MAX_PAGE: obj,created = Page.objects.update_or_create(page_title = self.page_title, page_num = self.page_num+1, textbook = self.textbook) def save(self, *args,**kwargs): self.iterSave() super(Page,self).save(*args, **kwargs) class Section(models.Model): page = models.ForeignKey(Page,related_name="sections") section_title = models.CharField(max_length=256) text = RichTextField(config_name='awesome_ckeditor') def __str__(self): return self.section_title I understand it has something to do with the query functions but I am not sure what I have done incorrectly to generate this error. Here is my admin.py if it helps: admin.site.register(Section) admin.site.register(Textbook) admin.site.register(Page) and here is a helper function I have: from django.db import models class IntegerRangeField(models.IntegerField): def __init__(self, verbose_name=None, … -
How do I write tests for the functionality of admin pages?
Disclaimer: I'm new to Django and testing I have some models in Django admin, but I'm overriding the save_model() function of a particular model. I'm unable to test Model.create() because the admin save_model() override isn't called. What would be the right way to test this function? Any example code would be very much appreciated :) Here's mine: models.py class Page(models.Model): title = models.CharField(max_length=100) content = models.CharField(max_length=50000) path = models.CharField(max_length=300, unique=True, help_text='Leave this blank to automatically generate a path.', blank=True ) pub_date = models.DateTimeField('publication date', default=timezone.now) def __str__(self): return self.title admin.py class NavigationInline(admin.StackedInline): model = Navigation class PageForm(forms.ModelForm): content = forms.CharField(widget=TinyMCE(attrs={'cols': 120, 'rows': 20}) ) class Meta: fields = ('title', 'pub_date') model = Page class PageAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title', 'content', 'path']}), ('Scheduling', {'fields': ['pub_date'], 'classes': ['collapse']}), ] form = PageForm inlines = [NavigationInline] def save_model(self, request, obj, form, change): obj.save() # All kinds of craziness to be tested! -
Django manage.py returns ImportError: South
I'm trying to install OpenSurfaces on Ubuntu 12.4. It has a lot of dependencies (virtualenv, postgresql,celery, django etc). At some point install_all.sh runs migrate_database.sh. DIR="$( builtin cd "$( dirname "$( readlink -f "${BASH_SOURCE[0]}" )" )" && pwd )" source $DIR/load_config.sh set -x -e builtin cd $SRC_DIR sudo -u $SERVER_USER ./manage.py syncdb The last lines calls manage.py: import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) The last lines returns an error: + sudo -u www-data ./manage.py syncdb Traceback (most recent call last): File "./manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "/home/mitchell/opensurf/opensurfaces-master/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() File "/home/mitchell/opensurf/opensurfaces-master/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute django.setup() File "/home/mitchell/opensurf/opensurfaces-master/venv/local/lib/python2.7/site-packages/django/__init__.py", line 21, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mitchell/opensurf/opensurfaces-master/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/mitchell/opensurf/opensurfaces-master/venv/local/lib/python2.7/site-packages/django/apps/config.py", line 87, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named south I followed the traceback to the execute_from_command_line, where it appears to call ManagementUtility(argv).execute, which is where i lose track of whats going on. I used 'pip install south', which went fine, but the error persists. I thought that maybe the manage.py is executed in a virtual environment, so i made sure to use 'pip … -
CSRF error in Django Rest Framework when the user is logged in
I am running an API built with Django Rest Framework(DRF). I am using AngularJs for my front-end, mainly for sending the requests to the API. However, I am facing a weird issue: If I am logged in using the admin panel, and I send the POST request, I get this error from my API: CSRF token missing However, if I log out and try again, the request just works. What's going on? It doesn't make much sense to me as I am clearly sending the requests from the same domain, not cross domain. Any help? -
Pymongo periodic_executor is most called in Django app
I am using Mongoengine 0.10.7 + Django-mongoengine + pymongo 3.4 with a django 1.10.3 app. As the load increased on our servers, the django app , suddenly and drastically, became CPU hungry. On thread profiling (by new relic) i found following result: link to periodic_executor.py : https://github.com/mongodb/mongo-python-driver/blob/master/pymongo/periodic_executor.py Can the function _run() be the one devouring the CPU? If yes, is there any way to fix it? PS. right now I'm using django-mongoengine only for creating the mongodb connections by sepecifying MONGODB_DATABASES in settings.py. -
How To a autoselect Patient Name field when bed assign to patients in Django
How To assign bed to Patient Django? when I try to assign bed to Patient at that time in bedconfig automatically select Patient Name view this image When click on assign bed then wardconfig file open but Patient name is blant, it must be autoselected Patient name -
Django - images not uploaded to form
I have a form on one of my Django pages, on which I am trying to allow the user to upload a couple of images to the database. The template code that is handling the upload of the images is: {% if presentation_form.instance.id %} {# PDF uploads #} {% with drawing_form=drawing_formset|getval:forloop.counter0 %} {# budget_pdf_form=budget_pdf_formset|getval:forloop.counter0 #} <tr> {% if not forloop.last %} <td colspan="3"><label>Drawings</label></td> {% endif %} {% for d_field in drawing_form.visible_fields %} {% if drawing_form.instance.pdf %} <td colspan="3" class="center"> <a class="button file-download pdf" href="{% url 'costing:pdf_open' presentation_form.instance.id %}?pdf=drawings" target="_blank"></a><a class="pdf-clear" data-view-url="{% url 'costing:pdf_clear' presentation_form.instance.id %}?pdf=drawings"><img class="icon m-l-sm m-b-md" src="{% static "img/bin.png" %}"></a> <!-- Need a hidden field to actually hold the file that's uploaded to the form --> <input type="hidden" name = "conceptDrawing" value="{{d_field.title}}"> </td> {% else %} <td colspan="3">{{d_field}}</td> {% for d_hidden in drawing_form.hidden_fields %} <!--td class="hidden">{{d_hidden}}</td--> <td class="hidden"> {{budget_formset.as_table}} {{budget_formset.management_form}} </td> {% endfor %} {% endif %} {% endfor %} <tr> <td colspan="1" class="p-t-md"></td> <td colspan="4" class="p-t-md"><input type="submit" value="upload"></td> <td colspan="1" class="p-t-md"></td> </tr> </tr> {% endwith %} {# Add a similar with statement for budgetPDF form #} {% with budget_pdf_form=budget_pdf_formset|getval:forloop.counter0 %} <tr> {% if not forloop.last %} <td colspan="3"><label>Budget PDF package</label></td> {% endif %} </tr> <tr> {% for … -
AttributeError 'list' object has no attribute 'id'
I got an error, AttributeError at /ResultJSON/v1/results/ 'list' object has no attribute 'id' . In views.py of ResultJSON(child app),I wrote import json from collections import OrderedDict from django.http import HttpResponse def render_json_response(request, data, status=None): json_str = json.dumps(data, ensure_ascii=False, indent=2) callback = request.GET.get('callback') if not callback: callback = request.POST.get('callback') if callback: json_str = "%s(%s)" % (callback, json_str) response = HttpResponse(json_str, content_type='application/javascript; charset=UTF-8', status=status) else: response = HttpResponse(json_str, content_type='application/json; charset=UTF-8', status=status) return response def UserResult(request): results = [] results = OrderedDict([ ('id',results.id), ('name', results.name), ]) results.append(results) data = OrderedDict([ ('results', results) ]) return render_json_response(request, data) I really cannot understand why this error happen because my database(sqlite) has id column. I wanna make the system that get datas(id&name which are columns' name and these datas are in my database) from database and encode these datas into JSON. So,how can I fix this?I think maybe models.py is wrong...(Because the child app's models.py has no code.) -
Django-admin-Filter Light
I am Using Django-admin-filter Light in my project. For some reason my dropdown and some other CSS is not working properly but not all. I used dal dal_select2 dal_admin_filter and i think dal dal_select2 is not working From https://pypi.python.org/pypi/django-autocomplete-light in views.py class DistrictAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated() or not self.request.user.is_superuser: return SchoolDistrictProfile.objects.none() qs = SchoolDistrictProfile.objects.all() if self.q: qs = qs.filter(name__icontains=self.q) return qs[:10] and in admin.py class DistrictFilter(AutocompleteFilter): title = 'Search and Select District' parameter_name = 'district' autocomplete_url = 'district-autocomplete' Note : Css for adding the tags in the text field is not working. -
Refresh table after Ajax response(django)
I created a filter form and send it via ajax post request: $('#id_server').change(function(e) { $.post($("form").attr("action"), { action: 'filter', filter: $("#id_server").attr("name"), info: $("#id_server option:selected").attr("value"), }, function (response) { }); In the backend I filtering and recieving new queryset then I send new page to Ajax The question is how load page from the ajax response to the screen or only 1 filtered tag? -
Django database urls?
I am developing a Django app but unfortunately my laptop is broken and will take a month to get repaired. So mean while I am using a android app called Termux to work on the project. But Termux still doesn't have a postgresql package and don't want to mess my settings just for running the project. So how can I use dj_database_url packages to configure my databases using database urls?? -
save file to instance & s3 from filesystem
In our system we upload an mp3 file, do some processing on that file and then upload/save the enhanced file to s3. The original is also stored on s3, and that gets saved correctly. The problem I'm having is that when uploading/saving the enhanced file from disk, the app is hanging and not returning any success or error. The same problem happens if I try to save the original mp3 file from disk, so the problem is not related to the enhancement process, but I wanted to give background on why I'm needing to save the file from disk. Luckily this is reproducible through shell. Below is the model and the shell code which can reproduce this issue. class Episode(models.Model): """ An individual podcast episode """ def original_episode_upload_path(instance, filename): return 'podcasts/original/%s/%s' % (instance.show.id, filename) def enhanced_upload_path(instance, filename): return 'podcasts/%s/%s' % (instance.show.id, filename) original_episode_file = models.FileField(upload_to=original_episode_upload_path) enhanced_episode_file = models.FileField(upload_to=enhanced_upload_path, null=True, blank=True) and then here's how to produce the error in shell: from django.core.files import File enhanced_file_path = "/tmp/my_mp3_file.mp3" with open(enhanced_file_path, 'r', errors='ignore') as f: episode.enhanced_episode_file.save("my_mp3_file.mp3", File(f)) When I replace the enhanced_file_path to point to the originally uploaded file and the same problem happens. When I update episode.original_episode_file instead of episode.enhanced_episode_file I …