Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fastest way to process a python list of tuples
In a Django project, I have a python list of tuples like so: users_and_values = [(user_id,value),(user_id,value),......] where value can either be 0.0 or 1.0 (float). Given this list, I need to create a new one, which is like so: [(user_object,value),(user_object,value),......] where user_object is the object associated with each user_id (containing user attributes and such). What is the most efficient way to achieve this (performance and correctness both matter)? Currently, I'm trying to achieve that as follows in a Django view: user_ids = [user_id for user_id, value in users_and_values] user_objs = User.objects.filter(id__in=user_ids) context["votes"] = [(user_objs(user_id),value) for user_id, value in users_and_votes] This gives me the error: 'QuerySet' object is not callable I could also have tried [(User.object.get(id=user_id),value) for user_id, value in users_and_values], but that would be too many DB calls. So can anyone chime in with what I'm doing wrong, and the correct solution? Thanks in advance. -
Django tutorial login, delete data on user logging out
I am preparing a multitenant website on Django using tenant-id for identification (and not schema). Now, for tutorial, I would want to have a webpage with sample login and password (like Django CMS does). However, I don't want to store user data from that login/password combination, so that the data would be availabale for each session and as soon as the user logs out, the data deletes. Is there any application/packages that could help me with this? Otherwise, how can I do this? -
Converting a single server Ubuntu+Nginx+uwsgi+Django(rest-framework)+celery+PostgreSQL to auto-scaling with ElasticBeanstalk?
There is quite a bit of documentation around getting Django running with EC2 - https://realpython.com/blog/python/deploying-a-django-app-and-postgresql-to-aws-elastic-beanstalk/ seems to be one of the better looking guides and Django app with Nginx + uWSGI on Amazon EC2 also contains links to some good information before diving in too deep - it'd be great if anyone has any more information (both overview and in detail) Can I use ubuntu 14.04/16.04? is there an advantage to amazon linux? What needs it's own server? I'm tempted to keep the setup as similar as possible per-instance (load balancer, nodes with nginx+uwsgi+django+redis+celery) - but suspect it may make sense to use amazons queuing system and separate celery worker machine(s) and a single non-scaling machine, mostly for celerybeat and DB backups to have a single location to run from, and still be able to communicate with the workers. writing eb init scripts - I guess I should interactively log into a machine, get it setup and log the process to translate into the eb file? What kind of timeframe would you expect setting this up to take? (I'm rather familar with linux and the various server components, but new to amazon and EB) Is there any other handy information β¦ -
Django, send dictionary to template
Is it possible to send a dictionary to a template. And use the django/python magic to work on it client side? The view function def index(request): context = { 'users' : users, 'investments' : { 'one' : 1, 'two' : 2 }, } return render(request, 'index.html', context) And the html {% if investments %} <h1>{{ investments['one'] }}</h1> #<---- something like that. {% endif %} -
How to redirect a Django template and use the 'Next' variable?
I am using Django's built in login view as can be seen in the following snippets: urls.py url(r'^login$',login,{'template_name': 'login.html'},name="login"), template.html <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login" /> <input type="hidden" name="next" value="{{ next }}" /> </form> How can I use the next variable to redirect to a URL different than the default /accounts/profile/ that django redirects to? I know of people referring to the settings.py file but I am wondering how I can utilize the next variable to do this? (I'm not really sure of how the next variable works even after referring to documentation, an explanation of this would be much appreciated) -
How to add event listner in JS if html5 video fails to load (e.g. because it's not supported)
In a Django website I've built, users can add videos for others to see and comment on. Not all users have devices that support video playback, and thus for such edge cases, I want to allow video download. To do this, I first need to detect whether the video failed or not. How can I do that? Currently I'm trying the following in my Django template (where all videos are listed using a ListView): <script> var videos = document.querySelectorAll('video'); for (var i = 0; i < videos.length; i++) { (function() { var v = videos[i]; var s = v.querySelector('source'); //console.log(source); s.addEventListener('error', function(ev) { var d = document.createElement('div'); d.innerHTML = v.innerHTML; console.log("hello") console.log(v); v.parentNode.replaceChild(d, v); }, false); }()); } </script> I.e. first I go through all video tags in the HTML page, then for each tag, I look up the source tag inside. Next, I try to add an event listener to the source tag, catch the error, and do some processing. However, I've found my code inside error is never fired. Can someone help in improving this? Thanks in advance. -
Django ORM query for empty FileFields
It's not clear to me whether this is possible through the ORM - it doesn't appear so, but maybe I'm missing something? class Application(models.Model): somefield... class ApplicationInstitution(models.Model): application = models.ForeignKey(Application, related_name='institutions') ... transcript_file = FileField(upload_to=...) So from an Application instance I can do app.institutions.all() etc. Some of those ApplicationInstitution objects may already have a transcript_file uploaded, while others don't. The question: I want to determine whether a given Application instance has one or more uploaded transcripts. At first I thought I could so something like app.institutions.filter(transcript_file__is_null=False).count() or similar, but nope (because the missing file is a None not a Null). And if you try to access the actual file object, you get a Raise, not an empty: >>> a.institutions.last().transcript_file.file Traceback (most recent call last): ... ValueError: The 'transcript_file' attribute has no file associated with it. I've written a model method using try/except that gets me the answer, but ORM would be cleaner. Is a query for empty or non-empty FileFields even possible? -
How can I clearly switch between two forms in one template (Django)?
When several html forms (signup and login) in one template, login_signup.html Also I have two views (signup and login) which direct template, login_signup.html. This is how it works. When I do login (http://example.com/login), it direct to login_signup.html and show just login form. (hide signup form) When I do signup (http://example.com/signup), it direct to login_signup.html and show just signup form. (hide login form) I implement it using javascript $(document).ready(function(){ if ((window.location.pathname).indexOf('login') >= 0) { $('#signupbox').hide(); $('#loginbox').show(); } else { $('#loginbox').hide(); $('#signupbox').show(); } }); Problem is though, when I want go to signup page(http://example.com/signup), it shows login forms in very few second and hide it and show signup form. I think this is not good User Interface. How can I deal with it clearly? Here is my whole template and javascript code. login_signup.html {% extends 'chacha_dabang/skeleton/base.html' %} {% load pipeline%} {% block content %} <div class="container"> <div id="loginbox" class="mainbox"> <div class="panel panel-info"> <div class="panel-heading"> <div class="panel-title">Sign In</div> </div> <div class="panel-body"> <div id="login-alert" class="alert alert-danger col-sm-12"></div> <form id="loginform" class="form-horizontal" role="form" method="post" action="{% url 'users:login' %}"> {% csrf_token %} <!-- id / pw --> <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" β¦ -
Django 1.10: extend/override admin css
I want to override the css definition of a select-multiple widget by decreasing the min-height attribute from contrib/admin/static/admin/css/base.css. However, my css is not loaded I think. I use a custom admin form and have defined the Media subclass within this form as well as within the corresponding ModelAdmin: class Media: css = { 'all': ('/css/admin widgets.css',) } The file itself is located in myapp/static/css/admin widgets.css and contains: select[multiple] { min-height: 65px; } In settings.py, I have defined BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = [os.path.join(BASE_DIR, "myapp", "static")] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static' I've ran manage.py collectstatic which collected all the admin files and my own css file in the project's static-subdir. I've also extended urls.py as described here, but the widget is still rendered with 150px min-height which is defined in base.css. Any help is appreciated. -
When does session refresh in Django-hitcount?
I'm trying to introduce django-hitcount into my project. My project has a board and user can upload a post. I want to show the number of views for each post. Before introducing, I test a example project it has (https://github.com/thornomad/django-hitcount/tree/master/example_project) In example project, I guess detail-with-count is suitable for my board application. when I click the Hello world, it increase number of count. But problem is that when I refresh it, or go backward and reclick it, close the browser and reopen and revisit again, it doesn't count! It shows like this I think this is kinda session issue, but want to know how it works. I mean when does session expire or refresh? Need your helps. -
'WSGIRequest' object has no attribute 'session' multiple app
I made a new app for my webapp project using ./manage.py startapp webapplogin. The templates all works however now I keep getting 'WSGIRequest' object has no attribute 'session' whenever I try to do anything with request such as logout(request) or login(request, user). I don't understand what the issue is after about 6 hours of debugging/googling... Do I need to go back to doing the webapp all in webapp instead of trying to split up the project into apps? The templating works fine as well as linking right now, just the no attribute 'session'... project structure below app_project app_backend settings.py urls.py wsgi.py static static_files webapp templates webapp base.html home.html admin.py apps.py models.py tests.py urls.py views.py webapplogin templates login login.html admin.py apps.py models.py tests.py urls.py views.py project settings below INSTALLED_APPS = [ 'webapplogin.apps.LoginConfig', 'webapp.apps.WebappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'django.contrib.humanize', ] 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', ] ROOT_URLCONF = 'app_backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'app_backend.wsgi.application' -
django-haystack unable to order by score
I am using Haystack (2.4.1) with Whoosh (2.6.0) backend. I am able to sort my SearchQuerySet by my personally defined field, modified, but not Haystack's build-in score. I couldn't find anything about this in Haystack's documentation, but I did found an example online that seemed to indicate that the .order_by('-score', '-modified') below should work: python sqs = (SearchQuerySet() .models(MyModel) .order_by('-score', '-modified')) but it doesn't; instead, I get a GET 500 error. Any help is greatly appreciated. -
Why would I need a separate webserver for Django?
I noticed that most of the books and tutorials on Django make it very clear that use Django development server as a normal webserver is not OK. But some state that other webservers are optional, that we can use Django server to put the website on the web for everybody to see. But why exactly? Why do I need (or not) to use Apache, Lighttpd, Nginx, etc. in front of Django - WSGI? Is Django server not safe in some way? If so, how it is unsafe exactly, and why can't Django just come with a more robust webserver (out of the box, ready to use)? How exactly those webservers help Django? *I know that those webservers have very useful mods, but AGAIN: couldn't Django just come with a safer "mod-able" webserver? -
django equivalent to sqlalchemy's sessionmaker
I'm new to Django 1.9 (fairly new to flask, as well), and am trying to populate my models.py much in the same way that sqlite sessionmaker does it. this is a snip of my models.py: @python_2_unicode_compatible class Location(models.Model): def __str__(self): return self.location_text location_text = models.CharField(max_length=200) travel_date = models.DateTimeField('date traveled') @python_2_unicode_compatible class Countries(models.Model): def __str__(self): return self.capitals location = models.ForeignKey(Location, on_delete=models.CASCADE) capitals = models.CharField(max_length=200) With flask and sqlalchemy I'd create a new file and be able to do something like this: from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from this_app.models import Location, Countries engine = create_engine("the db") Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() loc1 = Location(location_text = "Indonesia") session.add(loc1) session.commit() cap = Countries( capitals="Jakarta", location=loc1 ) session.add(cap) session.commit() How is this done with django's orm? -
MultiSelectField in Django Models
Suppose, I have a list of professionals. I need to filter them based on their availability(Monday, Tuesday...etc). For example, a professional can select Monday and Tuesday as his available days. How can I implement this in Django models. Is there any way? NB : I'm not refering to Django Forms or MultiChoiceFields or Choice fields. Also I'm using Django 1.9, Is there anyway to use the widget django-multiselectfield in here successfully. Coz I've already tried all possibilities. Thanks in advance -
django:adding more than one value in model field
i want to create a app for classroom in which their only one teacher and students can be more than one. i want to store usernames of students in one classroom. is there any model field i can use to store usernames of students. my code so far: models.py from django.db import models from django.conf import settings # Create your models here. class classroom(models.Model): teacher = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) students = models.CharField(max_length=120) -
Django iteration (for ... in ...) how to put it in different divs?
I have few instances of model. my model: class Record(models.Model): name = models.ForeignKey(Car) image = models.ImageField(upload_to='images/') created = models.DateTimeField( default=timezone.now) view: def allrecords(request): records = Record.objects.all().order_by('created') return render(request, 'mycar/allrecords.html', {'records' : records}) I want show it on my website. In my template i have: {% for record in records %} <img src={{ record.image.url}}/> <div> {{record.name}} </div> {% endfor %} Now i get list of my records, but i would like put the newest record to first div, next to second etc. How can i do that? I show simple screen how i would like have that (if someone will create new record, it will go to first div and other records will change place. Is any possibility to do something like that? -
Protecting a view without requiring login in Django?
I'm trying to password protect my registration page in Django without requiring the user to login, but I can't seem to figure it out. My flow should be: User accesses mydomain.com/register/ User enters password into registration_access form If unsuccessful, user re-enters password If successful, user is presented with UserCreationForm If UserCreationForm is not filled out properly, user is presented with UserCreationForm again + errors If UserCreationForm is filled out properly, user is redirected to their profile page The issue I'm having right now is that I can't redirect a user to a view without a URL (the view containing UserCreationForm). Here's my code: views.py def register(request): if request.method == 'POST': # Gather information from all forms submitted user_custom_info = user_information(request.POST) user_info = UserCreationForm(request.POST) profile_info = deejay_form(request.POST) # Check to make sure they entered data into each of the forms info_validated = user_info.is_valid() and user_custom_info.is_valid() and profile_info.is_valid() # If they did... if info_validated: # Clean the data... user_custom_info = user_custom_info.cleaned_data user_info = user_info.cleaned_data profile_info = profile_info.cleaned_data # Create a new user with those traits new_user = User.objects.create_user(user_info['username'], user_custom_info['email'], user_info['password1']) new_user.first_name = user_custom_info['first_name'] new_user.last_name = user_custom_info['last_name'] new_user.save() # Create a new deejay with those traits.. new_deejay = Deejay(user=new_user, dj=profile_info['dj'], role=profile_info['role'], bio=profile_info['bio'], phone=profile_info['phone']) β¦ -
How to upload a file from webpage and show the name in table in Django
I have been doing the research for a long time and cannot figure out. I have my Django app linked to mysql db which was created by my model "CostDetl", and I have a webpage to display my model table. In the table, I have a filefield "Agreement", where I would like the webpage to show browse and upload form in the cell for each table row, and if anything is uploaded and the filefield is not empty, the table cell would just show the file name with a link to open the uploaded file. I have no problem displaying the uploaded file with the link and I can upload the agreement in Admin, but I cannot figure out how to upload from the webpage. Please help! The following are all my code, much appreciated! Settings: MEDIA_ROOT = '/Users/username/myapp/media' MEDIA_URL = '/media/' In project urls.py, I added: url(r'^media/', views.UploadAgreementView), In models.py: def content_file_name(instance, filename): return os.path.join(['content', instance.user.username, filename]) class CostDetl(models.Model): Provider = models.CharField(null=True, blank=True, max_length=200) Description = models.CharField(null=True, blank=True, max_length=200) Agreement = models.FileField(null=True, blank=True, upload_to=content_file_name) def __unicode__(self): return self.Provider+' | '+self.Description def __str__(self): return self.Provider+' | '+self.Description Views: def CostData(request): costrecordset = CostDetl.objects.all() context = {'CostDetl1': costrecordset} return render(request, 'polls/CostDetl.html', β¦ -
Whitenoise, Mezzanine, Django -ImportError: cannot import name ManifestStaticFilesStorage
I am trying to deploy my mezzanine project on heroku. The last error gives me an ultimate stack- ImportError: cannot import name ManifestStaticFilesStorage. Here is my core project structure: βββ deploy β βββ crontab β βββ gunicorn.conf.py.template β βββ local_settings.py.template β βββ nginx.conf β βββ supervisor.conf βββ dev.db βββ fabfile.py βββ flat β βββ admin.py β βββ admin.pyc β βββ __init__.py β βββ __init__.pyc β βββ models.py β βββ models.pyc β βββ tests.py β βββ views.py β βββ views.pyc βββ __init__.py βββ __init__.pyc βββ manage.py βββ Procfile βββ README.md βββ requirements.txt βββ runtime.txt βββ settings.py βββ staticfiles -> mezzanine_heroku/staticfiles βββ urls.py βββ urls.pyc βββ wsgi.py wsgi.py: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise application = get_wsgi_application() application = DjangoWhiteNoise(application) Procfile: web: gunicorn wsgi Traceback from heroku-logs: 2016-09-02T18:02:36.124458+00:00 app[web.1]: Traceback (most recent call last): 2016-09-02T18:02:36.124494+00:00 app[web.1]: File "/app/.heroku/python/bin/gunicorn", line 11, in <module> 2016-09-02T18:02:36.124529+00:00 app[web.1]: sys.exit(run()) 2016-09-02T18:02:36.124558+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 74, in run 2016-09-02T18:02:36.124620+00:00 app[web.1]: WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() 2016-09-02T18:02:36.124646+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 192, in run 2016-09-02T18:02:36.124706+00:00 app[web.1]: super(Application, self).run() 2016-09-02T18:02:36.124709+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 72, in run 2016-09-02T18:02:36.124754+00:00 app[web.1]: Arbiter(self).run() 2016-09-02T18:02:36.124800+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 218, in run 2016-09-02T18:02:36.124858+00:00 app[web.1]: self.halt(reason=inst.reason, exit_status=inst.exit_status) 2016-09-02T18:02:36.124862+00:00 app[web.1]: File β¦ -
pass data from the model to view django
Hi everyone I am completely new with Python and Django. I am trying to read info from external database in mysql, for that I create a app inside my project and connect with the external database like this 'cpu_project': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '***', 'USER': '***', 'PASSWORD': '***', 'HOST': '***', } In my main urls.py I add this url(r'^cpu/', include('cpu.urls')), Now in the models.py of my app I have this def cpu(): rows = MyModel.objects.using('mysql').all() return render_to_response('cpu/cpu_data.html', {'rows': rows}) My problem is that I don't know how to pass the data form the model to the view I have this in my urls.py from this app from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] the view.py has this from . models import cpu def index(request): return render(request, 'cpu/cpu_data.html') and my cpu_data.html has this {{ rows }} by I see a white page Any idea about that! Thanks in advance! I try to pass a simple value in the model I change this rows = MyModel.objects.using('mysql').all() for this rows = 1 -
Django: Create new data sets automatically
I have three models. Question, Person and Response. Every person can only have one answer or response to a question. Because of that, I use unique_together: class Meta: unique_together = (("question", "person"),) So, my goal is that I have to each question one answer from every person in my database. I'd like to have that I can choose "Agree"/"Disagree"/"Neutral" in the admin interface to each question and for every person. But I don't want to create all those question/person-pairs. I want that if I create a new question: for every person: create -> new Response object with the new question and that I am able to set "Agree"/"Disagree"/"Neutral" in the admin interace then for every question/person-pair And if I create a new person: for every question: create -> new Response object with the new person and I will add the responses from the person in the admin interface again. But how do I do this that all possible Question/Person pairs are created automatically if I add a new question or person? Here for your information my models. Thanks a lot for your help! from django.db import models class Question(models.Model): these_title = models.CharField(max_length=40) these_text = models.TextField(max_length=200) class Person(models.Model): name = models.CharField(max_length=50) β¦ -
WHMCS with django 1.9 python?
I just want to know if it's possible to use WHMCS with Django framework ? Thank in advance ! -
Why does this very basic query on this Django model fail?
I have the following Django class: from caching.base import CachingManager, CachingMixin from mptt.models import MPTTModel def make_id(): ''' inspired by http://instagram-engineering.tumblr.com/post/10853187575/sharding-ids-at-instagram ''' START_TIME = 1876545318034 return (int(time.time()*1000) - START_TIME << 23 ) | random.SystemRandom().getrandbits(23) class My_Class(CachingMixin, MPTTModel): id = models.BigIntegerField(default=make_id, primary_key=True) # Other Attributes Snipped here for brevity But look what happens when I try to query this class: >>> My_Class.objects.get(pk=5000) Traceback (most recent call last): File "<console>", line 1, in <module> File "my_virtual_env/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "my_virtual_env/lib/python2.7/site-packages/django/db/models/query.py", line 334, in get self.model._meta.object_name DoesNotExist: My_Class matching query does not exist. Why does it fail?? How can I fix this? -
Automatic launch of Celery on Elastic Beanstalk
I've read some of the previous threads on how to do this, but it appears the script given in those threads doesn't work anymore. I know I need a celery.config file to be placed in my .ebextensions directory. That file needs to configure celery and then run supervisord on celery to start it as a daemon. Has anyone had luck doing this in the past 6 months or?