Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I build 'location auto-complete' like Facebook in Django?
How can I build 'location auto-complete' like Facebook? Should I send Ajax request everytime the user type a letter? For example, if user type 'atlanta', then how does Facebook check and find 'Atlanta, GA'? And How can I build the exact same thing in Django??? Thank you so much! -
django model manager or django queryset
I was reading django docs and these two classes seemed similar, here is the sample from django docs: class PersonQuerySet(models.QuerySet): def authors(self): return self.filter(role='A') def editors(self): return self.filter(role='E') class PersonManager(models.Manager): def get_queryset(self): return PersonQuerySet(self.model, using=self._db) def authors(self): return self.get_queryset().authors() def editors(self): return self.get_queryset().editors() class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) role = models.CharField(max_length=1, choices=(('A', _('Author')), ('E', _('Editor')))) people = PersonManager() In the sample code as you can see code in PersonQuerySet can be moved to PersonManager (or move manager to query set) - my point is I can merge one to another without any problem) so what is the difference between manager and queryset? do they have different use cases? or should I simply use one of them and ignore existance of the other one? -
Using PyMongo as Django backend
I'm writing an application with django and I want to use mongoDB as my database. I have searched around a lot and found mongoengine and Pymongo as possible choices. I have decided to got with PyMongo for the time being. But the thing is that I am unable to connect my app to mongoDB. I have tried following so far: from pymongo import MongoClient client = MongoClient() db = client['user_central'] But it doesn't work as it should. Something has to be put in the DATABASES django variable and that's where I'm caught up. How can I connect my django app to mongoDB and use mongo as my Django Backend?? Any help would be appreciated. -
Django MemoryError if degug = True
I am getting the following error when I make queries to my app throught custom forms: Environment: Request Method: GET Request URL: http://34.212.77.49/anagrafiche/insolventi/?anno=2010 Django Version: 1.11.4 Python Version: 3.5.2 Installed Applications: ['django_jinja', 'rest_framework', 'quotemanage', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar'] Installed Middleware: ['debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'quotemanage.middleware.customMiddleware.NavMenuMiddleware'] Traceback: File "/var/www/appWSGI/env/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/var/www/appWSGI/env/lib/python3.5/site-packages/django/utils/deprecation.py" in __call__ 142. response = self.process_response(request, response) File "/var/www/appWSGI/env/lib/python3.5/site-packages/debug_toolbar/middleware.py" in process_response 132. panel.generate_stats(request, response) File "/var/www/appWSGI/env/lib/python3.5/site-packages/debug_toolbar/panels/sql/panel.py" in generate_stats 192. query['sql'] = reformat_sql(query['sql']) File "/var/www/appWSGI/env/lib/python3.5/site-packages/debug_toolbar/panels/sql/utils.py" in reformat_sql 27. return swap_fields(''.join(stack.run(sql))) File "/var/www/appWSGI/env/lib/python3.5/site-packages/sqlparse/engine/filter_stack.py" in run 34. for stmt in stream: File "/var/www/appWSGI/env/lib/python3.5/site-packages/sqlparse/engine/statement_splitter.py" in process 82. for ttype, value in stream: File "/var/www/appWSGI/env/lib/python3.5/site-packages/debug_toolbar/panels/sql/utils.py" in process 14. for token_type, value in stream: File "/var/www/appWSGI/env/lib/python3.5/site-packages/sqlparse/lexer.py" in get_tokens 60. m = rexmatch(text, pos) Exception Type: MemoryError at /anagrafiche/insolventi/ Exception Value: I do not know if it is caused by an error somewhere in my code, however the Traceback is not giving me any idea! In my settins.py if a set DEBUG = False this error no longer exist. I have no idea what to do, I sure need to have my Debug option set to True. -
Can not add bootstrap class with button using Django and Python
I am trying to add bootstrap class in button using Django and Python but it could not added at all. I am explaining my code below. control.html: {% extends 'base.html' %} {% block content %} <center><h1>Welcome</h1> <div class="boxwidthdiv"> <form method="post" action="{% url 'plantsave' %}"> {% csrf_token %} <div class="boxwidthinnerdiv"> Nuclear Mini Plant <br /><br /> <select name="react"> <option value="Reactor1">Reactor 1</option> <option value="Reactor2">Reactor 2</option> <option value="Reactor3">Reactor 3</option> </select> <br /><br /><br /><br /> <button class="buttondiv" name="strt" type="submit" class="btn btn-success">Start</button> <button class="buttondiv" name="shutbt" type="submit" class="btn btn-danger">Shut Down</button> <button class="buttondiv" name="susbtn" type="submit" class="btn btn-info">Suspend</button> </div> </form> </div> {% endblock %} base.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> {% load static %} <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <script type="text/javascript" src="{% static 'js/bootstrap.min.js' %}"></script> </head> <body> <header> <h1>Nuclear Reactor</h1> {% if count > 0 %} <b>Hi, {{ user.username }}</b> <a href="{% url 'home' %}">Home</a> <a href="{% url 'view_reactor' %}">View Reactor status</a> <a href="{% url 'logout' %}">logout</a> {% else %} <a href="{% url 'login' %}">login</a> / <a href="{% url 'signup' %}">signup</a> {% endif %} <hr> </header> <main> {% block content %} {% endblock %} </main> </body> </html> Here I could not added the classes at all. Please help me to resolve … -
Django website with Wordpress
I have a website developed with Django. I want to add a blog to the website. If I choose Wordpress for the blog, can I unify the Wordpress blog with the Django website ? If yes, how ? The Wordpress blog can be access with this url : www.website-adress.com/blog ? Can be share the Django database with the Wordpress blog ? I read this : https://www.reddit.com/r/django/comments/39fzgc/wordpress_and_django_coexisting/ and someone speaking about configuration in nginx/apache level... (I am using Webfaction for the webhosting) Thank you ! -
Converting image data string (str) back into bytes
inputFile gets the image data from a image file input <input type="file"> and converts the data into a string (str) to be used in sessions. createView converts the image data string back into image data (bytes) so it can be saved. However when trying to convert the image data string back into image data bytes: session_data = request.session.get('img_data') data = base64.b64encode(bytes(session_data, 'utf-8')) data2 = base64.decodestring(data) It changes the original image data, img_data = request.FILES.get('image').read() witch raises an error when trying to save the image to a ImageField: cannot identify image file <django.core.files.temp.TemporaryFile object at 0x0074B110> so my question is how do i convert the image data string session_data = request.session.get('img_data') back into the original image data (bytes) without altering the data. And i know i could have saved the image using one view that would make it a lot simpler, but createView needs to use this image data in multiple places / forms. i tried doing it this way but i could only use the image data in one form. import base64 def inputFile(request): form = InputFile(request.POST or None, request.FILES or None) if form.is_valid(): img_data = request.FILES.get('image').read() request.session['img_data'] = str(img_data) return redirect('picxs:create') def createView(request): session_data = request.session.get('img_data') data = base64.b64encode(bytes(session_data, … -
queryset django for last value of column if another column is equal to a value
I have a django video model and i want to get the last value of "nameoriginalvideo" if owner id is equal to the current user id. This is my mysql table equivalent to the model: This is what i tried but it didn't work: def teste(request): originalvideo = Videounwtm.objects.values('nameoriginalvideo').filter(owner_id = request.user.id).first().last() vle = originalvideo['nameoriginalvideo'] return render(request, 'teste.html', {'vle': vle}) Thank you in advance. -
How can i edit the content on my django website pages?
I'm a newbie to django and i have worked on a few projects and in all of them i used the django admin interface to manage the content, which obviously is the content from my models.My main concern is how or rather is there a way i can edit the content in areas like the about section or on my home page without changing the actual html on my code? -
Send weekly emails for a limited time after sign up in django
The Goal: Once a user has signed up they start a challenge. Once they've started the challenge I'd like to be able to send users weekly emails for 12 weeks (Or however long the challenge lasts for). Bearing in mind, one user may sign up today and one may sign up in three months time. Each week, the email will be different and be specific to that week. So I don't want the week one email being sent alongside week 2 for 12 weeks. Should I add 12 boolean fields inside the extended User model, then run checks against them and set the value to True once that week gas passed? Assuming this is the case. Would i then need to setup a cron task which runs every week, and compares the users sign up date to todays date and then checks off the week one boolean? Then use the post_save signal to run a check to see which week has been completed and send the 'week one' email? I hope that makes sense and i'm trying to get my head around the logic. I'm comfortable with sending email now. It's trying to put together an automated process as currently … -
Nginx, WSGI, Django - setting up web server
I'm quite new to setting up a web server and have been following these guides: http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html https://gist.github.com/evildmp/3094281 Since I'm working off a mac, I installed nginx through Homebrew: brew install nginx. I have been struggling to get my nginx server to serve my Django static file. I have followed the guides and have copied their mysite_nginx.conf and changed it according to my project paths: # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { # server unix:///path/to/your/mysite/mysite.sock; # for a file socket server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name .example.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /Users/Simon/Documents/WebServer/uwsgi-tutorial/mysite/media; # your Django project's media files - amend as required } location /static { alias /Users/Simon/Documents/WebServer/uwsgi-tutorial/mysite/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /Users/Simon/Documents/WebServer/uwsgi-tutorial/mysite/uwsgi_params; # … -
how to filter a django query set by a foreign key in restful framework?
i met a problem when using django + restful framework. here is my intention: there are many chapters, each chapter has many words, each word has many expand explanations, these explanations are offered by users, so some of them are invaild, in the backend i can set these expands' field is_alive to False. in the views.py, currently i send all these data to frontend, i tried many ways to filter these invaild data out, but failed. here are codes: models.py class Chapter(models.Model): chap = models.IntegerField('chaptername') class Word(models.Model): chapter = models.ForeignKey('Chapter', related_name='voca') word = models.CharField('name', max_length=255) class Expand(models.Model): belong = models.ForeignKey('Word', related_name='expand') explansion = models.TextField('description') is_alive = models.BooleanField('status', default=True) serializers.py class ExpandSerializer(serializers.ModelSerializer): class Meta: model = Expand fields = ('explansion', ) class WordSerializer(serializers.ModelSerializer): expand = ExpandSerializer(many=True) class Meta: model = Word fields = ('id', 'word', 'expand') class ChapterSerializer(serializers.ModelSerializer): voca = WordSerializer(many=True) class Meta: model = Chapter fields = ('id', 'chap', 'voca') views.py def getChapter(request): if request.method == 'GET': chapter = Chapter.objects.get(pk=1) serializer_c = ChapterSerializer(chapter) return JsonResponse(serializer_c.data) -
Database modeling for products and store with better category of products
I am planning to develop a virtual shopping mall where stores of any kind can be registered, such as in a physical shopping mall. First I want to develop an efficient and effective database modeling for products and stores only. I wanted it be very flexible and user friendly. Here is the model design for Product and Store. How can I improve the database design? My primary concern is for the categories be user friendly. For example Men -> Clothing -> Shirts as a category. If you wish, you can help me to improve the design as well, I would appreciate all recommendations. I am using Python 3 and Django 1.11. DAY = (( 'Sun', 'Sunday'), ( 'Mon', 'Monday'), ( 'Tue', 'Tuesday'), ( 'Wed', 'Wednesday'), ( 'Thu', 'Thursday'), ( 'Fri', 'Friday'), ( 'Sat', 'Saturday') ) class OpeningHours(models.Model): store = models.ForeignKey('Store', related_name="opening_hour") weekday = models.CharField(choices=DAY, max_length=12) opening_hour = models.TimeField() closing_hour = models.TimeField() class Meta: verbose_name = 'Opening Hour' verbose_name_plural = 'Opening Hours' def ___str__(self): return '{} {} - {}'.format(self.weekday, str(self.opening_hour), str(self.closing_hour)) class Store(models.Model): merchant = models.ForeignKey(User, blank=True, null=False) token = models.CharField(default=token_generator, max_length=20, unique=True, editable=False) name_of_legal_entity = models.CharField(max_length=250, blank=False, null=False) pan_number = models.CharField(max_length=20, blank=False, null=False) registered_office_address = models.CharField(max_length=200) name_of_store = models.CharField(max_length=100) email … -
AJAX call returns CSRF Failed
Iam doing an ajax call in Typescript which calls an internal Webservice. All endpoints whit "GET" are working, but whit "POST" it says "403 Forbidden" - "detail: CSRF Failed: CSRF cookie not set" Things i tried to fix the issue: Followed https://docs.djangoproject.com/ko/1.11/ref/csrf/ Tryed to delete 'django.middleware.csrf.CsrfViewMiddleware' Tryed @csrf_exempt Nothing of this has worked, everytime still the same error occurs. Here is my code in Typescript: sendMessage(message, receiverId){ let self = this; var message_obj = "{\"id\":\""+ GUID.generateGUID() +"\",\"message\":\""+ message +"\",\"receiverId\":\""+ receiverId + "\",\"moddate\":\""+ Date.now() +"\"}"; var message_json = JSON.parse(message_obj); $.ajax({ type: "POST", url: "/chat/message/", data:{"message_object":message_json}, credentials: 'same-origin', success: function (response) { alert(response); }, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); } }) } This is an example of an working ajax call: getMessages(){ let self = this; $.ajax({ type: "GET", url: "/chat/message/", dataType: "json", success: function (response) { response = JSON.stringify(response); alert(response); }, error: function(jqXHR, textStatus, errorThrown){ alert(errorThrown); } }) } I really hope someone can help me! -
Django authentication override not working
I created a file "authentication.py" at the same level as the "settings.py" file in my django project. The content of this file is: from django.contrib.auth.models import User class SettingsBackend(object): def authenticate(self, request, username=None, password=None): user_name = 'user_name' user_password = 'user_pass' login_valid = (user_name == username) pwd_valid = (password == user_password) if login_valid and pwd_valid: try: user = User.objects.get(username=username) except User.DoesNotExist: user = User(username=username) user.is_staff = True user.is_superuser = True user.save() return user return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None Then I added the following line in the "settings.py" file: AUTHENTICATION_BACKENDS = ('myProject.authentication.SettingsBackend',) However, the login doesn't work. It was working before these 2 modification when the user's credentials where stored in the database. I don't know how I can debug this. Any idea ? Here are some pieces of my settings file: INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'default', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["templates/"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = … -
Django queryset grouped by count of values in Postgres JSONField
My model: from django.contrib.postgres.fields import JSONField class Image(models.Model): tags = JSONField(null=False, blank=True, default={}) tags field value can be empty, or something like: [ {"tag": "xxx"}, {"tag": "yyy"}, {"tag": "zzz"} ] The number or dicts may vary (from 0 to N). I need to make a query that counts Images grouped by number of tags. Something like: { "0": "345", "1": "1223", "2": "220", ... "N": "23" } where the key is the number of tags, and the value is the count of Image objects that contains this number of tags. How can i do that? Thank you for your help! -
dj-stripe / djstripe not using my config vars for heroku deployment
I am on my way to installing djstripe, however, i get following error when doing pip install -r requirements.txt: CRITICALS: ?: (djstripe.C001) Could not find a Stripe API key. HINT: Add STRIPE_TEST_SECRET_KEY and STRIPE_LIVE_SECRET_KEY to your settings. In my settings.py i have used following code: STRIPE_LIVE_PUBLIC_KEY = os.environ.get('STRIPE_LIVE_PUBLIC_KEY') STRIPE_LIVE_SECRET_KEY = os.environ.get('STRIPE_LIVE_SECRET_KEY') STRIPE_TEST_PUBLIC_KEY = os.environ.get('STRIPE_TEST_PUBLIC_KEY') STRIPE_TEST_SECRET_KEY = os.environ.get('STRIPE_TEST_SECRET_KEY') STRIPE_LIVE_MODE = os.environ.get('STRIPE_LIVE_MODE') # True or False As I am working on heroku, i use an .env file in which I have following code: STRIPE_LIVE_PUBLIC_KEY = 'pk_test_xxxxxxxxxxxxxxxxxxxxxxxx' STRIPE_LIVE_SECRET_KEY = 'sk_test_xxxxxxxxxxxxxxxxxxxxxxxx' STRIPE_TEST_PUBLIC_KEY = 'pk_test_xxxxxxxxxxxxxxxxxxxxxxxx' STRIPE_TEST_SECRET_KEY = 'sk_test_xxxxxxxxxxxxxxxxxxxxxxxx' STRIPE_LIVE_MODE = 'False' Things should work, but somehow, I think my .env file is not taken into account while running. When I use the following format in my settings.py, things work out, but this means I am putting my keys in my code, which i would prefer not to do. STRIPE_LIVE_PUBLIC_KEY = os.environ.get('STRIPE_LIVE_PUBLIC_KEY', 'pk_test_xxxxxxxxxxxxxxxxxxxxxxxx') I had a similar issue with celery not migrating my settings.py. I solved this by putting following code inside my celery.py file: os.environ['DJANGO_SETTINGS_MODULE'] = 'myprogram.settings' probably a similar issue, but where would I have to put this? -
Slicing pandas dataframe using Django template tag 'slice'?
I have a pandas dataframe which I passed into Django HTML. I would like to subset the dataframe when printing it out using Django's template filter 'slice'. Slice works for list and django's object QuerySet but somehow it does not work when used with pandas dataframe. I would like to know WHY and HOW this can work. I slice for 1 rows in the example below but when my code run, it displays all 3 rows. Sample code: in views.py: ## Libraries from django.shortcuts import render from django.http import HttpResponse import pandas as pd def dataframe_view(request): ## Creating pandas dataframe d = {'alphabet': ['a','b','c'], 'num':[1,2,3]} df = pd.DataFrame(d) return render(request, 'dataframe.html', {'df':df}) in dataframe.html <html> <body> ... <table> <thead> <tr> <th>{{ df.columns.0 }} </td> <th>{{ df.columns.1 }} </td> <tr> </thead> <tbody> {% for index, row in df1.iterrows|slice:":1" %} <tr> <td> {{row.0}} </td> <td> {{row.1}} </td> </tr> </tbody> </table> </body> </html> -
Shopify Django Auth With Multiple Store
Am using Django Shopify Auth And I have a problem while login with multiple stores within the same browser. I found some issue of session. It store the same session for all the store. Below is my sample code : @login_required def home(request, *args, **kwargs): # Get a list of the user's products. with request.user.session: # shopify.ShopifyResource.clear_session() orders = shopify.Order.find(financial_status='paid') data = { "orders": orders } return render(request, "home.html", data) And While I run Shopify.ShopifyResource.clear_session() it's not clear the current session also. So please help me. Thanks in advance. -
How to create a randomly generated user profile within a city boundary in Geodjango?
Disclaimer: I have limited knowledge in python.I asked this question in gis.stackexchange, but was voted "unclear what you are asking", may be because it is a programming question, not gis? I have used randomly generate users python script from this source , while the command creates a postgis table, it does not create the randomly generate user profile (the table is empty). What is missing in creating the random user profile in the postgis table? from django.core.management.base import BaseCommand from django.contrib.gis.geos import Point import random import uuid import numpy as np from mymap_app.models import LoveFinderUser class Command(BaseCommand): help = 'generate 1M users for Addis_Ababa with random sex, age, radius, location' def handle(self, *args, **options): Addis_Ababa__lat__min = 8.834544 Addis_Ababa__lat__max = 9.099231 Addis_Ababa__lng__min = 38.640241 Addis_Ababa__lng__max = 38.907086 for i in xrange(10**5): new_random_lat = random.uniform(Addis_Ababa__lat__min, Addis_Ababa__lat__max) new_random_lng = random.uniform(Addis_Ababa__lng__min, Addis_Ababa__lng__max) user_age = random.randrange(18, 55) user_delta_plus = random.choice([1, 2, 3, 5, 8, 13]) user_delta_minus = random.choice([1, 2, 3, 5, 8, 13]) user_sex = random.choice(['F', 'M']) user_prefered_sex=random.choice(['F', 'M']) new_user=LoveFinderUser.objects.create( nickname=str(uuid.uuid4()), age=user_age, sex=user_sex, prefered_sex=user_prefered_sex, prefered_age_min=(user_age-user_delta_minus), prefered_age_max=(user_age+user_delta_plus), last_location=Point(float(new_random_lng), float(new_random_lat)), prefered_radius=random.choice([5, 10, 15, 20, 25, 30]) ) new_user.save() -
Manipulate Request data of TastyPie and Django API
I'm writing an application with django-tastypie and following are my models.py and resource.py files. Models.py: import uuid from django.db import models class User(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50, null=False) email = models.EmailField(max_length=254, null=False) password = models.CharField(max_length=100, null=False) role = models.CharField(max_length=16, default='basic', null=False) def __unicode__(self): return self.name, self.email Resources.py: from tastypie.resources import ModelResource from tastypie.authorization import Authorization from api.models import User class UserResource(ModelResource): class Meta: queryset = User.objects.all() resource_name = 'user' authorization = Authorization() excludes = ['password'] #allowed_methods = ['get'] Now the thing is that whenever I hit an API end point from postman, the user is created directly. Now what I don't understand is that whether the request data goes into resources and then into database or directly into the database? Actually, the thing is that I need to apply some changes to the data before it is stored in the database, like hashing the password and then storing the object in the database. I'm new to django, so how can I achieve that? Like in Flask, we can do something like: @user.route('/users', methods=['POST']) def create_user(user_id): data = request.get_json(force=True) # do all the changes we want user = User(data) db.session.add(user) db.session.commit() Now if any request comes at … -
Download image and get file path
Is there a way to download a image from a <input type="file"> into a chosen file location in one view. and then retrieve that image path in another view. for example: def view1(request): # download image def view2(request): # get image file path -
Error statement on Django and Python web development
I've one problem here on elif statement. The process is taking the value from check box selected by the user and compare it to a statement. Checkbox id/name call token, which has two value visual and time. The user can check either visual or time and pass to views.py using a token variable. THIS views.py context = {} data = {} prev_key = '' with open(path) as input_data: for line in input_data: if (token == 'visual'): if line.startswith('2_visualid_') prev_key = line.lstrip('2_visualid_').rstrip() data.update({line.lstrip('2_visualid_').rstrip(): []}) elif (token == 'time'): if search_string in line if prev_key in data: data[prev_key].append (next(input_data).lstrip('2_mrslt_').rstrip()) context = {'output': data} return render(request, 'Output.html', context) When I select Visual in my check box is working. But comes to only select time is not working. If I choose both also it displays nothing in my table. This my checkbox html <form action=""> &nbsp&nbsp<input class="regular-checkbox" type="checkbox" name="token" value="visual"><b>&nbsp&nbsp Visual ID</b><br> &nbsp&nbsp<input class="regular-checkbox" type="checkbox" name="token" value="time"><b>&nbsp&nbsp Time Delay Index</b> </form> This is tabular HTML output <div class="input-group" align="center" style=" left:10px; top:-110px; width:99%"> <table class="table table-bordered"> <thead class="success" > <tr> <th class="success"> <b>Visual ID</b> </th> <th class="success"> <b>Time Delay Index Time</b> </th> </tr> {% for key, values in output.items %} <tr class="warning"> <td rowspan={{ … -
DataError exception instead of form validation error - max_length
bill_to2 model field max_length is 20. When I try to send my form with value lenght more than 20 I get: value too long for type character varying(20) / Exception Type: DataError instead of form validation error. What is the reason? class InviteCandidateForm(forms.Form): def __init__(self, user, *args, **kwargs): super(InviteCandidateForm, self).__init__(*args, **kwargs) self.user = user if self.user.company.display_bill_to2: self.fields['bill_to2'] = forms.CharField() self.fields['bill_to2'].label = self.user.company.bill_to2_label self.fields['bill_to2'].required = True self.helper = FormHelper() self.helper.form_method = 'post' self.helper.layout = Layout( Fieldset( '', 'name', 'email', 'bill_to2', ), ButtonHolder( Submit('save', 'Send', css_class='button') ) ) name = forms.CharField() email = forms.EmailField() -
django visualization and dashboard graph build
i want to build a simple analysis application by using django framework , what's the best lib,module for designing UI that represent graphs and let me display my visualization output.