Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms: MultipleChoiceField does not select options from instance
I have a form from a model. Depending on "property_type" would be dynamically build a (or multiple) field for "property_values". The result HTML form is right but the options for the multiple select field for "Property value" will not be selected from the instance. My form is: class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) if 'instance' in kwargs: if self.instance.property_type == models.Property.RANGE: self.fields['property_values'] = forms.MultipleChoiceField( choices=( ('lt', '<'), ('eq', '='), ('gt', '>') ) ) self.fields['property_values'].label = 'Value' class Meta: model = models.Property fields = ['property_type', 'property_values'] labels = { 'property_type': 'Type', } widgets = { 'property_type': forms.Select(), } In the Database the field property_values is: ['eq', 'gt'] -
How to integrate add django form in Django admin site
I want to add some custom textbox(dynamic) and buttons in my Django admin app for some calculation. How would i add it as inline in django-admin -
How to ensure AWS Elastic Beanstock is free
I am wanting to deploy a Django webapp with a PostgreSQL database to AWS Elastic Beanstock using this tutorial, but I am so confused about pricing. It says it uses services in the AWS Free Tier, but those seem to be limited to a certain number of hours a month, so how do I make sure I don't go above that threshold? And how do I make sure I'm only using free services? They even require a card on file, so it seems really hard to make sure I don't get charged. -
Django - How to avoid white space in django forms?
i'm using model.forms to get <input>data from user. also i'm using regular expression for that data. eg: Input = tomorrow then urls looking like : www.mysite.com/tomorrow/ problem: when user put tomorrow holiday with whitespace i get error. i tried .strip() in views.py to avoid white space. it gives error. -
Django cant find static files on server, but works fine on local machine
I have a vps running with django, i'm developing the site from my local machine, and pushing it up to the vps by git. On my local machine i've just installed the initializr, and changed all scripts to use the static location, and everything works fine there, but when i push it to my vps, all it finds is the .html files, it cant find either .css or .js scripts the vps is running Debian 8.* Minimal, with nginx, and gunicorn My local machine is running MacOs Both machines runs Python 3.6.2, and Django 1.11.4 Here are the relevant settings from settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "BaseFiles/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', ], }, }, ] ... STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "BaseFiles/static"), ) My paths are: Project_folder/ -> BaseFiles | Django_project | manage.py BaseFiles/ -> static | templates -
How to put check condition(i.e user is logged in or not) in resolve property?
I am new to Angular JS and Django. I am working on a project in which back end is implemented using Django framework. In this project multiple API's are there. Our front end is developed using Angular JS (Actually it is Angular JS Single page Application).I want to know that what would be the way to put a check condition that user is logged in or not before each API call.Because we want to reduce unecessary Api calling untill a user logged in. Currently , However we have implemented authentication mechanism in our back end part but we also want to implement some mechanism in front end so that untill a user logged in ,no request will pass to server. We want that if user is not logged in then no api should be called(i.e controller should not be loaded).But as soon as a user logged in, api should be called without reloading the browser. The solution which I have tried i am providing in following section.please correct me because i know that surely i am doing something wrongly. In rsf function , I am confused what should be written inside if statement. Please suggest some method. Thanks in advance. … -
How to customise Django admin filtration based on my requirement?
I have a model as follows - class Student: name = models.CharField() phone = models.CharField() country = models.CharField() I want to filter the following in admin page using phone --> valid phone no (it needs to meet phone no criteria of the country based) --> invalid phone no (which doesn't meet the criteria of the country based) --> duplicate phone no (same no registered by 2 or more students) I don't want to validate anything while the student is registering. I just want to filter by myself in the admin page. Thanks alot for your time -
Multi-Container Docker on AWS
I've can't seem to get my head around the Dockerrun.aws.json file, which is needed to run a multi-container docker environment on AWS Elastic Beanstalk. Everything works fine locally, when I run my app through Docker-Compose. The following is my docker-compose.yml file: version: '2' services: interfaceserver: build: . command: daphne -b 0.0.0.0 -p 8000 restbench.asgi:channel_layer user: app working_dir: /app ports: - 8000:8000 depends_on: - database - redis workerserver: build: . user: app working_dir: /app command: python manage.py runworker depends_on: - database - redis database: image: postgres:9.5 redis: image: redis:3.0-alpine Essentially I am trying to run four services. A Interface-Server, a Worker-Server, a Postgres Database and a Redis Server. The Interface-Server and the Worker-Server and my own Django Builds from a local Dockerfile which are in the same directory as the docker-compose.yml Now I am trying to deploy my app to Elastic Beanstalk and, from what I understand, I need a Dockerrun.aws.json, which is the same as a docker-compose.yml, just for AWS. I try to read the docs from EBS, but as I mentioned above I can't get my head around the part where I specify the Interface- and Worker-Server. The Database and Redis part is easy, but I don't understand how … -
How to update django-session without page refresh?
I am trying to add an item to the session without refreshing the page. I am able to add as many items as but I can only see them after refreshing the page. This is the sample code I used to add items without page refreshing. <iframe name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe> <form action="{% url 'myurl' 'id' %}" method="post" class="form-inline" target="hiddenFrame"> Any idea how to update django-sessions without refreshing the page? -
Django view not loading from the project folder
I'm having an issue with loading a view in Django. FYI very new to Django ;) The error that I'm getting is TemplateDoesNotExist at /polls/ Django is loading from the "Exception Location "/Users/NAME/anaconda/envs/Django/lib/python2.7/site-packages/django/template/loader.py" It should load from "/Users/NAME/Documents/Django/template/index.html" I have in my APP view.py return render(request,'index.html') My settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["/Users/NAME/Documents/Django/template/"], How do I load from the view from my project file? -
Including forms in Django
I am trying to create a form that will allow the user to input a name in a text field and input several numerical values (A, B, C, D, ...). Afterwards, I would like to have this information saved to the database and have all the numerical values added up and returned to the user. class Player(models.Model): name = models.CharField(max_length=15) A = models.IntegerField() B = models.IntegerField() C = models.IntegerField() D = models.IntegerField() I am very new to Python and Django so I tried to use the polls app as a starting point. I then looked up some forms tutorials like this one. This seems to be the closest thing I could find but it was written almost 6 years ago and does not seem to be compatible with the version of Django I am using (1.11.4) since I keep getting errors about commands not being recognized, look them up and they are different on a different version. My question is: How do I adapt the forms tutorial linked above to the newer version of Django? Any help would be appreciated. -
Web Scraping Python Script is not working in Heroku
I have created a django app which is deployed in Heroku. Everything within the Django is working fine. I am having problem running a extra script which scraps some data from websites and send emails to the users stored in the sqlite3 database. In my Procfile I have two processes, one is web and other one is clock.That script is working fine and users are getting the mails when run both locally (heroku local clock) and without heroku (python myscript.py) but when I am trying to run the script in the heroku app in the web it's crashing. First I thought this can be a problem with SMTP. so I changed from TLS to SSL. But that did not resolve the issue. The script is using BeautifulSoup4. So script is being executed till the urllib3.PoolManager() and request the website for data, after that it's crashing. I don't understand what can be the problem. Is there something I need to configure additionally in heroku dashboard to make this happen? I have also added the apscheduler, and added my scrapping function there. Is it the proper of doing the task? There is something problem with my code format(may be because of sublime3) … -
django how can I showing daily schedules of all users?
I'm using Django to make a website for gym trainers. what I want is a template for the daily schedules of all trainers like this But, my page is The problem is the td per trainer's tr repeats as many as the number of schedules the trainer has. I know the {% for sc in schedules %} is the problem. But, because schedules are the query set, I should use the for and while using for, I should check the right time to insert the schedule to the right tr, td position. How can I make the successful table to show the daily schedules of all users(trainers)?? Anybody will be very helpful to me. Schedule.model class Schedule(models.Model): Trainer = models.ForeignKey(settings.AUTH_USER_MODEL,blank=True,null=True, related_name='schedule', on_delete=models.SET_NULL) title = models.CharField(max_length=12,blank=True,) start = models.DateTimeField(null=True, blank=True) my views.py def staff_daily_schedule_search(request): all_schedules = Schedule.objects.all() Fitness_list = User.objects.filter(groups__name='Fitness') # Fitness Trainers search_date1 = request.GET.get('search_date','') search_date= datetime.datetime.strptime(search_date1, '%Y-%m-%d') #%T = %H:%M:%S '%Y-%m-%d' schedules= Schedule.objects.none() for f in Fitness_list: sc = f.schedule.filter(start__year=search_date.year).filter(start__month = search_date.month).filter(start__day = search_date.day) print(sc) schedules |= sc context = { 'search_date' : search_date1 if search_date1 else datetime.date.today(), 'Fitness_list':Fitness_list, 'schedules' : schedules, } return render(request, 'management/staff_daily_schedule.html', context) staff_daily_schedule.html <form action="{% url 'management:staff_daily_schedule_search' %}" method="GET"> <span><input type="date" class="search_date my-control" name="search_date" … -
Best way to create Specific Surveys with Django?
I'm very lost in Django. Recently I've begun the project to create a website for my school's student government, and part of that is gathering information from the student body. I've been playing with models and forms for the past view days attempting to find a good way of collecting survey data about real-world events that are rather dynamic but related. For example: there's a weekly event that typically revolves around 3 or 4 events, but there can be multiple instances of those specific events, each event instance needs individual input from the student body. Because of this, I'm lost in creating survey backend. The only answer I can find is to create a model for the surveys and then a modelForm based on that. While this seems like a fine solution for data that will always have the same number of everything, I don't see a way of modifying the data to work with dynamic data. Here's the sloppy mess I have so far: class Game(models.Model): name = models.CharField(max_length=200, default='None', blank=False, null=True) description = models.TextField(default='Describe the Game Here!', blank=False, null=True) number_of_participants = models.PositiveIntegerField(verbose_name='Number Of Participants', blank=False, null=True) estimated_length = models.PositiveIntegerField(verbose_name='Estimated Length', default=10, blank=False, help_text='Minutes') def __str__(self): return '{}'.format(self.name) class … -
Accessing locally hosted site through public ip
I have setup a django app on a apache server in a VM. The site is accessible when I use the apache server IP in the VM browser. It is also accessible from the host browser through it's local IP. But, I cannot access it through the public IP over the internet. I get a site can't be reached error I have set up port forwarding such that: 1. All router requests on port 80 are forwarded to local IP 2. All requests to local IP on port 80 are forwarded to the VM I checked if my port is open on my public ip using http://www.yougetsignal.com/tools/open-ports/ It says that my port is closed. Same results with http://canyouseeme.org/ I am able to ping my public ip successfully. I have tried disabling all my firewalls but this has not helped. Please tell me if you need any code to be shared. Any help would be appreciated. -
fetch all last two days objects according to uploaded date in django
In my model News I have-- NewsId,NewsSummary, date = models.DateTimeField(auto_now_add=True, blank=True) I want to fetch all last two days news according to uploaded date. How to do it??? -
expire old JWT token when user login
I am using django-rest-framework-jwt token. More details can be checked @ django-rest-framework-jwt With default configuration it allows to login single user from multiple systems simultaneously. But we don't want to expire all previous tokens if user login again. Since JWT do not store tokens into database, I am not sure how can we achieve this? JWT tokens are not stored into database. Hence it not seems that straight to expire a token when user login. Also the way JWT token works, I don't think we can achieve this. One possible way seems to achieve if i can override token creation and validation methods. In this I will pass information when user have last logged in then it possible to achieve it. If last logged in information is different than what stored in database then I will not allow user to do further action. So theoretically it seems possible. But I am not getting any documentation to override JWT token creation and validation methods. Please guide me how should I proceed further. -
Pagination for very long string Django 1.11 (Python 3.6)
I'm trying to create my own blog site which might contain a very long story (from one field in database). I successfully create pagination for list of records (for the list of stories) on my other views and tried to experiment from the Django documentation. What I did is create an array from the very long string so django pagination can count it. "views.py" def post_detail(request, slug=None): #retrieve instance = get_object_or_404(Post, slug=slug) words_list = instance.content.split() paginator = Paginator(words_list, 500) # Show 25 contacts per page page = request.GET.get('page') try: words = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. words = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. words = paginator.page(paginator.num_pages) if instance.draft or instance.publish > timezone.now().date(): if not request.user.is_staff or not request.user.is_superuser: raise Http404 share_string = urlquote_plus(instance.content) context = { "title": instance.title, "instance": instance, "share_string": share_string, "word_content": words, } return render(request, "post_detail.html", context) I successfully created it but as a list of words from top to bottom instead of paragraph format which doesn't look good at all. "post_detail.html" {% for word_con in word_content %} <p class="text-justify">{{ word_con }}</p> {% endfor %} I tried to … -
The table-striped class is not giving me alternate color
I was hoping to have alternating color for my table. However, all rows become grey after I applied the table-striped class. I tried to load both v3 and v4 boostrap css files. And it still didn't work. html <table id="maxDiversificationTable" class="investmentTable table table-striped table-bordered table-hover table-fit" style="margin-top:-55%" > <thead> <tr style="color:#337AC7" > <th >Tickers</th> <th >Current Weight</th> <th >New Weight</th> <th >Conviction</th> </tr> </thead> {% for tableData in dataSet %} <tbody> <tr> <td>{{tableData.tickers}}</td> <td>{{tableData.currentWeight}}</td> <td>{{tableData.newWeight}}</td> <td>{{tableData.conviction}}</td> </tr> </tbody> {% endfor %} </table> -
Django - Filter and display a model based on dropdown selection
I would like to display a table from a model that is filtered based on a dropdown box selection. I created a drop down using form. The values in the dropdown are distinct values of sensor_loc_blg. If the user makes a selection from the dropdown box, then table that filter all rows that have sensor_loc_blg as the selected value will be displayed. Following is my attempt: models.py class SensorsTable(models.Model): sensor_uuid = models.CharField(primary_key=True, max_length=32) sensor_desc = models.CharField(max_length=256) sensor_mid = models.CharField(max_length=256) gw_uuid = models.CharField(max_length=32, blank=True, null=True) sensor_loc_lat = models.DecimalField(max_digits=11, decimal_places=8, blank=True, null=True) sensor_loc_long = models.DecimalField(max_digits=11, decimal_places=8, blank=True, null=True) sensor_loc_blg = models.CharField(max_length=100, blank=True, null=True) sensor_loc_room = models.CharField(max_length=100, blank=True, null=True) sensor_loc_position = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'sensors_table' def __str__(self): return self.sensor_uuid forms.py from django import forms from .models import * class LocationChoiceField(forms.Form): locations = forms.ModelChoiceField( queryset=SensorsTable.objects.values_list("sensor_loc_blg", flat=True).distinct(), #empty_label=None ) views.py from django.http import HttpResponse from django.template import loader from django.shortcuts import render from django.views.generic.edit import CreateView from .forms import * from .models import * #def index(request): # return HttpResponse("Smart Uni Analytics Test") def index(request): if request.method =='POST': location_list = LocationChoiceField(request.POST) if location_list.is_valid(): selected_location = location_list.cleaned_data['locations'] query_results = SensorsTable.objects.filter(sensor_loc_blg='MAT') else: location_list = LocationChoiceField() query_results = SensorsTable.objects.all() else: location_list = … -
Django session variables lost when set in form_valid() of class-based views
Using Django, if I set a session variable within the post() method of a django.views.generic.edit.FormView class, that variable is then available for future requests. e.g. def post(self, request, *args, **kwargs): """ Store useful data in session variable for future requests """ if 'useful_data' in request.POST: request.session['useful_data'] = useful_data return HttpResponseRedirect(self.get_success_url()) If however, I attempt to set a session variable via the form_valid() method of a django.views.generic.edit.FormView class, the changes I make to the variable seem to disappear before the next request. e.g. def form_valid(self, form): """ Store useful data in session variable for future requests """ # Useful data that I only want to update if the form was validated self.request.session['useful_data'].update(form.cleaned_data['useful_data']) return HttpResponseRedirect(self.get_success_url()) So, how can I make persistent changes to session variables from the form_valid() method of a django.views.generic.edit.FormView class? -
Adding extra fields to Django site
I have a project that uses Django's django.contrib.sites.models.Site framework, Now I need to store an additional value per site. Currently, site contains the below fields id | integer | not null domain | character varying(100) | not null | extended | | name | character varying(50) | not null And here is the model class Site(models.Model): domain = models.CharField( _('domain name'), max_length=100, validators=[_simple_domain_name_validator], unique=True, ) name = models.CharField(_('display name'), max_length=50) What is the cleaner way of adding an extra field to the Site with a minimal footprint? -
Django cannot find __init__.py in the project folder when creating a new app
Everything is set up. Inside the apps folder and the project folder inside the project, there is an init.py double-checked to make sure the underscores are correct. I am trying to create a new app using python ../manage.py startapp {{blogs_app}} but I keep getting the error messages: Syntax Error: invalid syntax cannot find the file sample_project/sample_project/init.py (additional info: I'm using Windows terminal. The two underscores before and after init are there, stackoverflow won't display them for some reason.) -
Django Channels Daphne on AWS with to many environment variables
I've been trying to run Django Channels on AWS. I got to run daphne and workers with supervisord but I got in troubles because I'm using AWS environment variables, too many of them with special characters as well. How can I manage to run daphne without putting all my environment variables again on supervisor, and how can I cope with variables like SECRET_KEY that contains special characters? This is the message that I got: Traceback (most recent call last): File "./DrAmor/settings/__init__.py", line 15, in <module> from .production import * File "./DrAmor/settings/production.py", line 11, in <module> (os.environ['ADMIN_NAME'], os.environ['ADMIN_EMAIL']), File "/opt/python/run/venv/lib64/python3.4/os.py", line 633, in __getitem__ raise KeyError(key) from None KeyError: 'ADMIN_NAME' This is the script that I have on my production settings: """Production settings and globals.""" from __future__ import absolute_import from .base import * if not DEBUG: ########## MANAGER CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#admins ADMINS = ( (os.environ['ADMIN_NAME'], os.environ['ADMIN_EMAIL']), ) # See: https://docs.djangoproject.com/en/dev/ref/settings/#managers MANAGERS = ADMINS ########## END MANAGER CONFIGURATION ALLOWED_HOSTS = ['*'] INSTALLED_APPS += ( 'storages', ) ########## STATIC FILE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] AWS_STORAGE_BUCKET_NAME = os.environ['S3_BUCKET_NAME'] AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_HOST = 's3-us-west-2.amazonaws.com' STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storages.StaticStorage' STATIC_URL = … -
Getting 'None' while trying to initiate a class object
I was trying to initiate an object called tableData. However, when I do print(data), it returns none. .models.py class tableData(object): tickers = '' currentWeight = 0.0 newWeight = 0.0 conviction = 0.0 def __init__(self, tickers, currentWeight, newWeight,conviction): self.tickers = tickers self.currentWeight = currentWeight self.newWeight = newWeight self.conviction = conviction views.py data = tableData('ticker', 0.01, 0.01, 0.01)