Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reporting system in Python for multiplatform usage
I am facing a new challenge to write Reporting system. The system will be running on multiple server based on platforms linux and windows. There is actually running JasperReport on those servers but because of the price and other reasons they would like to build their own solution. I am thinking what technologies to use. I know I want to build it within a Python. Base Requirements: wsgi application multiplatform solution (linux/windows servers) possibility to create new reports (this will be done just by me or another programmer. New report=SQL query with the parametr). So once new report will be created on central server must be pushed to all servers. REST API My fist thought was to use Python/Django as that is my favourite couple. The main reason to not use Django I am thinking of, is that I will not use the most of django components: ORM -> no need here because report=SQL query (most of them are already written in actual solution) Authentification must be written custom as there is already database with some user/role logic. No admin needed. I am thinking about to use some microframework such as Flask or so. Please do you have any experience … -
Django ckeditor pdf files upload
I am using django-ckeditor==5.3.1 and django==1.11.2. I need to upload non-image file. I need to pdf files upload. But I can't not find solution for this (for example pdf icon in editor panel). Please hint where I can find this. My model: from ckeditor_uploader.fields import RichTextUploadingField class Event(models.Model): title = models.CharField(max_length=500) date = models.DateField() text = RichTextUploadingField() urls.py urlpatterns += [ url(r'^admin/', include(admin.site.urls)), url(r'^ckeditor/', include('ckeditor_uploader.urls')), ] settings.py CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_ALLOW_NONIMAGE_FILES = True CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Simple', 'toolbar_Simple': [ ['Bold', 'Italic', 'Underline'], ['Link', 'Unlink'], ['Image', 'Update', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'uploadwidget'], ], 'autoParagraph': False, 'shiftEnterMode': 2, 'enterMode': 2, }, } -
django returning blank page
i'm not sure what is wrong with the code, forms.py from django.form import datetime, widgets import datetime import calendar from bootstrap_datepicker.widgets import Datepicker class DateForm(forms.Form): date_1=forms.DateTimeField(widget=DatePicker( options={"format": "dd/mm/yyyy", "autoclose": True } (help_text ='please enter a date',initial= "year/month/day"))) def cleandate(self): c_date=self.cleaned_data['date_1'] if date < datetime.date.today(): raise ValidationError(_('date entered has passed')) elif date > datetime.date.today(): return date_1 def itamdate(forms.Form): date_check=calendar.setfirstweekday(calendar.SUNDAY) if c_date: if date_1==date_check: pass elif date_1!=date_check: raise ValidationError('The Market will not hold today') for days in list(range(0,32)): for months in list(range(0,13)): for years in list(range(2005,2108)): views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from django.urls import reverse import datetime from .forms import DateForm def imarket(request): #CREATES A FORM INSTANCE AND POPULATES USING DATE ENTERED BY THE USER form_class= DateForm form = form_class(request.POST or None) if request.method=='POST': #checks validity of the form if form.is_valid(): return HttpResponseRedirect(reverse('welcome.html')) return render(request, 'welcome.html', {'form':form}) welcome.html ** {% extends 'base.html' %} {% block content %} <title>welcome</title> <form action = "{% url "imarket"}" method = "POST"> {% csrf_token %} <table> {{form}} </table> <input type ="submit" value= "CHECK"/> </form> {% endblock %} ** i am trying to implement a datepicker on the welcome page, i have called the form in the views.py , and returned the "welcome.html" … -
demo application issue with models and queryset
I am trying to make one simple application but seems like facing issue. I have created many to many object between student and course and has also define dept. My model is mentioned below: class Course(models.Model): courseId = models.AutoField(primary_key=True) courseName = models.CharField(max_length=100) enrolledStu = models.IntegerField(max_length=3) students = models.ManyToManyField(Student) dept = models.ForeignKey(Dept, on_delete=models.CASCADE) def __str__(self): return '%s %s %s %s' % (self.courseName,self.enrolledStu,self.students,self.dept) class Dept(models.Model): deptId = models.AutoField(primary_key=True) deptName = models.CharField(max_length=100) def __str__(self): return '%s %s' % (self.deptId, self.deptName) class Student(models.Model): stuName = models.CharField(max_length=100) stuCity = models.CharField(max_length=100) stuPhone = models.IntegerField(max_length=10) stuNationality = models.CharField(max_length=50) stuCreatedt = models.DateTimeField(default=timezone.now) def __str__(self): return '%s %s %s' % (self.stuName,self.stuCity,self.stuNationality) my form is : class StudentForm(forms.ModelForm): class Meta: model = Student fields = ('stuName','stuCity','stuPhone','stuNationality','stuCreatedt') class CourseForm(forms.ModelForm): class Meta: model = Course fields = ('courseId','courseName','enrolledStu','students','dept') class DeptForm(forms.ModelForm): class Meta: model = Dept fields = ('deptId','deptName') I have displayed list of course , students and dept in html template now i am trying to edit it with code : def edtStudent(request,pk): course = Course.objects.filter(pk=1).prefetch_related('students').select_related('dept').get() if request.method =="POST": form = CourseForm(request.POST,instance=Course) if form.is_valid(): course = form.save(commit=False) print(form.cleaned_data) course.courseName = request.POST['courseName'] course.enrolledStu = request.Post['enrolledStu'] course.save() course.save_m2m() return redirect('liststudent') else: print(course.__dict__) print(course.students) #form = CourseForm() #return render(request, 'stuApp/edtStudent.html', {'form':form}) #form = CourseForm(instance=course[0]) worked … -
Django IntegrityError NOT NULL constraint failed: accounts_solution.puzzle_id
So I am creating a puzzling app, where you can submit Solutions to puzzles, and add Comments to Solutions. Here are my models: class Solution(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, ) puzzle = models.ForeignKey( Puzzle, on_delete=models.CASCADE, ) title = models.CharField(max_length=30) content = models.TextField() points = models.IntegerField() datetime = models.DateTimeField(default=timezone.now, blank=True) def __str__(self): return self.title class Comment(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, ) solution = models.ForeignKey( Solution, on_delete=models.CASCADE, ) title = models.CharField(max_length=30) content = models.TextField() datetime = models.DateTimeField(default=timezone.now, blank=True) def __str__(self): return self.title I am trying to implement an Add Comment feature using standard Django Forms. Here is my views: if request.method == "POST": # Add Comment feature form = AddCommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user comment.solution = Solution.objects.get(id=solutionID) ## Debugging ## print(comment.title) print(comment.content) print('Solution:') print(comment.solution) print('Puzzle: ') print(comment.solution.puzzle) print(comment.solution.puzzle.id) ############### comment.save() messages.success(request, 'Solution was created successfully!') return HttpResponseRedirect(reverse("solutions", kwargs={'puzzleID': puzzleID})) else: messages.warning(request, 'There are some errors on the form.') return render(request, "add_solution.html", { "form": form, }) And of course my forms: class AddCommentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AddCommentForm, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs['placeholder'] = 'Title' self.fields['content'].widget.attrs['placeholder'] = 'Content' title = forms.CharField() content = forms.CharField( widget=forms.Textarea(attrs={ "rows": 6, }), ) class Meta: model = Solution fields = ['title', 'content'] When … -
self.alias2op: typing.Dict[str, SQLToken] = alias2o
I am trying to integrate mongoDB with django using djongo package, when I do python3 manage.py migrate am getting the following error.. Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/eindhan/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/eindhan/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/home/eindhan/.local/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/eindhan/.local/lib/python3.5/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/eindhan/.local/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/eindhan/.local/lib/python3.5/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/eindhan/.local/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/home/eindhan/.local/lib/python3.5/site-packages/django/db/models/base.py", line 114, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/home/eindhan/.local/lib/python3.5/site-packages/django/db/models/base.py", line 315, in add_to_class value.contribute_to_class(cls, name) File "/home/eindhan/.local/lib/python3.5/site-packages/django/db/models/options.py", line 205, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/home/eindhan/.local/lib/python3.5/site-packages/django/db/__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/home/eindhan/.local/lib/python3.5/site-packages/django/db/utils.py", line 202, in __getitem__ backend = load_backend(db['ENGINE']) File "/home/eindhan/.local/lib/python3.5/site-packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "/usr/lib/python3.5/importlib/__init__.py", line … -
google oauth2client error no attibute sign
Trying to add google analytics report on my project in python. It shows error Exception Value: 'str' object has no attribute 'sign' I install PyOpenSSL but problem isnt solved. Using python 3.6, Django 2.0.3, oauth2client==4.1.2, pyOpenSSL==17.5.0 -
Serving static files during development without relying on django.contrib.staticfiles
I'm trying to keep my front and back ends completely separate. Front end is a template developed in node-land with (I hope) minimal or no context involvement, back-end is a set of TemplateViews and an API. I'm building my frontend to my frontend directory, so that's easy enough, I just set in settings.py: TEMPLATES = [ { "DIRS": ["frontend/"] ... I'm running into difficulties when these templates reference assets like: <link rel="assets/css/foobar.css" /> foobar.css is present at the relevant location, but the dev server doesn't know to look there. Obviously in production the proxy server will be serving these files directly, but can I get the django dev server to do that while I'm developing? I really want to avoid prefixing with {{ STATIC_URL }} and other template tags that couple the back end to the templates. -
Index not showing in Kibana 6.2
So I'm using Elasticsearch and Kibana to show specific user events that my Django App sends with elastic-py. I was using the 5.5 version before and it worked great, but for different reasons, I had to change the server itself and decided to use this opportunity to upgrade to ELK 6.x. So I set up a new fresh install of Elasticsearch and Kibana 6.2.2 in another server with the X-Pack also and did a few tweaks to my old code: Before . . . 'mappings': { 'example_local': { 'properties': { 'action': {'index': 'not_analyzed', 'type': 'string'}, 'date': {'index': 'not_analyzed', 'format': 'dd-MM-yyyy HH:mm:ss', 'type': 'date'}, 'user_type': {'index': 'not_analyzed', 'type': 'string'}, . . . After . . . 'mappings': { 'example_local': { 'properties': { 'action': {'type': 'text'}, 'date': {'format': 'dd-MM-yyyy HH:mm:ss', 'type': 'date'}, 'user_type': {'type': 'text'}, . . . After that, I added the user and password to my connection, one thing that in my old ELK couldn't do. host_port = '{}:{}'.format(settings.ELASTICSEARCH['host'], settings.ELASTICSEARCH['port']) Elasticsearch(host_port, http_auth=(settings.ELASTICSEARCH['username'],settings.ELASTICSEARCH['password'])) And at last, I created my index and went running to Kibana to see how my last 4 hours of struggle finally paid off. But in the Management -> Kibana -> Index Patterns there was only 1 index, … -
SQL database. I dropped a table, how can i now create it?
To drop table i used that commands : python manage.py dbshell .tables DROP TABLE table_what_i_drop; after i tried : python manage.py makemigrations and python manage.py migrate but table wasn't created. I deleted migrations folders from all apps and dbsqlite3 file and tried again makemigrations and migrate, but databases wasn't created. Now when i tried python manage.py dbshell .tables there is no tables for any of my app. I know that loosing tables is my fault, but how i can make all databases from the beginning ? -
how to add angular front end to django rest application?
I have a django rest app and I have my front-end designed with angularjs including homepage and all stuff in one folder I don't know how to connect my front end folder to my django app so that they work integratedly any suggestions? -
I have use the corsheaders config the CORS setting, why when `localhost:8080` access still get the error?
I have use the csrfheaders in my Django backend, but I use the frontend to access the API, I still get the bellow error: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:8080' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. my Django backend project's settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '8cyiv%(rkpv33s_(n8x_5&+6-9&s!ddc!0)98la3=9(y8=k$4u' DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'corsheaders', # the corsheaders 'rest_framework', 'rest_framework.authtoken', 'rest_framework_docs', 'rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth.registration', 'wx_numbers', 'users_management', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = ( 'XMLHttpRequest', 'X_FILENAME', 'accept-encoding', 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'localhost:8080' ) ROOT_URLCONF = 'wx_backup.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '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', ], }, … -
The view myapp.views.registration didn't return an HttpResponse object. It returned None instead
when i try to register with same username it must show error on html page but it show like "The view myapp.views.registration didn't return an HttpResponse object. It returned None instead." when i try to register with same username it must show error on html page but it show like "The view myapp.views.registration didn't return an HttpResponse object. It returned None instead." when i try to register with same username it must show error on html page but it show like "The view myapp.views.registration didn't return an HttpResponse object. It returned None instead. when i try to register with same username it must show error on html page but it show like "The view myapp.views.registration didn't return an HttpResponse object. It returned None instead. when i try to register with same username it must show error on html page but it show like "The view myapp.views.registration didn't return an HttpResponse object. It returned None instead. when i try to register with same username it must show error on html page but it show like "The view myapp.views.registration didn't return an HttpResponse object. It returned None instead." when i try to register with same username it must show error on html … -
How to set Collation in MySQL database with Django 2.* mysqlclient?
I need to set default Collation for MySQL tables with Django 2.*, im using mysqlclient, my settings are: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'charset': 'utf8mb4', }, } } 'charset': 'utf8mb4', This parameter seems don't work properly and tables in DB utf8. Although i want to manually set and tables Collation to utf8mb4_general_ci Will be appreciate for any clues. -
How can I use this for loop variable in django?
CODE: <form> <div class="form-group"> <label for="sel1">Select list (select one):</label> <select class="form-control" id="sel1" style="width: 96px"> {% for i in 150 %} <!-- here is what I ask for --> <option>{{ i + 1989 }}</option> {% endfor %} </select> </div> </form> I want to make year select form which is from 1900 to 2050. How can I use i variable in django template tag? -
django call view according to url version
Lets say I have a versioned url like: /movies/(?P<pk>[a-z]+)/(?P<version>v\d{1,2}\.\d{1,2})/?$, Movies.as_view() which calls the view Movies If the version is v1.2 I would like to call Movies_1_2 and if the version is v0.1 I would like to call Movies_0_1. I would like to know what is the best practice to do this. I am thinking of checking the version in Movies dispatch method and calling the version based view from there according to version. Is it good to do this or there is something else anyone is doing for versioning. I would be glad to know the best practice. P.S. I am not using DRF -
django pass extra parameters to foreignkey field
I have model like: class Profile(models.Model, DictMixin): user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name="profile") display_name = models.CharField(max_length=30) avatar = models.ForeignKey(MyMedia, models.CASCADE, related_name="avatar") class MyMedia(models.Model): media = models.FileField(upload_to="some_dynamic_folder") Here I am having a ForeignKey relation of MyMedia to avatar. When I upload the file I want it to save to specific folder that I pass as a parameter to ForeignKeyField or Manytomanyfield. Lets, say all the profile picture should be saved in profile_picture field and all the contents should be saved in content folder. Is it possible to do this ? Need some suggestins :) -
Modify LDAP user in a GUI (using Django)
So I am currently working on a webapp by using the Django-Framework. After a lot of research, I could not find a way for users, to type in their edits in the webapp and these will automatically change their attributes. This is how I did it ( # import class and constants from ldap3 import Server, Connection, ALL, MODIFY_REPLACE # define the server s = Server('servername', get_info=ALL) # define an unsecure LDAP server, requesting info on DSE and schema # define the connection c = Connection(s, user='user_dn', password='user_password') c.bind() # perform the Modify operation c.modify('cn=user1,ou=users,o=company', {'givenName': [(MODIFY_REPLACE, ['givenname-1-replaced'])], 'sn': [(MODIFY_REPLACE, ['sn-replaced'])]}) print(c.result) # close the connection c.unbind() In the example above, you need to set the user in the script and specifically say, way needs to be changed. Is it even possible with Django or do I need a dynamic script or whatever? If you have any idea, do not hesitate to post it. Thanks in advance. -
How to round up Django money
how do i round up django money? I can't find it in the doc. Thanks in advance! xxx = Money(amount=99.21, currency='SGD') xxx= round(xxx) -
POST vs GET method in Django's view function
My app's urls.py is: from django.urls import path from . import views app_name = 'javascript' urlpatterns = [ path('create_table', views.create_table, name='create_table') My views.py is: def create_table(request): if request.method == 'POST': row_data = "this is row data" context = {'row_data': row_data} return render(request, 'javascript/create_table.html') My create_table.html is: {% load static %} <form action="" method="post"> {% csrf_token %} <button id="create_table">Get data</button> </form> <div id="place_for_table"></div> <script type="text/javascript"> var row_data = "{{ row_data }}" </script> <script src="{% static 'javascript/scripts/create_table.js' %}"></script> And my create_table.js is: function create_table() { document.getElementById("place_for_table").innerHTML = row_data; } document.getElementById("create_table").onclick = function() { create_table() } What I want to achieve is: when the /create table URL is requested, only the button is displayed. When the button is pressed, row_data variable's value is displayed below the button. At this moment the data is displayed for a blink of an eye and then disappears. I guess I am not distinguishing between POST and GET methods correctly in the view function. Also I have based my logic on the assumption that URL is requested using GET method by default. However if I put a print(request.method) at the beginning of my view, it prints POST. Also, whenever I load the page for the first time or … -
Django RegexField field drops case insensitivity -- makes compiled object case sensitive
I need case insensitivity (lack of case sensitive). I compile an object as case insensitive, and immediately afterwards, it works as case insensitive. I can store it in the database, and at that moment, it still works as case insensitive. But when I come back later, case insensitivity is LOST -- the compiled object is CASE SENSITIVE. I'm using PostgreSQL version 10. Here is a shell session that illustrates: In [9]: t Out[9]: (re.compile(r'(Acoustat)', re.IGNORECASE|re.UNICODE), None, None) In [10]: findTitle, findExclude, findKeyWords = t In [11]: oTableRow.oRegExLook4Title= findTitle In [12]: oTableRow.save() In [13]: oTableRow.oRegExLook4Title Out[13]: re.compile(r'(Acoustat)', re.IGNORECASE|re.UNICODE) In [14]: findTitle.search( 'abc ACOUSTAT efg' ) Out[14]: <_sre.SRE_Match object; span=(4, 12), match='ACOUSTAT'> ... In [18]: exit (auctions) rick@conf-k16-2018:~/Devel/auctionbot$ python manage shell Python 3.5.2 (default, Nov 23 2017, 16:37:01) Type 'copyright', 'credits' or 'license' for more information IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help. In [1]: from brands.models import Brand In [2]: oBrand = Brand.objects.all().first() In [3]: oBrand Out[3]: <Brand: Acoustat> In [4]: oTableRow = oBrand In [5]: oTableRow.oRegExLook4Title Out[5]: re.compile(r'(Acoustat)', re.UNICODE) Line above Out[13] shows that the object has the IGNORECASE flag, and Out[14] shows it works as advertised. At bottom, Out[5] shows NO IGNORECASE flag. And yes … -
UnicodeEncodeError: 'charmap' codec can't encode character '\u2264'
I'm using python3.6 in windows7 and django 1.9 I got this error when i run my code. In my code i'm parsing xml data to write a html page. I got that some character is unable to encode properly thats why its throwing an error. \u2264 this is the character(less than or equal) which is the root cause of the error. My question is how to encode this properly in python3 Detailed Error Log: Traceback (most recent call last): File "C:\Dev\EXE\TEMP\cookie\crumbs\views.py", line 1520, in parser html_file.write(html_text) File "C:\Users\Cookie1\AppData\Local\Programs\Python\Python36-32\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u2264' in position 389078: character maps to -
TemplateDoesNotExist error in django polls aplication
I am making a polls application in django and I get the following error: TemplateDoesNotExist at /polls/ This is what my index function looks like this: def index(request): latest_questions = Question.objects.order_by('-pub_date')[0:5] context = {'latest_questions': latest_questions} return render(request, "polls/template.html", context) template.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% if latest_ques %} <ul> {% for question in latest_ques%} <li><a href = '/polls/{{question_id}}/'><b> {{question.ques_text}}</b></a></li> {% endfor %} </ul> {% endif %} </body> </html> Inside of my polls file I have a template file and inside of that I have a template folder inside of that I have another polls folder and inside of that I have template.html. I have tried using render_to_response instead of render, I also tried to add the path to DIRS in settings.py and I tried taking request out of the function. Thank you so much. -
Different migration file names for on external library using Django and docker-compose
I have a project which I added new external library recently. So I re-build my docker images to include this library by running docker-compose build and this is my DockerFile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN apt-get update && apt-get install -y \ rabbitmq-server \ gettext \ xmlsec1 # Chinese PYPI mirror RUN mkdir /root/.pip/ #COPY ./pip-china.conf /root/.pip/pip.conf RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ RUN DATABASE_URL=None python3 manage.py collectstatic --noinput RUN DATABASE_URL=None python3 manage.py compilemessages After I create my new docker image I run migrations with new field added on my model so it generates this migration file. # -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-03-16 02:46 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wagtailvideos', '0010_auto_20180316_0246'), ('pages', '0117_auto_20180315_0905'), ] operations = [ migrations.AddField( model_name='articlepage', name='header_video', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailvideos.Video'), ), ] so far everything is fine my local works completely perfect. But if build my my docker images on staging/production server it gives me migration file not found. ('wagtailvideos', '0010_auto_20180316_0246') So I have to run makemigrations manually on other servers which gives me different migration filenames … -
django pick from multiple databases for testing
I have multiple databases defined. This is for test profile, and I want to be able to specify which database to be picked for testing. eg: "python manage.py test -db=mysql" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'mysql': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mysql_test', } } I went through the django documentation, but i cant find a clear cut way of doing it. One way of getting around this is setting up environment variables, and define both databases as default. Then use the db based on the database type. please let me know if there is a much better way of doing this. thanks Amal