Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django exception handling - catching ghost error from server-side
I have a Django view that is responsible for providing raw data for graph rendering on server-side. When I run the app locally (I have Windows 10 on my machine), everything works fine. But when I run the app from the remote server (it's Ubuntu), I get an 500-error. This type of errors (when identical code is ok locally, but fails remotely), currently constitutes a serious issue for me in that on every such occasion it leads to very time-consuming - and seemingly unprofessional - process to identify and fix them. And my question is, what is the magic exception handling code snippet which would help me through the detailed exception message to client-side console. To be more specific, consider the following (I deliberately provide the code as is): Django view: def graph_vendors_black_white(request): try: legal_entity_own_qs = get_sale_points(request.user.id) list = [] data = [x.blacknwhite_agreement_count(True) for x in legal_entity_own_qs] list.append({'name':u'В белую', 'data':data}); data = [x.blacknwhite_agreement_count(False) for x in legal_entity_own_qs] list.append({'name':u'В чёрную', 'data':data}); data = [x.blacknwhite_agreement_count(None) for x in legal_entity_own_qs] list.append({'name':u'Не выбрана опция', 'data':data}); legal_entity_own_list = [unicode(x.short_identifier_rus) for x in legal_entity_own_qs] json_response = JsonResponse({'time_series':json.dumps(list, ensure_ascii=False).encode('utf8'),'categories':json.dumps(legal_entity_own_list, ensure_ascii=False).encode('utf8')}) return json_response except: user_msg, tech_msg = default_error_msg() return JsonResponse(user_msg + '\n ' + tech_msg, status = 500, … -
How do I run RabbitMQ with Django in Windows?
I'm doing the Webshop tutorial following the book "Django By Example". I'm using Windows. The book says I have to install Celery, and I managed to do the installation. Next, install RabbitMQ. I installed RabbitMQ from the website. The installation needed Erland and I installed that first. The RabbitMQ installation wizard was successfully finished. But after this I try to run RabbitMQ in the Command Prompt with this command: rabbitmq-server The Command Prompt says: 'rabbitmq-server' is not recognized as an internal or external command, operable program or batch file. I tried to launch RabbitMQ inside my virtual environment and without the virtual environment but I get the same answer. What should I do to get the RabbitMQ running? The book says that I should get an output that ends with: Starting broker... completed with 10 plugins. -
CSRF failed in djano admin
I use Django for my website and when I was testing it locally it was working fine but now when I test in my server by nginx,I enter in admin site and try to add an artical,but when I click the save button,it says 403 csrf failed. In my settings.py,I set 'DEBUG = False,TEMPLATE_DEBUG = False,CSRF_COOKIE_SECURE = False,SESSION_EXPIRE_AT_BROWSER_CLOSE = True,SESSION_COOKIE_HTTPONLY = True' and middleclass has 'django.middleware.csrf.CsrfViewMiddleware',I haven't changed my admin site,just use default. Strangely,when I change DEBUG=True,it works fine.I don't know why.When I change DEBUG = False,then it works raise 403 csrf failed. I have google for solutions,but I haven't solved my problem. -
How to specify the location to place static files in django?
big django beginner here. After you create your first project with django-admin startproject mysite. You get a directory that looks like this mysite/ manage.py - script for running tasks mysite/ __init__.py settings.py - for general setting configuration urls.py - for routing configuration wsgi.py - for webserver configuration What I want is 3 directories for me to put various files that are usable across all django apps. mysite/ manage.py javascript_css/ ... html_templates/ ... custom_modules/ ... mysite/ __init__.py settings.py urls.py wsgi.py What settings would I need to change in settings.py in order to configure this behaviour and how would I reference the javascript_css/html_templates/custom_modules in my django apps? Thanks for any help -
Context dictionary from Django template to Angular
this is my first question here! I am building a web app and I want to know what is the best and the safest way to pass a variable from a django context dictionary to Angular. I have access to a variable of the context dictionary from Django template. Should I use ng-init to pass that value to an Angular variable? It is about a user profile page and I want the user to be able to update his Data. The Data is initialized when calling the view but when I want him to update that Data i want to post using an Angular JS variable. Thanks in advance -
Using django with postman {"detail":"CSRF Failed: CSRF token missing or incorrect."}
I'm using postman to check json response from my django-rest-framework. When my first try to post id, email, password through POST method to my django on AWS(amazon web services), it works well. It returned like: { "key": "99def123123123123d88e15771e3a8b43e71f" } But after first try, the other words, from second try it returned {"detail":"CSRF Failed: CSRF token missing or incorrect."} I saw http://kechengpuzi.com/q/s31108075, but it is not proper to my case. and from http://django-rest-framework.narkive.com/sCyJk3hM/authentication-ordering-token-vs-session, i can't find solution which is using postman How can i use postman appropriately? Or Could you recommend other tools to use? I'm making android application with retrofit2 So I need tools to check POST, GET method and responses. -
cannot import name TEMPLATE_CONTEXT_PROCESSORS
I tried to use virtualenv and evrythings gone wrong ... I desactived (with deactavite) all virtualenv . When i try to launch : python manage.py runserver I got this error message : Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 316, in execute settings.INSTALLED_APPS File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 41, in _setup > self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/jf/mysite/mysite/settings.py", line 68, in <module> from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP ImportError: cannot import name TEMPLATE_CONTEXT_PROCESSORS my path PYTHON_PATH="/usr/lib/python2.7/dist-packages" my django version: 1.10 settings.py file """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.8.7. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'telo@^)(b_8j=s^507(u_zq)b71s$rcn=xl_r%36fs-e923*45' # SECURITY WARNING: don't run with debug turned on in … -
django charfield with default empty string is required in admin
I have a model with a Charfield: class SomeModel(models.Model): charfield = models.Charfield(max_length=5, default="") ... I expect this field to be not required when using in the admin. But when I include this model to the admin, I have this field required. I could use null=True, blank=True, but I'm curious Is it some kind of a bug or am I implementing something wrong? -
Could not show meal based on meal categories(Django)
I want to show meal based on the meal categories. I am using django rest framework for Rest API. I can show meat but not based on categories. The models are Restaurant, Meal and Meal Cateogies. here is my model class Restaurant(models.Model): name = models.CharField(max_length=150, help_text="name of restaurant") slug = models.SlugField(max_length=150) class Meal(models.Model): restaurant = models.ForeignKey(Restaurant) meal_category = models.ForeignKey('MealCategory') name = models.CharField(max_length=120, help_text="name of the meal") def __str__(self): return self.name class MealCategory(models.Model): name = models.CharField(max_length=80, help_text="name of the category of meal") slug = models.SlugField(max_length=80) Serializers.py class MealCategorySerializer(ModelSerializer): # meal = SerializerMethodField() class Meta: model = MealCategory class MealSerializer(ModelSerializer): meal_category = MealCategorySerializer(read_only=True) class Meta: model = Meal def get_meal(self, obj): print('object of meal',obj) instance = MealCategory.objects.get(slug=str(obj.slug)) meal_qs = instance.meal_set.filter(available=True) meal = MealSerializer(meal_qs, many=True).data return meal class RestaurantSerializer(ModelSerializer): owner = SerializerMethodField() meal = SerializerMethodField() class Meta: model = Restaurant read_only = ('id',) def get_owner(self, obj): return str(obj.owner) def get_meal(self, obj): print('object of meal',obj) restaurant = Restaurant.objects.get(slug=str(obj.slug)) meal_qs = restaurant.meal_set.filter(available=True) meal = MealSerializer(meal_qs, many=True).data return meal my API right now looks like this "meal": [ { "id": 1, "meal_category": { "id": 1, "name": "veg", "slug": "veg" }, "name": "Mushroom drumstick", "slug": "mushroom-drumstick", }, { "id": 2, "meal_category": { "id": 2, "name": "Non-veg", "slug": … -
No 'Access-Control-Allow-Origin' header is present on the requested resource with Amazonaws S3
I have a django application and using javascript to directly upload files to an s3 bucket after signing the upload in django backend all of this happening on my localhost. The problem is i am getting an error bellow: XMLHttpRequest cannot load https://mybucket.s3.amazonaws.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access. CORS configuration: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>HEAD</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> the client side javascript to upload the file after signing it function uploadFile(file, s3Data, url){ var xhr = new XMLHttpRequest(); xhr.open("POST", s3Data.url); var postData = new FormData(); for(key in s3Data.fields){ console.log(key, s3Data.fields[key]) // the out put of this is bellow postData.append(key, s3Data.fields[key]); } postData.append('file', file); xhr.onreadystatechange = function() { if(xhr.readyState === 4){ if(xhr.status === 200 || xhr.status === 204){ alert("File uploaded."); } else{ alert("Could not upload file."); } } }; xhr.send(postData); } the output of console.log(key, s3Data.fields[key]) above is policy KJDLSKAFJLASKDFJLSAKDJFLKASJDFLKSAJDFLSKADJFLKSAJDFLKJSAD Content-Type image/jpeg acl public-read signature lkjadflkjda key add.jpg AWSAccessKeyId LKAJDLKFJADFADD note: i modified the output result content not to put it public. and the file object is: File {name: "add.jpg", lastModified: 1472705615906, lastModifiedDate: Thu Sep 01 2016 12:53:35 GMT+0800 (MYT), webkitRelativePath: "", size: 93156…} … -
Serialize from a Django form
I'm migrating a tradicional django-site to a API Restful. I have a large form already working. This form is currently a Django.forms.Form object, and I want to send it's submit to a rest API point. I want to do some similar to ModelSerializer but from the Form object instead a Model. This project has some forms (not model based) and I want to reuse this code. Regrettably I don't found how to do a serializer directly from Form. PS. Sorry my english -
Javascript date string to python datetime object
The current datetime is passed via an ajax request to a django backend where it will be stored in the database. To store it in the database, the date must first be converted to a datetime object which can be done for a date of the in UTC format (Eg. Sun, 04 Sep 2016 07:13:06 GMT) easily by the following statement: >>> datetime.strptime("Sun, 04 Sep 2016 07:13:06 GMT", "%a, %d %b %Y %H:%M:%S %Z") However in such a method, there is no preservation of the user's timezone. The javascript Date constructor call i.e. new Date() returns a date in the following format: Sun Sep 04 2016 12:38:43 GMT+0530 (IST) which gives an error when converting to datetime object. >>> datetime.strptime("Sun, 04 Sep 2016 07:13:06 GMT+0530 (IST)", "%a, %d %b %Y %H:%M:%S %Z") ValueError: time data 'Sun Sep 04 2016 12:46:07 GMT+0530 (IST)' does not match format '%a, %d %b %Y %H:%M:%S %Z' 1) How to resolve this problem? 2) Is there any better way to approach it? -
Can't Post a Form in Django
It's my first real project in Django and I'm kinda noob here :)) In my index page I need some information from the user and then post it to another view. here what I found: NoReverseMatch at /download/ Reverse for 'progress' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['download/(?P<download_id>[0-9]+)/progress/$'] View Page: class IndexView(generic.TemplateView): model = Download template_name = 'download/index.html' def progress(request, download_link): download = models.Download(link=download_link, status = 0) download.save() return HttpResponseRedirect(reverse('download:detail', args=(download.id,))) Index page: <form class="download" action="{% url 'download:progress' download_link %}" method="post"> <input type="input" name="download_link" id="download_link" class="input" placeholder="Enter the URL:" value="{{download_link}}" required/> <input type="submit" class="btn btn-primary" value="Download"> Model: class Download(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) link = models.CharField(max_length=3000) status = models.IntegerField(default=-1) date = models.DateTimeField('date published') I'm using latest stable Django at this time (v1.10) -
Django : Many to many relation in with a shared model between multiple apps
I am working on a big project based on Django. I want to make a model (say root) which will be used in multiple apps. Every app will have a model having many to many relation with this root model. As per my knowledge, I have planned project structure like this: App1/models.py class Root(models.Model): #some fields class M1(models.Model): roots = models.ManyToManyField(Root) #other fields App2/models.py from App1.models import Root class M2(models.Model): roots = models.ManyToManyField(Root) #other fields I want to know that is it okay ? Will I have any problems if I try to retrieve other app's model's objects in current app linked by this root model. Also I want to get advice what cares should I take further as This is my first django project. Thanks in advance. -
django inline within same model
I have following model defined, class Language(models.Model): name = models.CharField(max_length=50) class Translation(models.Model): field_name = models.CharField(max_length=100) language = models.ForeignKey(Language) now i want to achieve such an admin interface where i can enter multiple languges to translate a common field_name, that is ,i want to avoid entering field_name each time to translate it in different languages. for an example if i want to translate banner(which is a field name) in multiple languages(which is foreign field) at a time,then i want to enter banner for a single time and then choose multiple languages from different rows and save.Can it be possible without changing my current model structure? According to current structure of my model, i have to enter field_name each time(though field name is same) to translate it in several languages. -
DoesNotExist at /machine/update_machine_data Controller matching query does not exist
DoesNotExist at /machine/update_machine_data Controller matching query does not exist. Request Method: POST Request URL: http://54.186.7.189/machine/update_machine_data?000000000000000011001111000000010000010000000000= Django Version: 1.6.5 Exception Type: DoesNotExist Exception Value: Controller matching query does not exist. Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/models/query.py in get, line 310 Python Executable: /usr/bin/python Python Version: 2.7.6 Python Path: ['/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', '/public_html/aquabrim_project'] Server time: Sat, 3 Sep 2016 18:49:54 +0000 -
@channel_session_user_from_http not working on heroku, working locally
I have the following consumer code: @channel_session_user_from_http def ws_connect(message): if not message.user.is_anonymous: print "WS: Connect: Adding channel %s to group for user %i" % (message.reply_channel, message.user.id) group_for_user(message.user).add(message.reply_channel) else: print "WS: Connect: Warning: Ignoring anonymous user." As you can see, it doesn't do much besides print a message to see whether the user connecting is anoymous or not. On the client side, I'm connecting like: var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; var chat_socket = new ReconnectingWebSocket(ws_scheme + '://' + window.location.host + "/?session_key=" + document.getElementById('internal-data').dataset.sessionKey); I am just trying to get the server to recognize the user that is creating the websocket. This works perfectly fine locally (that is, the log message printed shows the user was recognized correctly), when I run the server as daphne mysite.asgi:channel_layer --port 8888 -v2 and the worker as manage.py runworker -v2. However, when I run exactly the same code on Heroku, no matter what I try, it always thinks the user is anonymous. Any ideas for what is going on or how to debug this issue? -
Setting Up Nginx on Heroku Django App -- Error R10(Boot timeout)
I am trying to set up Nginx on my Django app (inb4 Cedar stack handles routing) and can't seem to get it working. I've pretty well followed this guide - https://koed00.github.io/Heroku_setups/ - to a T. Things were looking pretty good until I got hit with a "Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch" As per https://github.com/beanieboi/nginx-buildpack , "The buildpack will not start NGINX until a file has been written to /tmp/app-initialized. Since NGINX binds to the dyno's $PORT and since the $PORT determines if the app can receive traffic, you can delay NGINX accepting traffic until your application is ready to handle it..." My question, then, is how to make this connection. Thanks in advance. -
Fork Heroku app to local
Sorry for the basic question, but how can I fork an Heroku app to the local machine? I deployed a simple Django app, added some data to the app online and now I want to fork the app to my friend's laptop so he can continue to fill in the data for me (let say he don't have the internet). I tried heroku fork but it does not work, the forked repository doesn't have the data I added before and the account that I created for my friend... -
Sending context with request, and {% if %} not working properly
I have a problem trying to figure out why below will render an html page showing 'hi' and 1, instead of just 1. views method. def index(request): context = { 'test' : 1, } return render(request, 'index.html', context) template html. Rendering index.html will show both 'hi' and 1. But there's no user in context, so why is the if user going through? {% if user %} <h1>hi</h1> {% endif %} {% if test %} <h1>{{ test }}</h1> {% endif %} -
cannot import name 'patterns' -- unable to find the source of this error
I have an django app which wasn't written by me and I'm trying to run it $ python manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f0ced65d378> Traceback (most recent call last): File "/home/me123/.local/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/me123/.local/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/home/me123/.local/lib/python3.5/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/me123/.local/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/me123/.local/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/me123/.local/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/me123/.local/lib/python3.5/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/home/me123/.local/lib/python3.5/site-packages/django/contrib/admin/apps.py", line 23, in ready self.module.autodiscover() File "/home/me123/.local/lib/python3.5/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/me123/.local/lib/python3.5/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/me123/.local/lib/python3.5/site-packages/treebeard/admin.py", line 6, in <module> from django.conf.urls import patterns, url ImportError: cannot import name 'patterns' My django version is 1.10.1 The thing is that there's no place in the project where I have "from django.conf.urls … -
1067, "Invalid default value for 'lastlogin'
I'm trying to create some models in django. But I'm getting an error messaging saying I have a invalid default value for a field name which I don't even have? from django.db import models class User(models.Model): username = models.CharField(max_length=250, primary_key=True) password = models.CharField(max_length=100) last_login = models.CharField(max_length=30) investment_Points = models.IntegerField(default=0) class Transaction(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE) date = models.CharField(max_length=30) type = models.CharField(max_length=30) amount = models.IntegerField() I have a field named last_login but not lastlogin as the error says. Although I changed the name, but still django think it's the old name? I'm not even sure why it would give me invalid default value anyhow. What am I doing wrong? Console: Operations to perform: Apply all migrations: admin, Cr, auth, contenttypes, sessions Running migrations: Rendering model states... DONE Applying Cr.0001_initial... OK Applying Cr.0002_auto_20160817_2218... OK Applying Cr.0003_auto_20160904_0411...Traceback (most recent call last): File "C:\Anaconda3\Lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Anaconda3\Lib\site-packages\django\db\backends\mysql\base.py", line 112, in execute return self.cursor.execute(query, args) File "C:\Users\Rasmus\AppData\Local\Programs\Python\Python35\lib\site-packages\MySQLdb\cursors.py", line 226, in execute self.errorhandler(self, exc, value) File "C:\Users\Rasmus\AppData\Local\Programs\Python\Python35\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler raise errorvalue File "C:\Users\Rasmus\AppData\Local\Programs\Python\Python35\lib\site-packages\MySQLdb\cursors.py", line 217, in execute res = self._query(query) File "C:\Users\Rasmus\AppData\Local\Programs\Python\Python35\lib\site-packages\MySQLdb\cursors.py", line 378, in _query rowcount = self._do_query(q) File "C:\Users\Rasmus\AppData\Local\Programs\Python\Python35\lib\site-packages\MySQLdb\cursors.py", line 341, in _do_query db.query(q) File "C:\Users\Rasmus\AppData\Local\Programs\Python\Python35\lib\site-packages\MySQLdb\connections.py", … -
How can I deal with error message when not using {{form}} in Django template?
I implemented Login and it works good except error message. If I used {{ form.as_p }}, it shows error message. <form id="loginform" class="form-horizontal" role="form" method="post" action="{% url 'users:login' %}"> {% csrf_token %} <!-- id / pw --> {{ form.as_p }} <div class="form-group"> <!-- Button --> <div class="btn-controls"> <div class="row"> <input id="btn-login" class="btn btn-success" type="submit" name="login_submit" value="로 그 인" /> <input type="hidden" name="next" value={{ request.GET.next}} /> <a id="btn-fblogin" href="{% url 'social:begin' backend='facebook' %}" class="btn btn-primary col-xs-12"><i class="icon-facebook"></i> 1초만에 페이스북으로 로그인 </a> </div> </div> </div> <div class="form-group"> <div class="col-md-12 control"> <div class="signup"> 아직 차차다방 회원이 아니세요? &nbsp <a href="#" id="signuplink"> 가입하기 </a> </div> <div class="forget"> <a href="#"> 비밀번호를 잊어버리셨나요? </a> </div> </div> </div> </form> But when I change template like this, it doesn't show any error when I type wrong id or pw... <form id="loginform" class="form-horizontal" role="form" method="post" action="{% url 'users:login' %}"> {% csrf_token %} <div class="input-group"> <span class="input-group-addon"><i class="icon-user"></i></span> <input id="id_username" type="text" class="form-control" name="username" value="" placeholder="username"> </div> <div class="input-group"> <span class="input-group-addon"><i class="icon-lock"></i></span> <input id="id_password" type="password" class="form-control" name="password" placeholder="password"> </div> <div class="form-group"> <!-- Button --> <div class="btn-controls"> <div class="row"> <input id="btn-login" class="btn btn-success" type="submit" name="login_submit" value="로 그 인" /> <input type="hidden" name="next" value={{ request.GET.next}} /> <a id="btn-fblogin" href="{% url 'social:begin' backend='facebook' %}" … -
Overriding <head> tag within Django template
I have a Django application where users upload videos (played back via html5 video tag). To handle edge cases where a user is unable to playback the video, I give them the option to download it. For this, I'm writing JS that ensures a "download" button appears whenever a src isn't loading. Here take a look: http://plnkr.co/edit/o8YFZNaEhpJMg4YPhZCO?p=preview The problem is that my JS resides within <head></head> and it needs to be able to access all videos I'm going to show on page. Normally, I pass video objects as an object_list that I then iterate through (generated through a paginated ListView). But all this happens in the body of template. How can I get access to context[object_list] within <head> so that the JS snippet I've shared can utilize the sources (I'm already inheriting <head> from base.html)? Secondly, how do I ensure I only pass video sources in page to my JS snippet? Can someone give me an illustrative example via which I can solve this? -
How to deal with form error message in django?
I have a FormView and when I rendering this form as {{ form.as_table }} in my template, it shows error message right under each field like this (only when I type wrong value on each field) : (Ignore their arrangement, please) Since I want to show this form nicely, so I edit my template and add some css on it : <table id="signup-table"> <col width="30%"> <col width="70%"> <tr> <td class="label-tag">{{ signup_form.username.label_tag }}</td> <td class="value">{{ signup_form.username }}</td> {{ signup_form.errors.username }} </tr> <tr> <td class="label-tag">{{ signup_form.password1.label_tag }}</td> <td class="value">{{ signup_form.password1 }}</td> {{ signup_form.errors.password1 }} </tr> <tr> <td class="label-tag">{{ signup_form.password2.label_tag }}</td> <td class="value">{{ signup_form.password2 }}</td> {{ signup_form.errors.password2 }} </tr> <tr> <td class="label-tag">{{ signup_form.name.label_tag }}</td> <td class="value">{{ signup_form.name }}</td> {{ signup_form.errors.name }} </tr> <tr> <td class="label-tag">{{ signup_form.gender.label_tag }}</td> <td class="value">{{ signup_form.gender }}</td> {{ signup_form.errors.gender }} </tr> <tr> <td class="label-tag">{{ signup_form.birth.label_tag }}</td> <td class="value">{{ signup_form.birth }}</td> {{ signup_form.errors.birth }} </tr> <tr> <td class="label-tag">{{ signup_form.phone_number.label_tag }}</td> <td class="value">{{ signup_form.phone_number }}</td> {{ signup_form.errors.phone_number }} </tr> <tr> <td class="label-tag">{{ signup_form.job.label_tag }}</td> <td class="value">{{ signup_form.job }}</td> {{ signup_form.errors.job}} </tr> </table> And now it shows error messages on the top of the form. In this case, I want to show error message right under each field. How can I do …