Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uploading image via AJAX and pass file name using Django form submission
I am new in web development and what I am trying to achieve is as follows: On a page where user create a blog User upload image to a CDN via ajax and page will show image after ajax success. The uploaded image to CDN has a new file name and obviously URL address but the filename in input type="file" remains to be the original file name. During form submission, the ajax-returned filename has to be submitted for server side processing. I am not sure if I am doing it the right way as how I would normally observe on many websites. My question is, how do people normally sync filenames in above case when an Ajax upload is used and the file name has been changed and stored in CDN prior to a final form submission? I am using Django but I guess that doesn't really make a huge difference. -
Django: running code on every startup but after database is migrated
I thought there was an easy answer to this in recent versions of Django but I can't find it. I have code that touches the database. I want it to run every time Django starts up. I seem to have two options: Option 1. AppConfig.ready() - this works but also runs before database tables have been created (i.e. during tests or when reinitializing the app without data). If I use this I have to catch multiple types of Exceptions and guess that the cause is an empty db: def is_db_init_error(e, table_name): return ("{}' doesn't exist".format(table_name) in str(e) or "no such table: {}".format(table_name) in str(e) ) try: # doing stuff except Exception as e: if not is_db_init_error(e, 'foo'): raise else: logger.warn("Skipping updating Foo object as db table doesn't exist") Option 2. Use post_migrate.connect(foo_init, sender=self) - but this only runs when I do a migration. Option 3. The old way - call it from urls.py - I wanted to keep stuff like this out of urls.py and I thought AppConfig was the one true path I've settled for option 2 so far as I don't like the flakey try/except but it often trips me up when I'm developing locally because I need … -
Django 1.10 - Formset repopulates deleted item
I built up the Formset with can_delete=true. Formset works fine. Problem is repopulating the form, because after the submit, user is redirected on the same form page. What bugs me, is that deleted item still remains in the form, even if it does no longer exists in DB. My forms.py: class BookForm(forms.ModelForm): class Meta: model = Book fields = ['title', 'description', 'author'] BookFormset = forms.modelformset_factory( Book, form=BookForm, fields=['title', 'description', 'author'], can_delete=True, extra=1 ) Submit view function: def submit(request): book_formset = BookFormset(request.POST) if book_formset.is_valid(): messages.add_message(request, messages.SUCCESS, 'Correct.') book_formset.clean() book_formset.save() else: messages.add_message(request, messages.ERROR, 'Error!') context = { 'book_formset': book_formset, } return render(request, 'sand/index.html', context) What I tried: In following screens I tried to delete Rabit the Crazy book. Screen before submit: Screen after submit: -
django signal.post_save not taking modified values
data = { 'can_view_order_list': instance.has_perm('orders.view_all_orders'), } this is the object that I am trying to send with request.post() and this is inside signal function. But the problem is as far as I understand signals.post_save.connect() is executed before the changes in DB are commited. the signal is executed when in django admin permissions for users change. The Django version is 1.6 -
Catching UnicodeEncodeError in Django render in a meaningful way
I have a python script which is used to create static html files using Djnago templates. it looks like follows: .... from django.template import Template, Context from django.conf import settings settings.configure() template = """ <!DOCTYPE html> <html lang="en"> .......................... .......................... </html> """ t = Template(template) c = Context({"field1":field1_from_program, "field2": some_dictionary, ...... ...... "field1000": some_other_list }) f1=open(args.name+'.html', 'w+') f1.write(t.render(c)) f1.close() In some occasions, I get the following error Traceback (most recent call last): File "script.py", line 726, in <module> main() File "script.py", line 720, in main f1.write(t.render(c)) UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 49046: ordinal not in range(128) I found some fields in the content were causing this error, so I added .encode('ascii', 'ignore').decode('ascii') to the variable which was causing this error. However, it is not obvious from the error log. There are many more such values, and the error message is not showing a verbose output on which field is causing this error. In other words, if "field100":value_for_field100,, I would want to know that it is the problem with value_for_field100 may be using a try catch block. Any tips would be much appreciated. -
Lines/Columns not showing on Line/Column charts using Django Chartit
I'm just starting out with Python/Django, and am trying to use the Chartit library to create some charts. I've followed the instructions here, to setup a project with a simple line and a column chart. I can see the values when I hover over the charts. But the lines or the columns themselves do not display, as seen in the screenshot below. Following is the code I have in place for these charts. MODEL: class MonthlyWeatherByCity(models.Model): def __str__(self): return str(self.month) + "(H: " + str(self.houston_temp) + ", B: " + str(self.boston_temp) + ")" month = models.IntegerField() boston_temp = models.DecimalField(max_digits=5, decimal_places=1) houston_temp = models.DecimalField(max_digits=5, decimal_places=1) VIEW: def weather_chart_view(request): #Step 1: Create a DataPool with the data we want to retrieve. weatherdata = \ DataPool( series= [{'options': { 'source': MonthlyWeatherByCity.objects.all()}, 'terms': [ 'month', 'houston_temp', 'boston_temp']} ]) #Step 2: Create the Chart object lcht = Chart( datasource = weatherdata, series_options = [{'options':{ 'type': 'line', 'stacking': False}, 'terms':{ 'month': [ 'boston_temp', 'houston_temp'] }}], chart_options = {'title': { 'text': 'Weather Data of Boston and Houston'}, 'xAxis': { 'title': { 'text': 'Month'}}, 'yAxis': { 'title': { 'text': 'Temperature'}} }) pcht = Chart( datasource = weatherdata, series_options = [{'options':{ 'type': 'pie', 'stacking': False}, 'terms':{ 'month': [ 'boston_temp', … -
Is inversion of control implemented in Django?
I come for .net background i used to work with asp.net MVC that implements the dependency injection through the container ( UnityContainer) that does the mappings between the interfaces and their implementation . Now am working with django i wonder if there is something similar ? -
Is there a limit to number of POST variables that a website on django can receive
I have a bulk of input field in a form on my webpage and I'm trying to receive the data in these input fields through POST request method but i am only getting a limited no of data . Not all of my input fields are included in POST dictionary . A little help would be appreciated, Thanks in advance ---------views.py-------------- def booked(request, movie): menu = Movies.objects.all()[:4] alpha = list(string.ascii_uppercase) if request.method == 'POST': time1 = request.POST.get('time') date1 = request.POST.get('date') location = request.POST.get('location') mul = request.POST.get('multiplex') mov = get_object_or_404(Movies, title__icontains = movie) multiplex = get_object_or_404(Multiplex, name = mul, location = location) time = Time.objects.get(timing = time1) date = Date.objects.get(date = date1) for alph in alpha: if alph == 'R': break else: for i in range(1,19): a = alph + str(i) seat = request.POST.get(a) if seat == False: try: addseat = Snumber.objects.get(seat_name = a, seat_avail = seat) removeseat = Snumber.objects.get(seat_name = a, seat_avail = True) seat = Seats.objects.get(movie_name = mov, multiplex_name = multiplex, date=date, time=time) if removeseat in seat: seat.seat_no.remove(removest) seat.seat_no.add(addst) except: pass seat = Seats.objects.get(movie_name = mov, multiplex_name = multiplex, date = date, time = time) else: reverse('home') return render(request, 'jtc/pay.html', { 'menu':menu, 'seat':seat}) -------------template.html------------- {% for seat in movie.seats_set.all … -
creating custom view for 404 error page in django
In my project I want to create custom view for 404 page setting.py DEBUG = False ALLOWED_HOSTS = ['*'] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(os.path.join(BASE_DIR), "media_cdn")ode here Urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) handler404 = 'myapp.views.handler404' handler500 = 'myapp.views.handler500' When I make DEBUG = False in settings.py file, static files not loading properly. Screenshot attached for same. static files not loading Please help me to solve this issue. -
Django: Field doesn't exist at clean_data
I have a form and want to submit the data. The data are complete at the request.POST, but not if i print the cleaned_data. forms.py class Form(forms.ModelForm): cn = forms.CharField(max_length=100, required=True) status = forms.BooleanField(initial=False, required=False) class Meta: model = Group fields = ['name', 'users', 'status'] def __init__(self, *args, **kwargs): super(Form, self).__init__(*args, **kwargs) def clean(self): print(self.cleaned_data) # error return self.cleaned_data However, I get only cleaned_data = {'name': 'testgroup', 'status': 0}. I get also the error message Select a valid choice. That choice is not one of the available choices. by forms.errors. If I call self.cleaned_data['users'] i get None. Why? Any ideas? -
Django Custom Template Tag Issue
I didnt find an option to get relational instance object from a queryset without help of templatetags, so I am trying as below mentioned using custom template tags in for loop. But getting this error: File "D:\Neon_ecl\Projects\shof\shof\smapy\views.py", line 276, in menulist 'p' :p File "C:\Python27\Scripts\tvapp_env\lib\site-packages\django\shortcuts.py", line 30, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Python27\Scripts\tvapp_env\lib\site-packages\django\template\loader.py", line 67, in render_to_string template = get_template(template_name, using=using) File "C:\Python27\Scripts\tvapp_env\lib\site-packages\django\template\loader.py", line 21, in get_template return engine.get_template(template_name) File "C:\Python27\Scripts\tvapp_env\lib\site-packages\django\template\backends\django.py", line 39, in get_template return Template(self.engine.get_template(template_name), self) File "C:\Python27\Scripts\tvapp_env\lib\site-packages\django\template\engine.py", line 160, in get_template template, origin = self.find_template(template_name) File "C:\Python27\Scripts\tvapp_env\lib\site-packages\django\template\engine.py", line 134, in find_template name, template_dirs=dirs, skip=skip, File "C:\Python27\Scripts\tvapp_env\lib\site-packages\django\template\loaders\base.py", line 44, in get_template contents, origin, origin.template_name, self.engine, File "C:\Python27\Scripts\tvapp_env\lib\site-packages\django\template\base.py", line 191, in __init__ self.nodelist = self.compile_nodelist() File "C:\Python27\Scripts\tvapp_env\lib\site-packages\django\template\base.py", line 233, in compile_nodelist return parser.parse() File "C:\Python27\Scripts\tvapp_env\lib\site-packages\django\template\base.py", line 518, in parse raise self.error(token, e) TemplateSyntaxError: Invalid block tag on line 28: 'pdscheck', expected 'empty' or 'endfor'. Did you forget to register or load this tag? In Template: <tbody>{% load smapy_extras %} {% for obj in pds %} {% pdscheck czpds obj %} {{ temppd }} {% if obj in p %}<tr style="color:red;">{%else%} <tr style="color:grey;">{%endif%} <th scope="row">{{ obj.id }}</th> <td>{{ obj.pd_name }}</td> <td>{{ obj.volume }}</td> <td>{{ obj.mrp }} … -
paypal ipn coming up invalid but checking the ipn response its verified
What I am getting: Paypal response 200 - suggesting that I am receiving the IPN information. This is also showing on my Django admin sign as I can see the IPN received and the IPN details. The IPN I am receiving on my Django admin side shows a RESPONSE = VERIFIED. Nonetheless, the response I am getting to my URL Receiver is coming back INVALID. (This is the r.text response that I am getting in the below code). Things I checked: As far as I can tell, I am posting and receiving from the Paypal Sandbox. I updated the Paypal settings to be UTF-8. I am using my paypal sandbox buyer email to buy and facilitator email to get the purchase. The code is pretty straight forwards below. Please let me know if more information is needed to assess where my issue is occurring. from django.core.urlresolvers import reverse from django.shortcuts import render, get_object_or_404, render_to_response from django.contrib.auth.models import User, Group from django.contrib.contenttypes.models import ContentType from django.views.decorators.csrf import csrf_exempt import requests import sqlite3 import time import sys import urllib.parse from paypal.standard.forms import PayPalPaymentsForm from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received, invalid_ipn_received from payment.models import Profile def payment_view(request): host = request.get_host() # … -
Dojo BorderContainer / ContentPane
I'm in traineeship in a company and I need to used the program of an other trainee who programmed it in 2012. So I have done some update but I have a problem : In the report of this trainee the web page was a column on the left with a "menu" for request, at the bottom a field for the result of request, and on all the remaining space a map with different information. For the moment the problem it's the map in region 'center' it's like in region 'top'. <body class="soria" > <div id="mainLayout" data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design: 'sidebar'"> <div id="mapLayout" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region: 'center', splitter: true" style="height:500px;"> <div id="map"></div> </div> <div id="leftLayout" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region: 'left', splitter: true, minSize: 330" style="min-width: 330px"> <p> {% include "Home/forms/formQueries.html" %} </p> <p id="messageLimitNumberLines" style="display: none">Le nombre de paramètres est limité à cinq. Vous ne pouvez pas en ajouter d'autres.</p> </div> <div id="datagridLayout" data-dojo-type="dijit/layout/ContentPane" style="min-height: 300px" data-dojo-props="region: 'bottom', splitter: true, minSize: 300"> <div id="datagrid" data-dojo-type="dojox/rid/DataGrid"> </div> </div> </div> </body> I don't know if you need an other code so tell me. Thanks you so much. -
Django invalid literal for int() with base 10: 'Stalone'
I'm trying to get the users that i'm marking as True on my website in data['checked_users']: models.py class Player(models.Model): jucator = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, related_name='jucator') porecla = models.CharField(max_length=50, null=True, blank=True) selectat = models.BooleanField(default=False) def __str__(self): return u'%s' % self.jucator views.py def check_user(request): data = dict() data['players'] = Player.objects.all() if request.method == 'POST': list_of_checks = request.POST.getlist('checks[]') # data['checked_users'] = list_of_checks data['checked_users'] = Player.objects.filter(jucator__in=list_of_checks) return render(request, 'checkbox.html', data) checkbox.html <body> {% block content %} <form action="" method="POST">{% csrf_token %} <table> {% if request.user.is_superuser %} {% for user in players %} <tr> <td><input type="checkbox" name="checks[]" value="{{ user.jucator }}" title="selected_players">{{ user.jucator }}<br></td> </tr> {% endfor %} <tr> <td><input type="submit" name="submit" value="Submit"></td> </tr> {% else %} {% for user in players %} <tr><td>{{ user.jucator }}</td></tr> {% endfor %} {% endif %} </table> {% for player in checked_users %} {{ player }} {% endfor %} </form> {% endblock %} </body> If I try this, it shows the players: data['checked_users'] = list_of_checks If I try with filter, I get this error: invalid literal for int() with base 10: 'Stalone' -
Database Table directly to django forms.py, not from models.py
Im using Django 1.11 and Sqlite3 database in local machine. Usually we will write our model in models.py and call this model in forms.py and we wll asign to the ModelForm. for example in forms.py from django import forms from models import MyModel class MyModelForm(forms.ModelForm): class Meta: model = MyModel and we will call this form to views.py and will render to template as html form. this how django works normally. In my case I have a table(Model) in the connected database, not in models.py, I can access this through sql browser, here how can I access that db table directly to the forms.py?. I can get all tables present in database by django connection from django.db import connection tables = connection.introspection.table_names() print tables Here Im getting all the tables present in the connected database, is there any way to use these tables to django forms and call it in views and render to template as a html forms? Can you guys please suggest me any possible way to achieve this. It will be very greatfull for me. Thanks in advance. -
How to set the value of a model field by performing an equation between other model fields
I want to set the value of a model field by performing an equation between other model fields. Here's my model: class Current(models.Model): time = models.IntegerField(default=0) post_score = models.ForeignKey(PostScore, blank=True, null=True) comment_score = models.ForeignKey(CommentScore, blank=True, null=True) Say I want to create a new field called rate, which is calculated by: (post_score + comment_score) / time Is this possible? -
Recursive data in django breadcrumb
I have a modele to manage categories which looks like: class Category(models.Model): code = models.IntegerField() name = models.CharField('name', max_length=200) slug = models.SlugField(max_length=200) parent = models.ForeignKey( "self", blank=True, null=True, related_name='subcategories') Now, suppose 3 categories: cat A Cat B where parent is cat A Cat C where parent is cat B I'd like to show a breacrumb where, for cat C, looks like to: Home > Categories > Cat A > Cat B > Cat C I can currently get: Home > Categories > Cat B > Cat C but I do not know how to get the parent of my parent. More generally, is there a way to build this breadcrumb dynamically fonction of parents ? Thanks -
download a file after rendering a template in django
I am trying to download a csv file and rendering a template at the same time after redirecting from a view but it only downloads the file ,doesn't render the template. I think it can be handled by middleware but finding an easier solution to it. class ProductUploadView(FormView): template_name ='upload.html' form_class = csvform success_url = 'response/' failed_rows = [] def post(self,request,*args,**kwargs): form = self.form_class(request.POST,request.FILES) file = request.FILES['csvfile'] csvfile = csv.reader(utf_8_encoder(file), dialect='excel', delimiter=',') csvfile.next() for row in csvfile: if row[1] in ['PRES','GEN','GEN'] and row[2] in ['CAPS','TAB','SYP','GEL','SUSP','INJ']: try: p, created = Product.objects.get_or_create(brand_name=row[0], category=row[1], defaults={'form' : row[2],'mrp':row[3],'ptr':row[4]}) except ValidationError: self.failed_rows.append(row) pass else: self.failed_rows.append(row) return HttpResponseRedirect(self.success_url) class UploadedView(ProductUploadView): template_name = 'response.html' rows = ProductUploadView.failed_rows def download_view(self,request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' writer = csv.writer(response) writer.writerows(self.rows) return response def get(self,request): response = TemplateResponse(request,self.template_name,{'num':len(self.rows),'failed_rows':self.rows}) response.add_post_render_callback(download_view) return response -
Django DisallowedModelAdminLookup for lookup in Admin list_filter
I have a Member model and an Organization model, joined via a PrincipleMembership model. PrincipleMembership has ForeignKey fields for Member and Organization. I have ModelAdmin classes for all three, and I've added list_filter = ['principlemembership__organization__type', ] to MemberAdmin. (Type is a choice field on Organization.) The filter renders the links perfectly, but when I click on them I get a DisallowedModelAdminLookup exception. I can fix it by overriding ModelAdmin.Lookup_allowed to permit principlemembership__organization__type__exact, but is this a bug in Django? I'm on Python 3.5.3 and Django 1.10. I have tried adding the same filters to OrganizationAdmin and PrincipleMembershipAdmin. I do not use a many to many join as I have other data on PrincipleMembership, such as From and To dates. I have tried making the filter explicitly a admin.ChoicesFieldListFilter. I have tried removing everything else from MemberAdmin except list_filter = ['principlemembership__organization__type', ]. -
What are the Swagger advantages over coreapi?
I'm new to the Django restframework world. I've played around with coreapi library to make Linux bash scripts to call my API. I'm confused of the potential advantages of swagger to do something like this. I know many people are using swagger for documentation, but for my use case (calling it from the linux command line from a shell script) doesn't seem to be a good fit. Am I missing something huge from Swagger that I'll regret later down the road? -
send cross domain request using python Requests: HTTP for Humans
i am using Requests: HTTP for Humans cross domain request using python but i am getting internal server error 500 My Code: def request_post(request): if request.method == 'POST': method_name = request.POST.get('method') url_data = request.POST.get('url') response_arr=send_api_request(url_data,method_name) return HttpResponse( json.dumps(response_arr), content_type="application/json" ) else: return HttpResponse( json.dumps({"nothing to see": "this isn't happening"}), content_type="application/json" ) def send_api_request(url,method): response_data = {} resp= requests.get(url) response_data['status']= resp.status_code response_data['headers']= resp.headers response_data['data']= resp.text return response_data -
Django filter objects by some fields and get the latest unique ones
I have a model defined as: from django.db import models class Book(models.Model): name = models.CharField(max_length=200) author = models.CharField(max_length=200) version = models.IntegerField(default=0) def __unicode__(self): return "%s : %s : %s" % (self.name, self.author, self.version) A book with same name and author is considered as the same book, but they can have different versions. I want to filter out the latest (by comparing version) book of (name + author), for example: There is such books: Good Time : Andy : 1 Good Time : Andy : 2 Good Time : Andy : 3 My Django Book : Jim : 1 My Django Book : Jim : 2 My Django Book : Jim : 3 Python Tutorial : Tom : 1 Python Tutorial : Tom : 2 Python Tutorial : Tom : 3 Python Tutorial : Tom : 4 I want to filter it with: from books.models import Book Book.objects.filter(something) And get expect result as: <Book: Good Time : Andy : 3> <Book: My Django Book : Jim : 3> <Book: Python Tutorial : Tom : 4> How can I write the filter? -
Django: CSRF is incorrect or missing
I have seen a number of forums and posts but still couldn't get the handle of it. Here in django doc, it says The CSRF middleware is activated by default in the MIDDLEWARE setting. If you override that setting, remember that 'django.middleware.csrf.CsrfViewMiddleware' should come before any view > middleware that assume that CSRF attacks have been dealt with. If you disabled it, which is not recommended, you can use csrf_protect() on particular views you want to protect (see below). In any template that uses a POST form, use the csrf_token tag inside the > element if the form is for an internal URL, e.g.: form action {% csrf_token %} Based on that, in my html template I did simply: <form id='frm' name='frm' method="post" action="{% url 'gettip' %}" > {% csrf_token %} <input type="text" name="tipid" name="tipid"> <input type="submit" value="Get Tip Value"/> </form> I expected the CSRF_token to create the hidden element since the middleware is already loaded. I see no element in the form and I get CSRF error. The form is not associated with any model. I haven't used forms.py either. My current view is simply to output something: def gettip(request): if request.POST: return HttpResponse('You requested a tip') #from a … -
Django-cms - slick js slider not working in draft mode but works fine in live state
As I mentioned in title slick js slider is not working in django-cms draft mode, but works wine in live state. How to correct this error? On image we see that in draft mode something goes wrong with divs in slider but they work correctly in live mode -
importing image to django page
I am trying to attach an image to my page (per https://docs.djangoproject.com/en/1.10/howto/static-files/#configuring-static-files), but it cannot be displayed: http://prntscr.com/evwern settings.py STATIC_URL = '/portfolio/' urls.py urlpatterns = [ url(r'^$', index, name='index'),] index.html {% load static %} <img src="{% static '/catalog/static/portfolio/oh_i_ah.jpg' %}" alt="My image" style="width:640px;height:473px;"/> Path to the image: mysite/portfolio/catalog/static/portfolio/oh_i_ah.jpg If I try to open the image in the new tab it throws: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/portfolio/catalog/static/portfolio/oh_i_ah.jpg