Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CharField not defined
from django.db import models class Pet(models.Model): SEX_CHOICES = [('M','Male'), ('F', 'Female')] name = CharField(max_length=100) submitter = CharField(max_length=100) species = CharField(max_length=30) breed = CharField(max_length=30, blank=True) description = models.TextField() sex = models.CharField(choices=SEX_CHOICES, max_length=1, blank=True) submission_date = models.DateTimeField() age = models.IntegerField(null=True) vaccinations = models.ManyToManyField('Vaccine', blank=True) class Vaccine(models.Model): name = models.CharField(max_length=50) With this code I am getting command line error when running "python manage.py makemigrations". name "CharField" is not defined. How to fix it. -
Django ORM - N rows per column. Convert SQL query to ORM query
Please convert this query - select l.id, l.product_category_id from clientapi_product l join clientapi_product r on l.product_category_id = r.product_category_id and r.id >= l.id where r.product_category_id in (1,3) group by l.id having count(*) < 5; As you can see, this query is a solution to "N rows per column value" problem, where, in this case, n = 5. So, in case you have another solution to this problem in Django ORM, that solution is also welcome. -
Django rest framework many=True serializer return unexpected result on overriding to_representation
class MyModelSerializer(serializers.Serializer): def to_representation(self, data): print(data) print(self.instance) # here data will be an object from the queryset. so this method(to_representation) will # be called as many times as number of objects in queryset (default = 10 objects) # we can get whole queryset from `self.instance` variable data_list = [{'a': 1}, {'b': 2}] # dummy data_list to check respone structure return data_list queryset = self.model.objects.all() serializer = MyModelSerializer(queryset, many=True) return Response(serializer.data) Now the problem is, serializer.data will have a a list of list and each sub list will have same data returned by to_representation method. i.e [ [{'a': 1}, {'b': 2}], [{'a': 1}, {'b': 2}], [{'a': 1}, {'b': 2}], [{'a': 1}, {'b': 2}], ... # This will be repeated number of times queryset has objects ] What is wrong with this approach. -
How to create pre_populated_field in admin django like slug
i want create a custum auto populated field in admin django like slug but calculate another thing , not slugify. how do this ? -
Django - attributes and redefined fields with a ModelForm?
I have been learning about how forms, and now ModelForms, work. In a video by Max Goodridge, he redefines a field for one of his ModelFields in his ModelForm class. That is, he manually adds a field to his ModelForm class that could have been auto-generated by the ModelForm framework. From what I have read and understood thus far, that may be something to avoid. Though, that is not where my question lies. I am wondering how redefining fields within a ModelForm class works. In the Django Docs, it is stated (with an example) that a ModelForm instance will have a form field for every model field specified. What happens then, when a form field is explicitly defined in a ModelForm instance? Are two fields generated or does ModelForm recognise that a field is already defined, thus not generating another one? Furthermore, what exactly does adding an attribute to a ModelForm instance in the views do? For example, I have seen this: form = ExampleForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user # herein lies my confusion What exactly is happening here? I have seen people do this and adding a timestamp as well, but I fail to understand … -
When conda install django, PermissionError(13, 'Permission denied')
When I run conda install django, I get the following error: Solving environment: done ==> WARNING: A newer version of conda exists. <== current version: 4.4.10 latest version: 4.4.11 Please update conda by running $ conda update -n base conda Package Plan environment location: /opt/anaconda/anaconda3 added / updated specs: - django The following NEW packages will be INSTALLED: django: 2.0.2-py36hd476221_0 Proceed ([y]/n)? y Preparing transaction: done Verifying transaction: done Executing transaction: failed ERROR conda.core.link:_execute(481): An error occurred while installing package 'defaults::django-2.0.2-py36hd476221_0'. PermissionError(13, 'Permission denied') Attempting to roll back. Rolling back transaction: done PermissionError(13, 'Permission denied') What should I do? -
Django, Redirect user to different page by user's type
I want to redirect user to different page by user's type when they login. I'm using django-allauth for login system and I created a profile table for user that has a OnetoOne field with the user table, like this.... #models.py class Profile(models.Model): TYPE_CHOICES = ( ('sup', 'supplier'), ('dis', 'distributor'), ) type = models.CharField(max_length=3, choices=TYPE_CHOICES, unique=True, null=True, blank=True, default=None) user = models.OneToOneField(User, on_delete=models.CASCADE) nationality = CountryField() company = models.CharField(max_length=50, unique=True, null=True, blank=True, default=None) phone = models.CharField(max_length=50, unique=True, null=True, blank=True, default=None) skype = models.CharField(max_length=50, unique=True, null=True, blank=True, default=None) address = models.CharField(max_length=50, unique=True, null=True, blank=True, default=None) After their login, they will access a view called "redirect". (exampale.com/app/rediect) for this view, I'm using this #views.py @login_required def redirect(request): if request.user.profile.filter(type='sup'): return redirect('/app/a') elif request.user.profile.filter(type='dis'): return redirect('app/b') However, when I access this page. There is a error File "/opt/project/app/views.py", line 27, in redirect if request.user.profile.filter(type='adv'): AttributeError: 'Profile' object has no attribute 'filter' Does anyone know what is the problem? -
How can I add a parameter when consuming a post service without this field being in the form?
I am sending by parameter upload_preset, and this corresponds to the name of the text field, but from javascript I would like to send another parameter called folder with the value, myvalue. how can I do it without needing to add another text field called folder? <form action="" method="post" enctype="multipart/form-data" onsubmit="AJAXSubmit(this); return false;"> <fieldset> <legend>Upload example</legend> <p> <label for="upload_preset">Unsigned upload Preset: <input type="text" name="upload_preset" value="xx">(set it <a href="https://cloudinary.com/console/settings/upload#upload_presets">here</a>)</label> </p> <p> <label >Select your photo: <input type="file" name="file"></label> </p> <p> <input type="submit" value="Submit" /> </p> <img id="uploaded"> <div id="results"></div> </fieldset> </form> window.AJAXSubmit = function (formElement) { if (!formElement.action) { return; } var xhr = new XMLHttpRequest(); xhr.onload = ajaxSuccess; xhr.open("post", "https://api.cloudinary.com/v1_1/xxx/image/upload"); xhr.send(new FormData(formElement)); } -
Django ModuleNotFoundError when adding app
I'm using Visual Studio with Python tools to develop my Django project. I've create an app through the IDE. However after adding the app into the INSTALLED_APPS in my settings.py, it is always giving me ModuleNotFound Error This is the directory structure. This is how I've added the app INSTALLED_APPS = [ # Add your apps here to enable them 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'kleis', ] Stacktrace Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x00000228FCA30A60> Traceback (most recent call last): File "C:\Users\Sam\Documents\Exceptions\Projects\Kleis\Backend Django\Server\Server\env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Sam\Documents\Exceptions\Projects\Kleis\Backend Django\Server\Server\env\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Users\Sam\Documents\Exceptions\Projects\Kleis\Backend Django\Server\Server\env\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\Sam\Documents\Exceptions\Projects\Kleis\Backend Django\Server\Server\env\lib\site-packages\django\core\management\__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Users\Sam\Documents\Exceptions\Projects\Kleis\Backend Django\Server\Server\env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Sam\Documents\Exceptions\Projects\Kleis\Backend Django\Server\Server\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Sam\Documents\Exceptions\Projects\Kleis\Backend Django\Server\Server\env\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\Users\Sam\Documents\Exceptions\Projects\Kleis\Backend Django\Server\Server\env\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'kleis' -
Django template: force choices on field and print display value with get_FOO_display()
I want a model with 5 choices, but I cannot enforce them and display the display value in template. I am using CharField(choice=..) instead of ChoiceField or TypeChoiceField as in the docs. I tried the solutions here but they don't work for me (see below). model.py: class Language(models.Model): language = models.CharField(max_length=20,blank=False) ILR_scale = ( (5, 'Native'), (4, 'Full professional proficiency'), (3, 'Professional working proficiency'), (2, 'Limited professional proficiency'), (1, 'Elementary professional proficiency') ) level = models.CharField(help_text='Choice between 1 and 5', default=5, max_length=25, choices=ILR_scale) def level_verbose(self): return dict(Language.ILR_scale)[self.level] class Meta: ordering = ['level','id'] def __unicode__(self): return ''.join([self.language, '-', self.level]) view.py .. def index(request): language = Language.objects.all() .. mytemplate.html <div class="subheading strong-underlined mb-3 my-3"> Languages </div> {% regroup language|dictsortreversed:"level" by level as level_list %} <ul> {% for lan_list in level_list %} <li> {% for lan in lan_list.list %} <strong>{{ lan.language }}</strong>: {{ lan.level_verbose }}{%if not forloop.last%},{%endif%} {% endfor %} </li> {% endfor %} </ul> From shell: python3 manage.py shell from resume.models import Language l1=Language.objects.create(language='English',level=4) l1.save() l1.get_level_display() #This is good Out[20]: 'Full professional proficiency' As soon as I create a Language instance from shell I cannot load the site. It fails at line 0 of the template with Exception Type: KeyError, Exception Value: … -
uWSGI + Django + Nginx - Runtime Error
First post on Stackoverflow + help is definitely needed: I'm trying to set up a Ubuntu 16.04 server to host my Django app but I'm running into a weird error with the uWSGI; whenever I run: uwsgi --socket test.sock --module api.wsgi:app --chmod-socket=66 I get this: Python version: 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] *** Python threads support is disabled. You can enable it with --enable-threads *** Python main interpreter initialized at 0x8025d0 uWSGI running as root, you can use --uid/--gid/--chroot options *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 72920 bytes (71 KB) for 1 cores *** Operational MODE: single process *** Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 890, in _find_spec AttributeError: 'ConfigurationImporter' object has no attribute 'find_spec' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./api/wsgi.py", line 14, in <module> from configurations.wsgi import get_wsgi_application File "/usr/local/lib/python3.5/dist-packages/configurations/wsgi.py", line 14, in <module> application = get_wsgi_application() File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File … -
__init__() missing 3 required positional arguments: - Django 2.0
This error happens when I try to access an instance of my model into admin, this is my models.py: from django.db import models class Repo(models.Model): name = models.CharField(primary_key=True, max_length=150) creation_datetime = models.DateTimeField() update_datetime = models.DateTimeField() def __init__(self, name, creation, update, *args, **kwargs): super(Repo, self).__init__(*args, **kwargs) self.name = name self.creation_datetime = creation self.update_datetime = update def __str__(self): return self.name class Stats(models.Model): name = models.CharField(primary_key=True, max_length=30) value = models.TextField() def __str__(self): return self.name This is my admin.py: from django.contrib import admin from webapp.models import Repo admin.site.register(Repo) This is the traceback: Internal Server Error: /admin/webapp/repo/add/ Traceback (most recent call last): File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/contrib/admin/options.py", line 551, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/contrib/admin/sites.py", line 224, in inner return view(request, *args, **kwargs) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/contrib/admin/options.py", line 1508, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/utils/decorators.py", line 67, in _wrapper return bound_func(*args, **kwargs) File "/home/kristian/.virtualenvs/gitjavier/lib/python3.4/site-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File … -
Why does Django raised IntegrityError :null value in column "user_id" violates not-null constraint when a form is committed?
I have a UserSession model that creates a session that uses the IPaddress, and city data to populate the model using Geip2. I set up a form that takes the info that I want the user to enter but get: **django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint** when I submit the form. The object gets created but the information that the form takes doesn't save to the object. views: class NewLocationCreateForm(CreateView): model = UserSession success_url = reverse_lazy('post:index') form_class = NewLocationCreateForm def form_valid(self, form): if form.is_valid(): roote = Post.objects.filter(owner =self.request.user) instance = form.save(commit=False) instance.owner = self.request.user user_logged_in.send(self.request.user, request=self.request) return super(NewLocationCreateForm, self).form_valid(form) def get_form_kwargs(self): kwargs = super(NewLocationCreateForm, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs The problem seems to arrive at at is: if form.is_valid(): return super(NewLocationCreateForm, self).form_valid(form) The user session call of the Geoip2 seems to work but it doesn't save the form forms.py from .models import UserSession from post.models import Post from django import forms class NewLocationCreateForm(forms.ModelForm): class Meta: model = UserSession fields = [ 'g_post', 'coordinate', 'place_name' ] def __init__(self,user=None, *args, **kwargs): super(NewLocationCreateForm, self).__init__(*args, **kwargs) self.fields['g_post'].queryset = Post.objects.filter(owner=user) models.py: from django.conf import settings from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import User from django.db.models.signals import pre_save … -
Accessing a field on a Django model that is linked to a different model via the User model
I have the following models: class Reputation(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) score = models.IntegerField(default=0) .... class Article(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL) .... I am trying to access the "score" field on the Reputation model from an Article object. I tried the following on an Article object (article_object), but it does not work: article_object.created_by.reputation_set.score Is there any way I can access "score" from an Article object? Thank you. -
Connecting React Frontend to Django Backend
I have been looking at plenty of tutorials namely [this] (https://blog.cloudboost.io/react-redux-webpack-3-django-nov-2017-53a09d09cf75) and a blog [posted] (http://v1k45.com/blog/modern-django-part-1-setting-up-django-and-react/) 4 months ago. Do these still apply with the update to Django? If not, can someone send me in the right direction? -
Django: request to database or substitution value
Im study the Django. Essence: I check the user lang and replace text depending on the language but does not work. def check_lang(chat_id): # Проверка языка global language con = lite.connect('db.sqlite3') cur = con.cursor() sql = "SELECT Lang FROM Userprofile WHERE Id={} ".format(chat_id) cur.execute(sql) lang_user = cur.fetchone() if lang_user is None: language = "request_base.english" elif lang_user[0] == 'English': language = "request_base.english" else: language = "request_base.russian" def settinngs(chat_id, message): check_lang(chat_id) global language request_base = Loclizationmain.objects.get(keys__exact='change_city') change_city_text = language request_base = Loclizationmain.objects.get(keys__exact='button_subs') button_subs_text = language The model 'Loclizationmain' contains three field: keys, russian, english Сan i create in Queryset this request? SELECT {} FROM aut_loclizationmain WHERE keys={} " .format(language, chat_id) -
show price and rating in facet search
I want to show rating and price range in facet search however the rating is not displayed and price range is displayed but is disabled. What else should i have to do to show them in facet search? This is the source code of django-oscar. Here is the configuration FURNITURE_SEARCH_FACETS = { 'fields': OrderedDict([ ('product_class', {'name': _('Type'), 'field': 'product_class'}), ('rating', {'name': _('Rating'), 'field': 'rating'}), ]), 'queries': OrderedDict([ ('price_range', { 'name': _('Price range'), 'field': 'price', 'queries': [ # This is a list of (name, query) tuples where the name will # be displayed on the front-end. (_('0 to 20000'), u'[0 TO 20000]'), (_('20000 to 40000'), u'[20000 TO 40000]'), (_('40000 to 60000'), u'[40000 TO 60000]'), (_('60000+'), u'[60000 TO *]'), ] }), ]), } class ProductIndex(indexes.SearchIndex, indexes.Indexable): # Search text text = indexes.CharField( document=True, use_template=True, template_name='search/indexes/product/item_text.txt') name = indexes.EdgeNgramField(model_attr='name', null=True) name_exact = indexes.CharField(model_attr='name', null=True, indexed=False) # Fields for faceting product_class = indexes.CharField(null=True, faceted=True) category = indexes.MultiValueField(null=True, faceted=True) price = indexes.FloatField(null=True, faceted=True) num_in_stock = indexes.IntegerField(null=True, faceted=True) rating = indexes.IntegerField(null=True, faceted=True) # Spelling suggestions suggestions = indexes.FacetCharField() date_created = indexes.DateTimeField(model_attr='created_at') date_updated = indexes.DateTimeField(model_attr='updated_at') _strategy = None def get_model(self): return get_model('catalogue', 'Product') def index_queryset(self, using=None): # Only index browsable products (not each individual child product) return … -
Django Sending Nav Pill Selection
I have two pills here: I just want to be able to click on them and have a variable be sent to my 'views' code to tell me which one is selected. Here is the html: <div class="col-md-2" id = "charts_tables"> <ul class="nav nav-pills nav-stacked" id = charts_tables> <li {% if type_display == 'charts' %} class="active"{% endif %}><a href="" name = "radio-option" class="text-primary" {{type_display}} == 'charts'><i class="fa fa-fw fa-bolt"></i> Charts</a></li> <li {% if type_display == 'tables' %} class="active"{% endif %}><a href="" name = "radio-option" class="text-primary" {{type_display}} == 'tables'><i class="fa fa-fw fa-calendar"></i> Tables</a></li> </ul> Ideally, when pushed I'd like to set the "type_display" variable to the name of the selected pill and pass that variable to my view file. I tried to make a similar post, but the only answer I receieved was to use radio buttons. For this project it has to be nav pills. Here's the top of my view: def analysis_view(request, action=None): print(request.GET.get("radio-option")) I've been trying to find documentation for the past two days and nothing. I don't even see a nav-pills widget type in any docs. Any help would be greatly appreciated. -
Django query limit 2000 for Postgresql Psycopg2
I have Django app and using postgresql with psycopg2. I observed that there is maximum limit of 2000 records of data which can be retrieved and saved. It might have to do with psycopg2 or postgresql. Is there any way I can increase this limit or make it unlimited? -
How do I use matplotlib to produce plots on Django admin dashboard?
I want to customize the plots myself using matplotlib and show them on the Django admin dashboard. Can anyone tell me how to do this? Thanks! -
Python Matplotlib Django : out of stack space (infinite loop?)
I am trying to generate a graph using matplotlib in django. If I load a large csv file and generate a graph it works as expected. However if I do the same process again I see the below error: TclError: out of stack space (infinite loop?) What is causing this and how can I resolve this issue. Anything comment is welcome. Code: from django.shortcuts import render from django.conf import settings from django.core.files.storage import FileSystemStorage from django.shortcuts import redirect import csv import pandas as pd import matplotlib.pyplot as plt import re import sys import gc GraphName = "" YLabel = "" YColumns = "" XLabel = "" XColumns = "" file = "" ip = "" tmp_file_name = "" def get_form_inputs(request): global GraphName global YLabel global YColumns global XLabel global XColumns global file global ip GraphName = "" YLabel = "" YColumns = "" XLabel = "" XColumns = "" file = "" ip = "" tmp_file_name = "" GraphName = request.POST.get("GraphName") YLabel = request.POST.get("YAxisLabel") YColumns = [request.POST.get("YInputs")] for num in range(1,20): if request.POST.get("YInputs"+str(num)+"") is None: break YColumns.append(request.POST.get("YInputs"+str(num)+"")) XLabel = request.POST.get("XAxisLabel") XColumns = [request.POST.get("XInputs")] file = request.FILES['file'] ip = request.META['REMOTE_ADDR'] def process_validate_csv_file(): global tmp_file_name tmp_file_name = 'tmp_graph'+ip+'.csv' try: with open(tmp_file_name, 'w') … -
Why can't I iterate over this queryset?
I am trying to use a basic for loop to iterate over this query and it is giving me a "Company is not iterable" error. Any help? def activate(request, uidb64, token, pk): try: uid = force_text(urlsafe_base64_decode(uidb64)) company = Company.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, Company.DoesNotExist): company = None if company is not None and account_activation_token.check_token(company, token): pmm_date = Thursday.objects.get(pk=pk) company.is_registered = True company.save() pmm_date.assigned_company = company pmm_date.save() automatic_denial_list = Company.objects.exclude(company).filter(pmm_date=pmm_date) current_site = get_current_site(request) for company in automatic_denial_list: if company.email_one or company.email_two: mail_subject = 'Denied Pizza My Mind Visit' message = render_to_string('thursdays/denied_visit.html', { 'user': company.name, 'domain': current_site.domain, }) to_email = company.email_one if company.email_one else company.email_two email = EmailMessage(mail_subject, message, to=[to_email]) email.send() # company.delete() return redirect('/') else: return HttpResponse('Activation link is invalid!') The error is when I define automatic_denial_list. Thanks! -
ConnectionAbortedError after choosing an image to upload
This is a pretty long question and I really appreciate your time - hopefully most part of the pasted codes you can just skim through. I have been working on a Django project which involved user uploading images (and cropping/rotating the image on the client side, before sending the final image to the server). The JavaScript Image Cropper I found and used is Croppie, with some basic customization. The whole process was working at that time (about 4 months ago, Nov. 2017), but then I set the project aside. I've recently picked it back up, and with some new package updates, I've made some minor modifications to the Django code, but DID NOT touch the JavaScript/HTML part. I was surprised that when I tried to upload an image, the console threw a ConnectionAbortedError and triggered some downstream errors, very much like encountered in this question. The full error log is as follows: Traceback (most recent call last): File "c:\users\xurub\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "c:\users\xurub\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "c:\users\xurub\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "c:\users\xurub\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "c:\users\xurub\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "c:\users\xurub\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 453, in … -
Django "The submitted file is empty"
I have used multiple FileFields in a model and my app gives error "The submitted file is empty" on execution, folowing are the details of my code: My models.py: class KBCTest(models.Model): algorithm = models.CharField(max_length=10, blank=False) entityFile = models.FileField(blank=False, upload_to=updateFilename, validators=[validateTestingFileExtension]) relationFile = models.FileField(blank=False, upload_to=updateFilename, validators=[validateTestingFileExtension]) My forms.py class KBCTestForm(forms.ModelForm): class Meta: model = KBCTest fields = ('algorithm', 'entityFile', 'relationFile') def clean(self): super(KBCTestForm, self).clean() data = self.cleaned_data return data My views.py: def testing(request): title = 'Testing' template = 'testing.html' form = '' if request.method == 'GET': form = KBCTestForm() if request.method == 'POST': form = KBCTestForm(request.POST, request.FILES) if form.is_valid(): form.save() runAlgo = Run(form.cleaned_data) runAlgo.configAndTest() return HttpResponseRedirect(reverse('learning', kwargs={'function': 'testing'})) context = {'title': title, 'form': form} return render(request, template, context) My template: {% if request.user.is_authenticated %} <div class='col-sm-4 col-sm-offset-4'> <h1>{{ title }}</h1> <!-- If form not rendered(i.e. views context) don't show submit button --> {% if form %} <!-- Use 'csrf_token' to prevent cross-site forgery --> <form enctype='multipart/form-data' method='POST', action=''> {% csrf_token %} {{ form|crispy }} </br> {{ form.non_field_errors|crispy }} <input type='submit' value='Test' class='btn btn-default'/> </form> {% endif %} </div> {% endif %} When I run this template it fails to validate the form and gives error "The submitted file is empty" error … -
display list in django template
I have a list of tuples which looks something like the following: answer_guess_list = [('A',), ('B', 'C',), ('A', 'B', 'C', 'D',)] In my templates, I have a template variable with the same name. {% for guess_list in answer_guess_list %} <p> {% for guess_value in guess_list %} {{ guess_value }}, # Notice the comma (,) {% endfor %} </p> {% empty %} <p>Nothing to show.</p> {% endfor %} It displays the list as the following: A, B, C, A, B, C, D, I don't want the terminal commas and rather display it as A B, C A, B, C, D Please suggest changes or provide hints to achieve the same.