Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django naturaltime tag
I want to receive time difference,so I have added 'django.contrib.humanize' to Installed Apps, and '{% load humanize %}' to my template, and use it in as below: {% for notification in request.session.notifications %} <li> <div class="media"> <div class="media-left"> <div class="media-object"> <img data-src="holder.js/50x50?bg=cccccc" class="img-circle" alt="50x50" style="width: 50px; height: 50px;" src="{% static 'img/profile.png' %}" data-holder-rendered="true"> </div> </div> <div class="media-body"> <strong class="notification-title"><a href="#">{{ notification.fields.actor_object_id }} {{ notification.fields.verb }} {{ notification.fields.target_object_id }}</a></strong> <div class="notification-meta"> <small class="timestamp">{{ notification.fields.timestamp|naturaltime }}</small> </div> </div> </div> </li> {% endfor %} but result is same again: 2017-01-18T10:59:11Z -
Django, ForeignKey to non unique field?
I'd like to have a reference field (normally it is a foreignkey field) foo field in Bar class is the reference field. class Foo(models.Model): _id = models.AutoField(primary_key=True) id = models.IntegerField(blank=True, null=True, db_index=True) class Bar(models.Model): foo = models.ForeignKey(Foo, to_field='id') I'm getting an error saying Foo.id needs to be unique. (Foo.id must set unique=True because it is referenced by a foreign key.) Is there a relational field I could use to reference another django model instance without the restriction above? (Or could I get away with it somehow?) All I need is the ability to use foo and foo_id, I don't need the referential integrity of ForeignKey. bar_instance.foo to access foo instance bar_instance.foo_id to access the id. Bar.objects.create(...., foo_id=foo_id) -
Optimize and Scale my Webservers (Nginx + Gunicorn + Django nonrel stack)
We have a web server setup running Nginx and Gunicorn which runs a Django application. There have been times that we received high load and got a lot of 5XXs. To get rid of that immediately we increased the number of servers 5 times and restarted all Gunicorn workers. Now, our servers are still not used optimally, CPU is around 10-15% max used and same for the memory (20-30%). So, this is not a permanent solution and it also incurs us downtime and high costs if we go with larger and more number of servers. To research this we started with load tests. When we do a load test we start getting 5xx errors even when the resources on the server are barely used. LOAD TEST RESULTS Load Test 1 Resources: 1 ELB 1 server with Nginx and 4 workers of gunicorn running in virtual env serving Django. Ran load test using Locust which has a full workflow of what a user would do after getting into the app. 1000 Users, Ramp up 10 Requests Per Second (Before Failure): 120 Max CPU = 45 % on CloudWatch, on server fluctuating up to 100% Memory did not get used more than … -
How do i pass a initial value from within a form to a new form?
If i try to add a new object within a django form how can i pass a initial value to this new form? I know how to set an initial value on form init but i dont know how to do it form within a new form any help?enter code here -
django upgrade from 1.9 to 1.10 __init__() got an unexpected keyword argument 'current_app'
ive just upgraded Django from 1.9 to 1.10. i run 1.10 in my test environment and ironed out any upgrade issues to make sure it all worked. however when ive gone to do it on my live site and gone to load the home page i get the errors below Environment: Request Method: GET Request URL: http://it.local.com/ Django Version: 1.10.5 Python Version: 2.7.5 Installed Applications: ('home.apps.HomeConfig', 'oncall.apps.OncallConfig', 'tools.apps.ToolsConfig', 'sites.apps.SitesConfig', 'maintenance.apps.MaintenanceConfig', 'service.apps.ServiceConfig', 'management.apps.ManagementConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'bootstrap_pagination', 'easy_thumbnails') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware') Traceback: File "/usr/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/infternal/home/views.py" in index 13. return render(request, 'home/index.html', {"user": user}) File "/usr/lib/python2.7/site-packages/django/shortcuts/__init__.py" in render 49. context_instance = RequestContext(request, current_app=current_app) Exception Type: TypeError at / Exception Value: __init__() got an unexpected keyword argument 'current_app' -
hashtag (#) on urls in angularjs
I am using angularjs framework in my website. I have a problem with urls! There is # in urls in Google analytics I am using Html5Mode in my config.js app.config(function($httpProvider, $analyticsProvider, $locationProvider) { $httpProvider.defaults.withCredentials = true; $httpProvider.interceptors.push('TokenInterceptor'); $analyticsProvider.firstPageview(true); /* Records pages that don't use $state or $route */ $analyticsProvider.withAutoBase(true); /* Records full path */ $locationProvider.hashPrefix('!'); $locationProvider.html5Mode(true); }); it is some part of my routes.js: app.config(['$locationProvider', "$routeProvider", function($locationProvider, $routeProvider) { $locationProvider.html5Mode(true); $locationProvider.hashPrefix('!'); var modulesPath = 'modules/'; $routeProvider .when("/", { title: '', templateUrl: modulesPath + "site/views/index.html", access: { requiredLogin: false } }).when("/index", { redirectTo: "/", access: { requiredLogin: false } }).when("/home", { redirectTo: "/", access: { requiredLogin: false } }).when("/terms", { title: 'Terms and Conditions', templateUrl: modulesPath + "terms/views/index.html", access: { requiredLogin: false } I tried several ways like adding $locationProvider.html5Mode(true); plase help me to fix it thank you -
Django default pages are not accessing properly?
I have done Debug=False for creating custom 404 error page it is done but the static pages of Django is not displaying properly i.e, i am trying to open my api using urls but the page is not displaying properly thank you in advance -
Python- how do I get the object whose date field has the most recent value from a list of objects?
I have a Django application in which I there are a number of projects. Each project can have a number of budgets, and every time a new budget is added to a project, the existing budgets for that project should have their version_number incremented by one. The 'current' budget should be the budget whose version_number is 0- so when trying to 'get' the current budget for use elsewhere in the code, I am doing things like: budgetInstance = Budget.objects.get(project = project, version_number = 0) However, it seems that somehow, some of the projects have ended up with a number of budgets whose version_number is 0, so it appears that some of the projects in the database seem to have several 'current budgets'... I know that I will need to fix the logic for how the versioning is done, so that no two budgets can have the same version_number, but for now, I just want to get the most recent budget for each project in the database. Each Budget object has attributes such as: project_id, version_number, id, presentation_date, etc. So I now want to filter the budgets that have been returned when I filtered by version_number = 0) by their presentation_date … -
Functions in separated js file don't work
I have an template in django as follows : <nav class="navbar navbar-default"> <div class="container-fluid" style="padding: 0"> <div class="collapse navbar-collapse" style="padding: 0"> <ul id="categories_nav" class="nav navbar-nav col-lg-12" style="padding: 0"> {% for category in categories.nextStep %} {% if category.name == default_type %} <li id="category-{{ category.name }}" class="active col-lg-6" style="padding: 0"> <a href={{ category.href }}>{{ category.name }}</a></li> {% else %} <li id="category-{{ category.name }}" class="col-lg-6" style="padding: 0"> <a href={{ category.href }}>{{ category.name }}</a></li> {% endif %} {% endfor %} </ul> </div> </div> </nav> <div id="makes"> {% for make in makes.nextStep %} <div id="make" class="col-lg-3"><a href={{ make.href }}>{{ make.name }}</a></div> {% endfor %} </div> And I added a separated .js file to control click events. The custom.js is as follows : $(document).ready(function () { $('ul[id="categories_nav"] li').click(function (e) { e.preventDefault(); var url = "{% url 'render_makes' 123 %}".replace('123', e.target.innerText); $.ajax({ type: "GET", url: url, context: this, success: function (data) { $('ul[id="categories_nav"] li').removeClass('active'); $(this).addClass("active"); $('#makes').html(data); } }); }); $('div[id="makes"]').on('click', '#make', function (e) { e.preventDefault(); var model_id = e.target.href.split("/").pop(); var url = "{% url 'render_models' 123 %}".replace('123', model_id); debugger; $.ajax({ type: "GET", url: url, context: this, success: function (data) { $('#calculation-menu a').removeClass("active"); $('#model').addClass("active"); $('#content').html(data); } }); }); }); And it doesn't work. If I put all my … -
gunicorn systemd startup not working with django inside a vagrant box
I translated this tutorial in a chef recipe. And so far everything apart from starting gunicorn (the right way) seems to be working. For example when I shut down the machine after the initial setup and provisioning via vagrant halt and then start it up again with vagrant up - I always get an 502 Bad Gateway error. Then I have to ssh into the box and run these commands manualy sudo systemctl daemon-reload sudo systemctl restart gunicorn After that everything is working again. What I dont understand is when I run sudo systemctl status gunicorn before I reload the daemon and restart gunicorn - it tells me that gunicorn is running. Here is my gunicorn.service file contents that get written to /etc/systemd/sytem/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/vagrant_data ExecStart=/vagrant_data/myprojectenv/bin/gunicorn --workers 5 --bind unix:/home/ubuntu/run/myproject.sock myproject.wsgi:application --reload [Install] WantedBy=multi-user.target My projects folder structure is: /home/ubuntu/myproject ls manage.py myproject myprojectenv I symlinked the myproject folder to vagrant_data which is setup to the vagrant.synced_folder in my Vagrantfile. Does anyone know what I am doing wrong ? -
Django Rest Framework Related Field Filtering
I just started coding in DRF and I have come across an issue where I have to search from a related foreign key. I have 2 models, BookDetails and BookCopies. BookCopies has BookDetails referenced in it as a foreign key. Now I want to search BookCopies using the attribute book_title which is in the model BookDetails. I used django_rest_framework_filters as follows but It gives an error when I visit http://localhost:8000/book/copy/?book_details__title=abc. class BookFilter(FilterSet): class Meta: model = BookDetail fields = { 'title': ['exact', 'in', 'startswith'], 'author': ['exact', 'in', 'startswith'], 'editor': ['exact', 'in', 'startswith'], 'publisher': ['exact', 'in', 'startswith'], 'cl_num': ['exact', 'in', 'startswith'] } class CopyFilter(FilterSet): book_details = RelatedFilter(BookFilter, name="title", queryset=BookDetail.objects.all()) class Meta: model = BookCopy fields = { 'ref_id': ['exact', 'in', 'startswith'] } Please Help. Thank You -
Html form and Rest Api Django
I am sending a Username and password from my HTML form to django backend . <html> <style type="text/css"> #center_align{ width: 200px; margin: 10px auto; } </style> <head> <title>Login Form</title> </head> <body> <div id = "center_align"> <h1>Login</h1> <form method = "GET" action="http://127.0.0.1:8000/login/" > Username :<input type ="text" name = "username"><br> Password :<input type ="password" name = "password"><br> <input type="submit" value="Submit"> </form> </div> </body> </html> In my django , i have wrote a class in my Views class Login(APIView): global User_Grps def get(request,self): state = "" username = "Gauss" password = settings.AUTH_LDAP_BIND_PASSWORD oLdap = LDAPBackend() try: User = oLdap.authenticate(username=username,password=password) print User.ldap_user.group_dns if User is not None: User_Grps = User.ldap_user.group_dns else: User_Grps = "Invalid Group" except Exception as e: User_Grps = "Error" return HttpResponse(User_Grps) How would i retrieve my username and password from the request object ? Like i need to get the data from the request parameter of the method . -
Sending messages to django-channels via celery
So I have a scheduled celery beat task (celery.py): @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(10.0, test_event, name='test') And the task (events/tasks.py): @shared_task def test_event(): from .models import Event Event.objects.create() When the event is created, a receiver is fired, that should send a message to a channels group (events/receivers.py): @receiver(post_save, sender=Event) def event_post_add(sender, instance, created, *args, **kwargs): if created: print("receiver fired") Group("test").send({ "text": json.dumps({ 'type': 'test', }) }) The main problem is that the receiver is being fired in the celery beat process, and nothing is getting sent via django channels. No error messages, nothing, it's simply not being sent. How can I integrate these two so that I will be able to send messages to channels from celery background processes? -
django-filer: can't upload images on server Cannot read property 'API' of undefined - error 500
I've my project correctly working on my local. I deployed it on a staging server. Everything was working (filer included) until I migrate my static files / paths to s3: STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'project.storage.StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'project.storage.MediaStorage' class MediaStorage(S3Boto3Storage): location = settings.MEDIAFILES_LOCATION Since then, each time I try to upload a file I have: POST admin/filer/clipboard/operations/upload/no_folder/ 500 (Internal Server Error) dropzone.init.js:38 TypeError: Cannot read property 'API' of undefined So I'm like... What the f***? Is there an other hidden configuration to apply when you migrate your static files to s3? My urls are like: urlpatterns = [ url(r'^', include('django_inspirations.urls')), url(r'^', include('django_tutorialvideos.urls')), url(r'^', include('django_faq.urls')), url(r'^ckeditor/', include('ckeditor_uploader.urls')), url(r'^admin/', admin.site.urls), ] So, it was working locally on the server, and stopped once I migrated the static files (and media) to s3. I'm lost. -
Trying to dynamically add a form to an InlineFormSet
I have a page where I want to display existing records and allow the user to edit them, and also add new records to the database - as many as they wish. I'm new to django so bare with me...here is my view class Time(models.Model): project_id = models.ForeignKey(Project, null=True) date_worked = models.DateField(null=True, blank=True) hours = models.CharField(max_length=1) description = models.CharField(max_length=150) timesheet_id = models.ForeignKey(TimeSheet, null=True) def __unicode__ (self): return self.description This is my Time Model, and it is related to the timesheet model and a project model. Here is my view: class CustomInlineFormSet(BaseInlineFormSet): def clean(self): super(CustomInlineFormSet, self).clean() # example custom validation across forms in the formset timesheet = TimeSheet.objects.get(pk=timesheet_id) for form in self.forms: form.empty_permitted = True def timesheet(request, timesheet_id): timesheet = TimeSheet.objects.get(pk=timesheet_id) TimeInlineFormSet = inlineformset_factory(TimeSheet, Time, exclude=('timesheet_id',), extra=0, formset=CustomInlineFormSet) if request.method == 'POST': existing_formset = TimeInlineFormSet(request.POST, request.FILES, instance=timesheet) for thetime in existing_formset.forms: print thetime if thetime.is_valid(): print "this is fine" thetime.save() else: "Not validating" thetime.timesheet_id = timesheet if thetime.is_valid(): thetime.save() else: "something else is wrong" context = { "timesheet": timesheet, "existing_formset": existing_formset, } return render(request, 'tande/timesheet.html', context) And here is how I am dynamically adding rows to my timesheet to allow the user to input as many times as they want before … -
how to remove background color of a dynamic div in navbar
I have a nav bar with header section on it. In nav-bar header, there is a input box of search. When user searches, the search list populated in a div. I want that search list without background of navbar <nav class="navbar navbar navbar-default navbar-fixed-top" ng-controller="VikasController"> <!-- Search input box--> search Submit</button>--> <!-- Show Search List --> <div class="col-md-3 search-result-article-box pull-right" style="background-color:none" ng-show="(search_res_objs.length > 0)&&BlogListSearch" id="search_list"> <div class="col-md-9 bg-white pt10 ng-cloak" id="search_result" tabindex="-1" > {% verbatim %} <a ng-repeat="x in search" href="{{ x.link }}" > <span ng-if="x.text && x.text.length <=40">{{ x.text}}</span> </a> {% endverbatim %} </div> </div> </nav> When i remove above, then search list comes without a background but when I scroll down, the header becomes transparent. So how can I make my search-list transparent -
View with form and context dict
I don't know how return a form and a context_dict in the same view My view: def myview(request): context_dict = {} u = request.user context_dict['user'] = u ... form = form.myformForm() #return render(request, 'mytemplate.html', context_dict) return render(request, 'mytemplate.html', {'form': form }) Also I need to use the context_dict in a base template (for a navbar) so I would like to have access to the context in this format, if it is possible, without other prefix/path: {{ user.username }} -
How to use inspectdb for multiple mysql schemas in django?
This is the DATABASES dictionary in my Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'account', 'USER': 'xxxx', 'PASSWORD': 'xxxx', 'HOST': 'localhost', 'PORT': '3306' } } My database has multiple schemas, for example, account, login, notifications etc. When I do a python manage.py inspectdb, I only get the classes for the tables in the "account" schema, but I want the classes for all the schemas. I tried doing python manage.py inspectdb --database=login, but I get a django.db.utils.ConnectionDoesNotExist exception But, if I change the settings to DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'account', 'USER': 'xxxx', 'PASSWORD': 'xxxx', 'HOST': 'localhost', 'PORT': '3306' }, 'login': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'login', 'USER': 'xxxx', 'PASSWORD': 'xxxx', 'HOST': 'localhost', 'PORT': '3306' }, } I get the proper classes of the table login on executing python manage.py inspectdb --database=login. But, problem is, if this is supposed to be the procedure, I have to make an option in the DATABASES option, which will become really long, as I have more than 15 schemas, and I am not sure if doing that will be a good thing or not. So, I want to know what is the right way of doing this. I am on Django … -
How to make a good ModelForm for receiving and handling multiple files?
I need to make a form for this model: class Message(models.Model): text = models.TextField(blank=True) files = models.ManyToManyField( PersonalFile, related_name='+', ) ... Now I have this: class CreateMessageForm(forms.ModelForm): class Meta: model = Message fields = ['text'] def save(self): cleaned_data = super(CreateMessageForm, self).clean() message = Message( text = cleaned_data.get('text'), ) message.save() ... As you see I didn't put in it something for receiving and handling files because in Message model I have ManyToManyField for files. I don't know how to make this ModelForm suitable for qualify working in this situation. Also this is PersonalFile model: class PersonalFile(models.Model): name = models.CharField(max_length=50) data = models.FileField(upload_to=user_directory_path) owner = models.ForeignKey( Person, related_name='files', ) ... The main question is about receiving multiple files, of course. How to make CreateMessageForm receive multiple files. And the second - which place is more suitable for handling files: view, form save or clean methods or something else? -
Django channels & celery & receivers
So I have a scheduled celery beat task (celery.py): @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(10.0, test_event, name='test') And the task (events/tasks.py): @shared_task def test_event(): from .models import Event Event.objects.create() When the event is created, a receiver is fired, that should send a message to a channels group (events/receivers.py): @receiver(post_save, sender=Event) def event_post_add(sender, instance, created, *args, **kwargs): if created: Group("test").send({ "text": json.dumps({ 'type': 'test', }) }) The main problem is that the receiver is being fired in the celery beat process, and nothing is getting sent via django channels. How can I integrate these two so that I will be able to send messages to channels from celery background processes? -
Python 3 threading.enumerate() exception
I'm writing django based web, where my application is running. User gives passes some parameters and the application is started in its own thread. For debugging purposes I want to print to console all active threads. I use python threading module and following code: import threading def some_func(): print(threading.enumerate()) . . . and this call leads to the following exception: Traceback (most recent call last): File "C:\Python34\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python34\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\bakajsa\AppData\Local\Programs\Git\mysite\my_project\views.py", line 90, in some_func print(threading.enumerate()) File "C:\Python34\lib\threading.py", line 824, in __repr__ self.is_alive() # easy way to get ._is_stopped set when appropriate File "C:\Python34\lib\threading.py", line 1120, in is_alive self._wait_for_tstate_lock(False) File "C:\Python34\lib\threading.py", line 1076, in _wait_for_tstate_lock assert self._is_stopped AssertionError Do you have any idea what could possibly go wrong? According to documentation: threading.enumerate() Return a list of all Thread objects currently alive. The list includes daemonic threads, dummy thread objects created by current_thread(), and the main thread. It excludes terminated threads and threads that have not yet been started. -
Uncaching the results of a particular view in django
I have come across this project. It uncaches the results of a particular view in django. I want to do a similar thing but I read that this project is no longer updated. I am using Memcached and Django 1.8. I want to delete all the cache entries of a particular view whenever I make changes to the databases. Earlier I was clearing the entire cache whenever a new object was added, but I think its better to just clear the entries of concerned view. Is there someway to do it using the cache_control decorator or some other effective way? -
ValueError at /music/4/favorite/ invalid literal for int() with base 10: ''
Here I am getting the ValueError at /music/4/favorite/ invalid literal for int() with base 10: '' Request Method: POST Request URL: http://127.0.0.1:8000/music/4/favorite/ Django Version: 1.10.5 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: '' Exception Location: /usr/local/lib/python2.7/dist- packages/django/db/models/fields/__init__.py in get_prep_value, line 946 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/user/python/official-django-tutorial/MusicApp', '/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', '/home/user/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client'] Server time: Tue, 24 Jan 2017 15:13:57 +0530 Here is the view.py for the project from django.http import HttpResponse from django.shortcuts import render,get_object_or_404 from .models import Album,Song def index(request): all_albums=Album.objects.all() context={"all_albums":all_albums} return render(request,'Music/index.html',context) def detail(request,album_id): album=get_object_or_404(Album,pk=album_id) return render(request,'Music/detail.html',{"album":album}) def favorite(request,album_id): album=get_object_or_404(Album,pk=album_id) try: selected_song=album.song_set.get(pk=request.POST['song']) except(KeyError,Song.DoesNotExist): return render(request,'Music/detail.html',{"album":album,"error_message":"You Did Not Selected a valid Message"}) else: selected_song.is_favorite=True selected_song.save() return render(request,'Music/detail.html',{"album":album,}) here is the detail template for this one, <img src="{{ album.album_logo}}"> <h1>{{ album.album_title }} </h1> <h3>{{ album.artist }} <h4>Here are the Available Songs</h4> {% if error_message %} <p>{{error_message}}</p> {% endif%} <form action="{% url 'Music:favorite' album.id %}" method="post"> {% csrf_token %} {% for song in album.song_set.all %} <input type="radio" id="song{{ forloop.counter }}" name="song" value="{{ songs.id }}"> {{song.song_title}} <!label for="{{forloop.couter}}"{{song.song_title}}></label> {% if song.is_favorite %} <img src="http://i.imgur.com/b9b13Rd.png"> {% endif %} <br> {% endfor %} <input type="submit" value="Favorite"> </form> how can … -
How to execute external script in the Django environment
I am trying to execute an external snippet for debugging and terminal-like purposes in the environment the Django console uses so it can connect to the db, etc. Basically, I am just using it for the same reason one would fiddle with the console but I am using longer snippets to output some formatted information so it is handy to have that code in an actual file manipulated with an IDE. An answer said you could do that by executing python manage.py shell < snippet.py but I did not see a successfull result. And although no errors are reported, I am not getting the excepted output, but only a series of >>> prompts. So how can I do this? By the way, I am using PyCharm, in case this IDE has a shorthand way of doing this or any special tool. -
Why does Django's BooleanField's BoundField return sometimes string, sometimes boolean in template?
When the form loads with initial values or when the form loads being bound (form = SkierForm(request.POST)) and form.is_valid(), form['field_name'].value() returns False (bool) in the template! When the form does not validate on form = SkierForm(request.POST) then form['field_name'].value() returns False (string) in the template. I am really unhappy about this because it makes checking the state of a BooleanField harder (in order to set the correct state for a checkbox, for example). This is the model definition: BOOLEAN_YN = ( (True, _('Ja')), (False, _('Nein')), ) field_name = models.BooleanField(_("A boolean field"), default=False, choices=BOOLEAN_YN) The field value in the Django template is called like {% for value, text in form.field_name.field.choices %} {{ value }} {% if form.field_name.value == value %}checked!{% endif %} {% endfor %}