Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django LDAP E-Mail as Username
I am trying to login as a LDAP-user with an e-mail adress. I used the following code: settings.py AUTH_LDAP_SERVER_URI = "ldap://192.168.12.123" AUTH_LDAP_BIND_DN = "User" AUTH_LDAP_BIND_PASSWORD = "Password" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 1, ldap.OPT_REFERRALS: 0 } AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_ONELEVEL, "(uid=%(user)s)") AUTH_LDAP_GROUP_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_SUBTREE, "(objectClass=group)") AUTH_LDAP_GROUP_TYPE = NestedActiveDirectoryGroupType() AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } AUTH_LDAP_ALWAYS_UPDATE_USER = True LDAP_AUTH_OBJECT_CLASS = "inetOrgPerson" AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 AUTH_LDAP_E_USER_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_SUBTREE, ldap.SCOPE_ONELEVEL, "(mail=%(user)s)") AUTH_LDAP_E_USER_ATTR_MAP = AUTH_LDAP_USER_ATTR_MAP AUTH_LDAP_E_ALWAYS_UPDATE_USER = AUTH_LDAP_ALWAYS_UPDATE_USER AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', #'django.contrib.auth.backends.ModelBackend', 'accounts.backends.LDAPEmailBackend', ) backends.py from django_auth_ldap.backend import LDAPBackend, _LDAPUser class LDAPEmailBackend(LDAPBackend): settings_prefix = "AUTH_LDAP_E_" def get_or_create_user(self, email, ldap_user): model = self.get_user_model() username_field = getattr(model, 'USERNAME_FIELD', 'username') kwargs = { username_field + '__iexact': ldap_user.attrs['uid'][0], 'defaults': { username_field: ldap_user.attrs['uid'][0].lower(), 'email': email } } return model.objects.get_or_create(**kwargs) The console gives me this: search_s('DC=sbvg,DC=ch', 1, '(uid=%(user)s)') returned 0 objects: Authentication failed for ipa@sbvg.ch: failed to map the username to a DN. Caught LDAPError while authenticating ipa@sbvg.ch: SERVER_DOWN({'desc': u"Can't contact LDAP server"},) If you have any idea,,do not hesitate to post it. Any help is much appreciated. Thanks in advance. -
axios POST not working, but working in postman
In a Django rests framework + Reactjs virtual environment: I have an axios post call as follows: var data = JSON.stringify({diagnosis: diagnosis, frequency: frequency}); axios.post('/by/frequency/'+id, data, { headers: { 'Content-Type': 'application/json', } }); which gives me the following error: POST http://localhost:8000/by/frequency/86 403 (Forbidden) my json console.log output: {"diagnosis":"strep throat","frequency":3} However, when I do a post request in postman, it succeed as seen in the screenshot below: I've been working on this for several hours and can't figure out why. -
How to use django on two databases
I have a legacy Django project with a legacy database. That project uses django.contrib.auth.User as the user model. Now I need to write a new Django project and that app has to get access to the legacy database. The problem is that my new Django project also needs a User object. So how do I route django.contrib.auth.user models into the correct database? Another possible way to do this: is it possible to "bootstrap" a Django app for use inside another project? So if I have a legacy Django app with legacy settings.py, and I want to use the Django model functionality inside a new Django project with new settings.py (and it has its own apps), is there a way to do this? -
How do I convert a CSS file into JSON object?
I am trying to make a style editor using python Django. I need to convert a CSS file to JSON and vice-versa. Is there any Plugin or some thing in Django.? I also need to upload this file to git, How do I do that with Python? -
How to create Prefetch queryset based on parent queryset in django
Here is the scenario, a project model which contains multiple bids. `Class Project(models.Model): user = models.ForeignKey() Class Bid(models.Model): project = models.ForeignKey(Project, related_name='bids')` When we are querying projects, we want to prefetch bids for projects. Project.objects.filter(whatever condition).prefetch_related( Prefetch('bids', queryset=Bid.objects.all()) ) Here we only want to fetch the bids that belongs to the filtered projects, but not all the bids, how can we specify that? I am expecting something like queryset=Bid.objects.filter(project=project?)... Thanks. -
Type Error in get_wsgi_application() in Django 2.x with python3
I am migrating a web application from Django 1.9 to 2.0.2. The code is import os import sys path = '/mypath' if path not in sys.path: sys.path.append(path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Myapplication.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() However, if I try to execute this, I get an error: File "/home/.../wsgi.py", line 29, in <module> application = get_wsgi_application() File "/home/.../virtual/lagerthree/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "/home/.../lagerthree/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 140, in __init__ self.load_middleware() File "/home/.../virtual/lagerthree/lib/python3.5/site-packages/django/core/handlers/base.py", line 39, in load_middleware mw_instance = middleware(handler) TypeError: object() takes no parameters According to StackExchange and other sites, the cause of this error is the deprecation of certain things from 1.x to 2.x and the solution is the MiddlewareMixin which should be used like this: class FOOMiddleware(MiddlewareMixin): ... But I don't have any classes and also, the get_wsgi_application() function should still work, as far as I know. How should I solve this? -
Django Python : adding custom permissions to specific users
Models.py class Meta: permissions = ( ("can_add_data","can add a new data"), ) This is the custom permission I've created in Models.py and I've also created these users. Users in Django Admin ie., http://localhost:8000/admin click the hyperlink to view image How do I give permission to specific users so that I can use @permission_required('myapp.can_add_data') in views.py and also where do I write the snippet? ( in which file ) I'm a beginner at this so if there are any mistakes please let me know. -
I need advice on how to implement a checkbox in Django
I am trying to create a way that a student can enroll to a teacher's course. I added a boolean field to my StudentData model and from there I added a many-to-many field to my Course model. Each of my course page is a generated slug page and there all students are listed. I want that near each student a checkbox will be shown. And if teacher selects more students and presses Enroll button, only those students can view the course. Now, the template conditionals I can do them myself, but I am stuck on updating data the right way using the checkbox. This is the boilerplate: <ul> {% for student in students %} <br> <br> {{ student.name }} {{ student.surname }}<input type='checkbox' {% ifequal value 0 %}checked{% endifequal %}> 0 <br> <br> {% endfor %} </ul> <div class="row"> <div class="col-md-4"> <div class="pagination"> <span class="step-links"> {% if students.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ students.previous_page_number }}">previous</a> {% endif %} <span class="current"> {{ students.number }} </span> {% if students.has_next %} <a href="?page={{ students.next_page_number }}">next</a> <a href="?page={{ students.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> </div> <div class="col-md-4"> <button class="btn-success">Enroll</button> </div> </div> class StudentDataForm(forms.ModelForm): enrolled = forms.BooleanField() def __init__(self): if self.checked: self.fields['enrolled'].initial … -
Unable to find django in pycharm community IDE
I am getting started to django. I created a basic project using the below in windows powershell : django-admin startproject project1 This create the project structure, then I opened the project in pycharm , but looks like django module is not recognized. The below lines in urls.py are complaining - Unresolved reference django Also, when I run manage.py, below error is thrown : C:\Users\611834094\venv\Scripts\python.exe C:/Users/611834094/project1/manage.py runserver Traceback (most recent call last): File "C:/Users/611834094/project1/manage.py", line 8, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:/Users/611834094/project1/manage.py", line 14, in ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Process finished with exit code 1 -
Invalid embedded document instance provided to an EmbeddedDocumentField
I am currently working on an billing app and require to have orders inside a bill for that I have following two models Bill and orders class Bill(Document): billNo = IntField(unique=True, blank=False) table = ReferenceField('Table',reverse_delete_rule=1) orders = EmbeddedDocumentListField('Order', required = False) total = models.FloatField() discount = models.FloatField(blank=True) grandtotal = models.FloatField() payment_option = ReferenceField('PaymentOption',reverse_delete_rule=1) paid = models.BooleanField(default=False) class Order(EmbeddedDocument): food = ReferenceField(Food) quantity = IntField(required = True) complementory = BooleanField(default = False) and their serializers are as class OrderSerializer(EmbeddedDocumentSerializer): class Meta: model = Order fields = 'all' read_only_fields = ('id',) class BillSerializer(DocumentSerializer): orders = OrderSerializer(many = True) class Meta: model = Bill fields = '__all__' read_only_fields = ('id',) def create(self, validated_data): orders = validated_data.pop('orders') bill = Bill.objects.create(**validated_data) bill.orders = [] for order in orders: print(order) bill.orders.append(order) bill.save() return bill But whenever I pass a json like { "billNo": "4", "table":"5a93eb7f59951a3320a0b4d8", "payment_option":"5a93eddf59951a2fd4dbabe9", "orders":[{ "food":"5a93c2c759951a018c5e18b5", "quantity":"2", "complementory":"False" }] } the bill object is created but the order is not added and it gives the error mongoengine.errors.ValidationError: ValidationError (Bill:5a94f76859951a19d4688aeb) (Invalid embedded document instance provided to an EmbeddedDocumentField: ['orders']) I am using django rest framework and since it is mongodb i am using django rest framework mongo engine. What is the actual error and what … -
Unicode issue with pygithub and django
I'm trying to connect to this org githubtraining This is my code on views.py: def home(request): global org email=request.GET['email'] password=request.GET['password'] g = Github("user", "paswword") org = g.get_organization('githubtraining') list_rep= org.get_repos() context = { 'list_rep': list_rep, 'org':org } return render(request, 'Github/repo.html',context) But everytime I try to render the view I got this error: UnicodeEncodeError at /auth/ 'ascii' codec can't encode character '\u200b' in position 24: ordinal not in range(128) Is this because of something wrong in my call? Or maybe there's something else there? -
Django-haystack can not filter by datetime
Version: django-haystack (2.6.1) Django (1.11.4) I am trying to creating a search form, following by the tourial: After filtering the start date, the sqs become empty. What's wrong? class DateRangeSearchForm(SearchForm): start_date = forms.DateTimeField(required=False) end_date = forms.DateTimeField(required=False) def search(self): sqs = super(DateRangeSearchForm, self).search() print (sqs[0].object.publish_date) #2017-10-23 02:10:40.673000+00:00 print (self.cleaned_data['start_date']) #2017-10-17 00:00:00+08:00 print (self.cleaned_data['start_date']<sqs[0].object.publish_date) #true print (len(sqs)) #19 if not self.is_valid(): print("no query found/n") return self.no_query_found() if self.cleaned_data['start_date']: sqs = sqs.filter(publish_date__gte=self.cleaned_data['start_date']) print(len(sqs))#0 return sqs -
Django: Querying M2M table after object creation returns empty array
I'm using a Django signal to run a block of code after a model saves using post_save. The signal receiver in post_save gets an instance of the object sends it to a method for some processing before the instance is sent to a third party via network. One of my models, foo, has a many-to-many relation with another model, bar, and I need to add an array named bar_id that contains ids of each bar before I send foo to the third party. This configuration works when updating a foo instance however when I create a new instance of foo and I query for its relations (see the troublesome query in the Add Bar's ID to Foo and send it to third party section, the query is returning an empty query set even though the relation exists in the database. This exact same query returns a query set if I update the same model moments later. Any ideas of why this may be happening? Here's the code: Register the signal from django.apps import AppConfig class FooConfig(AppConfig): name = 'foo' def ready(self): import foo.signals Signal Code from django.dispatch import receiver from django.db.models.signals import post_save from django.conf import settings from django.db.models import … -
Django-Rest-Framework can not load the Styles and Scripts
I use Django-Rest-Framework, but get bellow error when I open the DRF APIs: The styles and Scripts can not load: GET http://localhost:8000/static/rest_framework/css/bootstrap.min.css net::ERR_ABORTED localhost/:20 GET http://localhost:8000/static/rest_framework/css/bootstrap-tweaks.css net::ERR_ABORTED localhost/:23 GET http://localhost:8000/static/rest_framework/css/prettify.css net::ERR_ABORTED localhost/:24 GET http://localhost:8000/static/rest_framework/css/default.css net::ERR_ABORTED (index):219 GET http://localhost:8000/static/rest_framework/js/ajax-form.js net::ERR_ABORTED (index):218 GET http://localhost:8000/static/rest_framework/js/jquery-1.12.4.min.js net::ERR_ABORTED (index):220 GET http://localhost:8000/static/rest_framework/js/csrf.js net::ERR_ABORTED (index):221 GET http://localhost:8000/static/rest_framework/js/bootstrap.min.js net::ERR_ABORTED (index):222 GET http://localhost:8000/static/rest_framework/js/prettify-min.js net::ERR_ABORTED (index):223 GET http://localhost:8000/static/rest_framework/js/default.js net::ERR_ABORTED (index):219 GET http://localhost:8000/static/rest_framework/js/ajax-form.js 404 (Not Found) (index):220 GET http://localhost:8000/static/rest_framework/js/csrf.js net::ERR_ABORTED (index):221 GET http://localhost:8000/static/rest_framework/js/bootstrap.min.js net::ERR_ABORTED (index):222 GET http://localhost:8000/static/rest_framework/js/prettify-min.js net::ERR_ABORTED (index):223 GET http://localhost:8000/static/rest_framework/js/default.js net::ERR_ABORTED and the Network: but the docs is ok, the Style and Script all work fine: -
django rest + axios put request error 403
I've read the duplicates and nothing seems to be working. I can do the put request directly from the form in the url but I can't seem to get the axios request working. I tried: CSRF with Django, React+Redux using Axios https://gist.github.com/paltman/490049a64fa4115a2cea My axios request: axios({ method: 'put', url: '/f/'+id, data: { item: item, }, }).then(function (response) { this.setState({needReceipt: true}); }) .catch(function (error) { console.log(error); }); In my settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), } in my webpack.config.dev.js: const axios = require('axios'); axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.xsrfCookieName = "csrftoken"; -
context and dictionaries python Django
So I have the following code: views.py: def topics(request): """Show all topics""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) return render(request, 'learning_logs/topic.html', context) I understand that I am querying the database and sorting the data by date then storing that data in the topics variable. My first question is, is the topics variable storing the data as a list? (assuming multiple entries). If so when I have the following code in my html file topics.html: <ul> {% for topic in topics %} <li>{{ topic }}</li> {% empty %} <li>No topics have been added yet.</li> {% endfor %} </ul> why do I need pass the data stored in topics into a context dictionary for topics.html to loop through and display the data? why not loop through the topics variable itself? I'm just confused on the use of "contexts" Thanks for the help in advance. -
Django Model.objects.all() returns unexpected empty QuerySet
I have some problem while trying to use a MySQL database with Django. The database contains a table named items. This database is imported from a development system to a production system. This database is the second database in addition to an existing SQLite databased used by other teams. There had been an error message about no such table, but I was able to solve it with this question. It assume that there are no migration errors. The MySQL database works fine in the development system (tested using python manage.py shell), but it doesn't work in the production system (tested the same way.) I tested the import with: $ python manage.py shell >> from project.models import Item >> Item.objects.all() <QuerySet []> I created the models.py file with: $ python manage.py inspectdb > models.py I verified that the database and the table items actually contains records. (Although some fields are stored as unicode text, if that makes any difference to the situation.) I am using Django 2.0.2 with Python 3.6.3. -
Error [mportError: No module named 'django'] while trying integrate apache2 with Django 1.11
I really need help with this as I've been trying to get the bottom of it for a while. I'm trying to get Django to use the apache2 server.However, when I try to log unto the apache page i get : Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at webmaster@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. Apache/2.4.7 (Ubuntu) Server at 127.0.1.1 Port 80 I have copied my version(s) output from the ubuntu 1404LTS Python 3.6.0+ (default, Feb 4 2017, 11:11:33) [GCC 4.9.4] on linux Type "help", "copyright", "credits" or "license" for more information. django.VERSION (1, 11, 4, 'final', 0) dpkg -l | grep wsgi ii libapache2-mod-wsgi-py3 3.4-4ubuntu2.1.14.04.2 amd64 Python 3 WSGI adapter module for Apache When I open the logs, I see the below: [Tue Feb 27 02:32:43.409875 2018] [:error] [pid 3211:tid 140311519147904] AssertionError: [Tue Feb 27 02:32:44.388403 2018] [:warn] [pid 3567:tid 139906080114560] mod_wsgi: Compiled for Python/3.4.0. [Tue Feb 27 02:32:44.388477 2018] [:warn] [pid 3567:tid 139906080114560] mod_wsgi: Runtime using … -
How to show a update form while keeping the original data in Django?
I'm using Django Forms to do some updating work.For example,I write a FilmForm to present a film information form: class FilmForm(forms.Form): name = forms.CharField() director = forms.CharField() release_year = forms.DateField() ......(many other infos) And I create and save a model instance using the form.Next time I want to modify only one info,like 'director',and update the model info using the FilmForm. def FilmUpdate(request,pk): if request.method == 'POST': ... else: form = FilmForm() return render(request,'film_update.html', {'form':form}) but when the form show up,the html inputs are all blank,and have to input all the original data again while the only item I want modify is just 'director'.So how to present the update form with the original data keeping? -
Django - Trying to delete 3rd party app, but getting "doesn't declare an explicit app_labels"
I am trying to uninstall a 3rd party app called Silk. I have removed all traces from Silk from my project, include settings.py, urls.py and anywhere else in the project. Now when I try to start the server, I get the following error - RuntimeError: Model class silk.models.Request doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.. I tried doing python manage.py migrate silk zero, but it says that silk is not a valid app (it's not in my project folder). Then I said screw it, and ran python manage.py reset_db to completely reset my database, but even after that, I still get the same error. How do I get rid of Silk? -
proper way to set up many to many relation where intermediary field has foreign keys django
I have a custom user field and a permissions field in a django app. The documentation says the following: https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.ManyToManyField that we are to use the manytomany through method. But I am confused on its proper implementation. Below I have my two models. I am asking for assistance in understanding how the through field applies in this case or at all. class STUser(AbstractBaseUser): email = models.EmailField(unique=True) name = models.CharField(max_length=255) companyname = models.CharField(max_length=200, blank=True, null=True) userphoto = models.CharField(max_length=200, blank=True, null=True) signupvaildatestring = models.CharField(max_length=200, blank=True, null=True) is_active = models.BooleanField(default=False) phone = models.CharField(max_length=10, null=True, blank=True) jobtitle = models.CharField(max_length=100, null=True, blank=True) # password field function is provided by AbstractBaseUser and the permissions table class Permissions(models.Model): venue = models.ForeignKey(Venue, on_delete=models.SET_NULL, blank=True, null=True) user = models.ForeignKey(STUser, on_delete=models.DO_NOTHING) isclient = models.BooleanField(default=False) isvenueviewer = models.BooleanField(default=False) isvenueeventplanner = models.BooleanField(default=False) isvenueadministrator = models.BooleanField(default=False) issuitsviewer = models.BooleanField(default=False) issuitsadministrator = models.BooleanField(default=False) issuitssuperuser = models.BooleanField(default=False) now I am supposed to use the through fields on this? The Example the docs uses its below does it differ in a way from my implementation where I do not need to use the through field? from django.db import models class Person(models.Model): name = models.CharField(max_length=50) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField( Person, through='Membership', through_fields=('group', 'person'), … -
psycopg2.OperationalError: FATAL: password authentication failed for user "<my UNIX user>"
I am a fairly new to web developement. First I deployed a static website on my vps (Ubuntu 16.04) without problem and then I tried to add a blog app to it. It works well locally with PostgreSQL but I can't make it work on my server. It seems like it tries to connect to Postgres with my Unix user. Why would my server try to do that? I did create a database and a owner via the postgres user, matching the login information in settings.py, I was expecting psycopg2 to try to connect to the database using these login informations: Settings.py + python-decouple: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config ('NAME'), 'USER': config ('USER'), 'PASSWORD': config ('PASSWORD'), 'HOST': 'localhost', 'PORT': '', } } This is the error message I get each time I try to ./manage.py migrate 'myportfolio' is my Unix user name, the database username is different: Traceback (most recent call last): File "/home/myportfolio/lib/python3.5/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/home/myportfolio/lib/python3.5/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/home/myportfolio/lib/python3.5/site-packages/django/db/backends/postgresql/base.py", line 168, in get_new_connection connection = Database.connect(**conn_params) File "/home/myportfolio/lib/python3.5/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "myportfolio" … -
Django/Python Regex Error -- No Reverse Match
Back with what I suspect is one more regex error.. have tried a ton of different iterations, but nothing is working. Here are urls in my 'deals' folder: url(r'^$', DealListView.as_view(), name='deals'), url(r'^(?P<slug>[\w-]+)/', deal_by_detail, name='deal_detail'), url(r'^category/(?P<category>\w+)\/$', deals_by_category, name='category'), url(r'^(?P<pk>[0-9]+)/like', like, name='like'), The error is happening if i visit an individual deal page like this: http://localhost:8000/deals/free-bike-dicks-sporting-goods/ And here is the 'deal_by_detail' view: def deal_by_detail(request, slug): deal_detail = Deal.objects.get(slug=slug) return render(request, 'deals/deal_detail.html', {'deal_detail': deal_detail}) Here is my error and traceback NoReverseMatch at /deals/free-bike-dicks-sporting-goods/ Reverse for 'deal_detail' with arguments '()' and keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['deals/(?P<slug>[\\w-]+)/'] Request Method: GET Request URL: http://localhost:8000/deals/free-bike-dicks-sporting-goods/ Traceback: File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\urlresolvers.py" in reverse 586. extra, resolver = resolver.namespace_dict[ns] During handling of the above exception ('dealmazing.deals'), another exception occurred: File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\defaulttags.py" in render 507. current_app=current_app) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\urlresolvers.py" in reverse 596. key) During handling of the above exception ('dealmazing.deals' is not a registered namespace), another exception occurred: File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\crstu\Desktop\JSPROJ\dealmazing\deals\views.py" in deal_by_detail 23. return render(request, 'deals/deal_detail.html', {'deal_detail': deal_detail}) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\shortcuts.py" in render 67. template_name, context, request=request, using=using) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\loader.py" in render_to_string 97. return template.render(context, request) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\backends\django.py" in render … -
django sqlite3 URIs not supported
Odd situation. Django 2.x in its features for sqlite3 drive turns on uri support. It seems to only be a problem seen in python 3. On machines with older version of sqlite, in my case 3.6.20, the problem of URIs not supported does not arise with exactly the same virtualenv and codebase. On machine with sqtlite3 --version showing 3.7.17 it does arise. The funny thing is the feature is only supported in sqlite3 after 3.7.7 or so from what I read. So apparently django sees it is supported but it really isn't at the level of the internal sqlite3 drivers in python? (guessing) In [3]: sqlite3.version_info Out[3]: (2, 6, 0) In [4]: sqlite3.sqlite_version_info Out[4]: (3, 7, 17) On the machine it does not work on and as expected last line is (3, 6, 20) on machine it does work on. Now I don't have full control of the machine. I thought just to pull over the lower version but no luck there. Internal libraries determine actual version even when you run sqlite3 on the command line. I can hack the relevant part of the django driver setup but that is less than pleasing even though I do have control of … -
Wagtail blog example gallery image not loading
I'm following the blog tutorial on the Getting Started page and I've added the BlogPageGalleryImage. I've done all the migrations and I'm able to add images to a post I created earlier as an admin. The templates and models have all been modified as required. However when I view the page, the image doesn't get displayed. Below are the relevant code excerpts. Model.py class BlogIndexPage(Page): intro = RichTextField(blank=True) def get_context(self, request): # Update context to include only published posts, ordered by # reverse-chron context = super(BlogIndexPage, self).get_context(request) blogpages = self.get_children().live().order_by('-first_published_at') context['blogpages'] = blogpages return context content_panels = Page.content_panels + [ FieldPanel('intro', classname="full") ] class BlogPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('body'), ] content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('intro'), FieldPanel('body', classname="full"), InlinePanel('gallery_images', label="Gallery images"), ] class BlogPageGalleryImage(Orderable): page = ParentalKey(BlogPage, related_name='gallery_images') image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.CASCADE, related_name='+' ) caption = models.CharField(blank=True, max_length=250) panels = [ ImageChooserPanel('image'), FieldPanel('caption'), ] blog_page.html {% extends "base.html" %} {% load wagtailcore_tags wagtailimages_tags %} {% block body_class %}template-blogpage{% endblock %} {% block content %} <h1>{{ page.title }}</h1> <p class="meta" >{{ page.date }}</p> <div class="intro" >{{ page.intro }}</div> {{ page.body|richtext }} {% for item in page.gellery_images.all …