Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Maintaining active tab in Django
I'm working on an application that has three tabs, one of which I would like to have marked as active at all times. Based on a similar question, I currently have the following in my base template: <div class="tab"> <a class="{% if request.resolver_match.url_name == 'home' %}active{% endif %}" href="/">Home</a> <a class="{% if request.resolver_match.url_name == 'questions' %}active{% endif %}" href="/questionManager/">Question Manger</a> <a class="{% if request.resolver_match.url_name == 'course' %}active{% endif %}" href="/courseManager/">Course Manager</a> </div> Which works great when navigating between /, /questionManager/, and /courseManager/, respectively. The issue is that if I navigate to another page (for example, /questionManager/addQuestion/), the tab is no longer marked as active. Is there a way that I can maintain the active state no matter where I want to navigate? Specifically, the 'question' tab should be marked active for all /questionManager/*, the 'course' tab should be marked active for all /courseManager/*, and the 'home' tab should be marked active for everything else. I realize I could pass along some variable indicating whether it's question/course/home in the context whenever I'm rendering a response, but that seems like a lot of repetition and I feel like there's an easier way to do what I want to do. -
Django: jwt: How can I keep user logged in even the token can expire in one week period
I am having a mobile app which will show some articles not very sensitive data. My backed is Django with jwt. I am planning to keep 1 month as token expiration time. After the token get expired how to refresh the token without the user to login again. I want to keep them logged in for ever as long as one wants, but at the same time i want the token to be changed, becasue some one can misuse it. How to do this with jwt and Django -
Start thread in Django app after entering runserver command
I want to have a thread which interacts with database and updates the database. This thread is started just after server is started by python manage.py runserver . -
Basic Django Search Implementation
I am having some difficulty retrieving the user submitted data from the form. I am able to hard code a 'term' and successfully search the database, but with the current code I have now, I receive a MultiValueDictKeyError when the results are dynamically populated. So, I am wondering what approach I should use to handle the line: "term = request.GET['term']". views.py def search(self, request): try: r = requests.get( self.URL + 'company/contacts?childConditions=communicationItems/value=' + request, headers=self.Header) r.raise_for_status() except: print(r.text) raise return r.json() def search_bar(request): term = request.GET['term'] results = objCW.search(term) context = {'results': results} return render(request, 'uccx/search.html', context) urls.py urlpatterns = [ path('', views.table_content, name='table_content'), path('search_form', views.search_bar, name='search_bar')] search.html <html> <head> <meta charset="utf-8"> <title>SEARCH</title> </head> <body> <form action="" method="get"> <input type="text" name="term"> <input type="submit" value='Search'> </form> {% if results %} Found the following items: <table class="table"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Company</th> <th>E-Mail</th> </tr> </thead> <tbody> {% for result in results %} <tr> <td> {{ result.id }}</td> <td>{{ result.lastName }}</td> <td> {{ result.company.name }}</td> <td> {{ result.communicationItems.0.value }}</td> </tr> {% endfor %} {% endif %} </tbody> </table> </body> </html> -
Could not install packages due to an EnvironmentError in ec2 server
i'm typing the following in my working amazon ec2 linux server. (with ENV activated) pip install pillow getting this error: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/home/ec2-user/env/lib64/python3.5/site-packages/Pillow-5.1.0.dist-info'. Consider using the `--user` option or check the permissions. if i use --user i get: Can not perform a '--user' install. User site-packages are not visible in this virtualenv. -
Html table rendering
my Django view is returning a list of dictionaries. This goes to html table through template rendering. Below is my template code, My list of dictionary looks like below, Results : [{ 'name' :'x','age': 20}, {'name': 'y','age': 25 }] <table class="table table-striped" border="1" class="dataframe"> <thead> <tr style="text-align: center;"> {% for k, v in results.0.items %} <th>{{ k }}</th> {% endfor %} </tr> </thead> <tbody> {% for x in results %} <tr style="text-align: center;"> {% for y in x %} <td> {{ x.y }} </td> {% endfor %} </tr> {% endfor %} </tbody> </table> Expected output: name age x 20 y 25 But output is blank . Please let me know is there anything wrong with my html table template. -
Django rest framework , serializer - after submitting with POST method will not lead back to homepage
i am a django newbie here. I am confused as in why after i have submitted a POST request, the django rest framework will lead me to this page here instead of bringing me back to my homepage this is my views.py: class TableData(APIView): def post(self,request,*args,**kwargs): startRange = request.POST.get('mcap') endRange = int(startRange) + 29868 sector = request.POST['cat'] print(str(sector)) stocks = StockInfo.objects.filter(Q(company__company_categories__contains=sector),Q(companymcap__range=(startRange,endRange)),Q(datetimecollect__contains=datetime.date(2018,3,13))) serializer = TableSerializer(stocks,many=True) return Response(serializer.data) my serializers.py: class TableSerializer(serializers.ModelSerializer): #stocks = serializers.StringRelatedField(many=True) company_name = serializers.CharField(source='company.company_name') company_id = serializers.IntegerField(source='company.company_id') company_categories = serializers.CharField(source='company.company_categories') class Meta: model = StockInfo fields = ('company_name', 'company_id', 'company_categories','companyprice', 'companyvolume', 'companyeps', 'companydps', 'companynta', 'companype', 'companydy', 'companyroe', 'companyptbv', 'companymcap') My initial idea is that after a person has chosen some criteria from my html form then when they submit the form, I will query the database based on their criteria and load it into a serializer. Then using the serializer to fill up my ajax data table in my html page. I tried my best and i still do not know what is wrong... -
django - python makemigrations
Hi there sorry I'm quite new to Django and Python anyway I'm running python 2.7 on mac and trying to create my first project here. I get an error when trying the shell command 'python manage.py makemigrations'. I did the upgrade of the pip previously 'pip2 install --upgrade pip' otherwise django could not get installed. So I don't know if it might be a matter of django version or... (mydjangoblog) ninodidoxxx:mydjangoblog antoninodanselmo$ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/antoninodanselmo/Desktop/mydjangoblog/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/antoninodanselmo/Desktop/mydjangoblog/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/Users/antoninodanselmo/Desktop/mydjangoblog/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/antoninodanselmo/Desktop/mydjangoblog/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/antoninodanselmo/Desktop/mydjangoblog/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/antoninodanselmo/Desktop/mydjangoblog/mydjangoblog/posts/models.py", line 15 def__str__(self): ^ SyntaxError: invalid syntax MY MODELS.PY IS # -*- coding: utf-8 -*- #from __future__ import unicode_literals from django.db import models # Create your models here. class posts(models.Model): titolo = models.CharField(max_length=120) contenuto = models.TextField() data = models.DataTimeField(auto_now=False, auto_now_add=True) slug = models.SlugField() #python 3 def__str__(self): return self.titolo #python 2 def__unicode__(self): return self.titolo AND THE SETTING.PY IS # Application definition INSTALLED_APPS = [ 'posts', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', … -
How to run a single django project for different customers
i have developed a web application named “SANET” using django, gunicorn and nginx for a customer named “A” and gave them access using “custumerA.mydomain.com”. Now a new customer “B” has ordered a dedicate version. Here is what i think im able to do: . i want them all on a particular server . 1) make a copy from project and deploy it on “customerB.mydomain.com” like a compeletly different project! . 2) find a way to just change the project “database config” depend on which domain has client requested! . It would be appreciated if you can guide me to choose one or offer me a better way! . *sorry for my english ;)) -
Django Rest Framework with android error while sending email (Very unique)
I have created a Custom User model in django rest framework for android application. I used post receive signals for Activate User model. Every thing works fine if i create the user without sending email. But when i send email it shows user already exists and pings the register url twice creating the user second time. This error occurs only while using android app but does not show when using postman. Here is my code: Models.py class UserManager(BaseUserManager): def create_user(self, username, email, password=None, **extra_fields): """ Creates and saves a User with the given username and password. """ if not username: raise ValueError('Users must have an username') if not password: raise ValueError('Users must have a password') if not email: raise ValueError('Users must have an email') user = self.model( username=username, email=email, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, username, email, password, **extra_fields): """ Creates and saves a superuser with the given username and password. """ user = self.create_user( username, email, password=password, **extra_fields, ) user.is_staff = True user.save(using=self._db) return user def create_superuser(self, username, email, password, **extra_fields): """ Creates and saves a superuser with the given username and password. """ user = self.create_user( username, email, useremail=username+"@antef.co.in", password=password, **extra_fields, ) user.is_superuser = True user.is_staff … -
How to activate mod_wsgi 4.6.4 with apache2.4
I have installed apache on my ubuntu 14.04 using `sudo apt-get install apache2 apche2-dev' and mod_wsgi4.6.4 mod_wsgi documentation But after doing make install i got the following. ---------------------------------------------------------------------- Libraries have been installed in: /usr/lib/apache2/modules If you ever happen to want to link against installed libraries in a given directory, LIBDIR, you must either use libtool, and specify the full pathname of the library, or use the `-LLIBDIR' flag during linking and do at least one of the following: - add LIBDIR to the `LD_LIBRARY_PATH' environment variable during execution - add LIBDIR to the `LD_RUN_PATH' environment variable during linking - use the `-Wl,-rpath -Wl,LIBDIR' linker flag - have your system administrator add LIBDIR to `/etc/ld.so.conf' See any operating system documentation about shared libraries for more information, such as the ld(1) and ld.so(8) manual pages. ---------------------------------------------------------------------- chmod 644 /usr/lib/apache2/modules/mod_wsgi.so Then i have tried LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so But this gives me an error below. LoadModule: command not found So when i searched google, i understand that for Debian we have to use a2enmod and hence i tried sudo a2enmod /usr/lib/apache2/modules/mod_wsgi.so but this gives me another error below. ERROR: Module mod_wsgi.so does not exist! How to configure mod_wsgi with apache2.4 and python 2.7 to … -
Django with postgress using REST migrate error
(venv) D:\PycharmProjects\postgressDemo>python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\django\core\management__init__.py", line 364, in execute_from_com mand_line utility.execute() File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\django\core\management__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\django\core\management\base.py", line 327, in execute self.check() File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\django\core\management\commands\migrate.py", line 62, in _run_chec ks issues.extend(super(Command, self)._run_checks(**kwargs)) File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\Lib\importlib__init__.py", line 37, in import_module import(name) File "D:\PycharmProjects\postgressDemo\postgressDemo\urls.py", line 4, in from rest_framework import routers, serializers, viewsets File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\rest_framework\routers.py", line 26, in from rest_framework import views File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\rest_framework\views.py", line 16, in from rest_framework import exceptions, status File "D:\PycharmProjects\postgressDemo\venv\lib\site-packages\rest_framework\exceptions.py", line 19, in from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList ImportError: No module named utils.serializer_helpers i am using … -
Django vs Angular for a simple page to show results of a Python program
I'm working on a school project on Machine Learning where I implemented a Python program using Tensorflow, and now I have a set of results (predictions) in the form of CSV/JSON that I want to display to the user. I've decided to make a not too complex web page (only home page, no user's profile, admin page, etc) to show my results. After reading about Django I thought it would integrate niceley with the Python program and I managed to create a website, but I'm starting to realize that maybe Django would be too back-end focused: I'm heavily using the template side, mainly a lot of Javascript (jQuery and Chartjs), and only using the controller side to pass the JSON results to the template. I've never worked on Angular, but I read it's more client side front-end based, so it might be a better option for the interface I want to create. So what would be the simplest way to create the web app? Should I continue using Django and Javascripts libraries, even though I'm virtually not exploiting any of the back-end features, or should I go with Angular? -
Django Rest Swagger 2.2.0 Api's on TokenAuthentication not being shown
Currently, I'm using DRF 3.7.7 and Django-rest-swagger 2.1.2, in the following fashion. settings.py SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'api_key': { 'type': 'apiKey', 'in': 'header', 'name': 'Authorization' } }, # 'LOGIN_URL': getattr(settings, 'LOGIN_URL', None), # 'LOGOUT_URL': getattr(settings, 'LOGOUT_URL', None), 'DOC_EXPANSION': None, 'APIS_SORTER': None, 'OPERATIONS_SORTER': None, 'JSON_EDITOR': False, 'SHOW_REQUEST_HEADERS': False, 'SUPPORTED_SUBMIT_METHODS': [ 'get', 'post', 'put', 'delete', 'patch' ], 'VALIDATOR_URL': '', } views.py from rest_framework.schemas import AutoSchema class RandomClass(APIView): authentication_classes = (TokenAuthentication, ) permission_classes = (IsAuthenticated, ) schema = AutoSchema( manual_fields=[ coreapi.Field( "page_id", required=True, location="query", type="string", description="Facebook Page ID" ) ] ) This allows me to somewhat use drf-schema to render each view individually in swagger docs. The caveat is that, since this view enforces Authentication, only after I authorize an user (authorization by token, as per swagger settings security definitions) I can view all my IsAuthenticated views. Also, If a single view function has multiple methods (get and post) the schema generation for both is same (if I do it this way. I have two problems here. I want to know what would be the proper way to move forward for APIView using TokenAuthentication (I didn't get any useful docs whatsoever and had to scrape forums for a working solution). The Authorization … -
Get All Issues on GitHub repository in specific month using GitHub API
I am trying to get all Pull requests created by specific user in a specific month in my django application using GitHub API. e.g: https://api.github.com/repos/myrepo/example/issues?creator=person_name&start_date=2018-1-1&end_date=2018-1-31 -
How to tell which application or model will be processing a given URL?
So for example: if I'm working in an arbitrary application and or model but I want to get a handle to the application and / or model that will be actually handling the current URL in the browser address bar. -
Django tags showing on live server
I'm trying to upload my django site for the first time but all the template tags are showing. You can see what I mean right here. I'm running it on an AWS ec2 instance and have used CodeCommit, CodeDeploy and Codepipeline, all of which are set up correctly as I am able to make changes on the website. It runs fine on my local machine but I've never seen an error message like this. I feel like I havent installed something or set something up properly? When I run django-admin version I see that 2.0.5 is installed but when I try to run migrations, I get this error message: Traceback (most recent call last): File "/usr/local/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File "/home/ec2-user/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/ec2-user/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ec2-user/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 216, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/ec2-user/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 36, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, … -
How do I check if a Model name exists in Django?
What Django command(s) must I use to check if model SomeModelName exists? -
Adding a KML file into a GeoDjango field
I'm trying to add a KML file to a field in GeoDjango. Link to KML file. I tried to follow the answer on this question but it's mostly wrong. My model: class School(models.Model): boundaries = models.PolygonField(null=True) i = School.objects.get(...) ds = DataSource('school.aspx') layer = ds[0] #The file only has 1 layer geom = layer.get_geoms() boundary = GEOSGeometry(geom[0]) i.boundaries = boundary i.save() The above code gives me the following error: TypeError: Improper geometry input type: <class 'django.contrib.gis.gdal.geometries.Polygon'> When I try to add the field directly, like this: i = School.objects.get(...) ds = DataSource('school.aspx') layer = ds[0] geom = layer.get_geoms() i.boundaries = geom[0] i.save() I get this error: TypeError: Cannot set School SpatialProxy (POLYGON) with value of type: <class 'django.contrib.gis.gdal.geometries.Polygon'> How do I save the polygon shape in the KML file into my database? I'm stumped. -
How to remove default admin in django?
I saw the django stores sessions in database and groups and permission are also..how can i remove everything because i want to create my own admin side. if any technique available to store session without using database. -
Django readinf csv file failed
I'm a begining in Django, and i try to read an upload file but i can't, i passed hours and hours to found solution, but i didn't, can any one help me plz, My code is bellow : def Savedocument(request): uploadFailed='Your upload is failed, the format of file must be a csv file, Please try again' docfile = request.FILES["docfile"] if not docfile.name.endswith('.csv'): messages.error(request,'File is not CSV type') return render(request,'app/modelisation.html',{'uploadFailed':uploadFailed}) if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() listApp=[] paramFile = request.FILES['docfile'].read() data = csv.DictReader(paramFile) for row in data: listApp.append(row) return render(request,'app/modelisation.html',{'listApp':listApp}) return render(request,'app/modelisation.html') -
Is there a way to regenerate PO files from weblate with new formatting?
In an attempt to reduce the frequency of merge conflicts and unhelpfully large diffs in weblate generated PO files I have opted to use the "no wrap" formatting option of the "Customize gettext output" addon on an existing project. This seems to work fine however the nowrap formatting is only applied to strings that are modified. Is there a way I force weblate to regenerate all strings in the PO files even if the string is unchanged (thereby applying nowrap to every translation string in the project/component)? https://docs.weblate.org/en/latest/admin/addons.html#customize-gettext-output -
DJANGO Login // INPUT FIELDS not working // Error messages not showing
****** Hear me out, I know this is kinda long and I hate to sound like this, but I haven't slept in 4 days and this is part of my project due for school so I would really appreciate literally any input on this ****** Hello, I'm relatively new to Django but nonetheless, I've been bouncing from tutorial to tutorial on youtube and Django documentation try to make up for that. I've created the polls application, and was also creating several other applications but both times when I was almost complete, they went COMPLETELY blank white and I had to START ALL OVER. At this point, I'm just about tired of Django, but I'm willing to continue because I really hate quitting. Anyways that's not what this question is about (although if you could help get my apps up and running again that would be great! I'll put a link down below). After my most recent app crash after trying to learn how to do a login page. I started yet another app called accounts which would be SOLELY dedicated to login/logout/register. However, so far things haven't been working out great. I started out following one tutorial on youtube, but … -
How to tell whether migrations are reversible?
In a project I'm working on, we run some tests against snapshots of production databases. For changes including migrations, I'd like to apply the migrations, run the tests, and the reverse the migrations. However, not all migrations are reversible. How can I have an automated process detect whether all required migrations are reversible before applying them? -
Django instance crashes after a while when running on elastic beanstalk
im running a django project with elastic beanstalk. I'm using Python 3.6 running on 64bit Amazon Linux/2.7.0. Already earlier had a problem with mod_wsgi and had to follow https://serverfault.com/questions/884469/mod-wsgi-call-to-site-addsitedir-failed-on-aws-elastic-beanstalk-python-3 to avoid daily crashes. Now my eb instance is crashing in a weird way after a random amount of time (usually couple hours). The logs provided below show a weird /RPC2 POST that starts a flood of csrf errors and end with a SIGTERM. After the crash the server tries to restart but with disregard of env vars like DJANGO_SETTINGS_MODULE. The variable is set in 01_packages.config and I can see it set properly in the aws console. Any ideas what could cause this? Not sure if this is all the data required, but this is what I've found so far in the logs. error.log [Wed May 30 23:46:23.013771 2018] [wsgi:error] [pid 20187] Forbidden (CSRF cookie not set.): /RPC2 [Wed May 30 23:46:23.013890 2018] [wsgi:error] [pid 20187] WARNING:django.security.csrf:Forbidden (CSRF cookie not set.): /RPC2 [Thu May 31 01:06:26.046042 2018] [wsgi:error] [pid 20187] Forbidden (CSRF cookie not set.): / [Thu May 31 01:06:26.046159 2018] [wsgi:error] [pid 20187] WARNING:django.security.csrf:Forbidden (CSRF cookie not set.): / [Thu May 31 01:08:26.330210 2018] [wsgi:error] [pid 20187] Forbidden (CSRF cookie …