Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Foreign key not returning child instance using django-polymorphic
I just started using django-polymorphic and I'm having trouble returning the child instance of a parent model from a Foreign Key relationship. Here's an example: >>> poll = Poll.objects.create(asker=official, question='test question',background='background') >>> poll.asker <Official: Mayor Test Official> >>> poll.save() >>> poll = Poll.objects.get(question='test question') >>> poll.asker <Asker: Test Official> In this instance, the Official model is a child of Asker. All help is appreciated, thanks! -
Django: Not working the translation of strings
im study the Django and faced with a problem translating strings. This code is send keyboard for the Telegram bot. In the code you will see SQL request, since the bot was writeed on clear python. Im need translate the keyboard text on "ru" or "en" (default) depending on what text the user sent. def bot_message(request): def settinngs(chat_id, message): con = lite.connect('db.sqlite3') cur = con.cursor() sql = "SELECT City, Lang FROM Userprofile WHERE Id={} ".format(chat_id) cur.execute(sql) result = cur.fetchall()[0] keyboard = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True) button_change_city = types.KeyboardButton(text=_('Change name city')) button_subs = types.KeyboardButton(text=_('Subscriptions')) button_change_language = types.KeyboardButton(text=_('Change language')) backs_button = types.KeyboardButton(text=_('Back')) keyboard.add(button_change_city, button_subs, button_change_language, backs_button) bot.send_message(message.chat.id, '{}{}\n{}{}'.format(_('Your city: '), result[0].capitalize(), _('Language: '), result[1]), reply_markup=keyboard) I created translate in .po and compilemessages .mo file LANGUAGES = ( ('ru', 'Russian'), ('en', 'English'), ) USE_I18N = True LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) And set in MIDDLEWARE MIDDLEWARE = [ 'django.middleware.locale.LocaleMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] What am I doing wrong? -
Django ImportError Windows
So I created a virtualenv. I activated it (workon). Then I installed Django. py -3 -m django --version returns "No module named django." Then I try pip3 install django and it returns "Already satisfied." I created my project successfully using django-admin (meaning django IS installed?). Then I cd into the folder and run py -3 manage.py runserver and it says the following: "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?" -
Queryset distinct() with filter() and order_by() does not work
I am using the following models and forms to build two dropdown menus. The City menu is dependent upon the Country menu. Right now my code does the filtering and ordering correctly. However, distinct() is not working. I've played around with the ordering of the queries for a while and it still doesn't work. How can I fix this? models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Person(models.Model): country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name forms.py from django import forms from .models import Person, City class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('country', 'city') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.none() if 'country' in self.data: try: country_id = int(self.data.get('country')) self.fields['city'].queryset = City.objects.filter(country_id=\ country_id).order_by('city').distinct('city').\ exclude(city__isnull=True) except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['city'].queryset = self.instance.country.city_set.order_by('name') -
Execute linux command within Django views
I would like to execute a linux curl command through python. I went through multiple links but my problem is that it keeps saying file name too long. Is there a way to tackle this error? I use subprocess call to go about it. -
Django object retrieval not working
For some reason UserProfile.objects.all() isn't retrieving the models I have to serialize them as json. Any ideas? views.py def get_modelAPI(request): UserProfile_json = serializers.serialize("json", UserProfile.objects.all()) data = {"UserProfile_json": UserProfile_json} return JsonResponse(data) urls.py url(r'^details/json/$', views.get_modelAPI, name='json'), models.py class UserProfile(models.Model): fullName = models.CharField(max_length = 250) address = models.CharField(max_length = 250) gender = models.CharField(max_length = 250) dob = models.CharField(max_length = 250) homePhone = models.CharField(max_length = 250) personalPhone = models.CharField(max_length = 250) emergencyContact = models.CharField(max_length = 250) email = models.CharField(max_length = 250) ppsn = models.CharField(max_length = 250) maritalStatus = models.CharField(max_length = 250) employment = models.CharField(max_length = 250) personalPic = models.CharField(max_length = 1000) I am simply attempting to view this model in json format for now later to be parsed. Output -
Restrict access to Geoserver except for javascript
I have Django web application that request wms and wfs from geoserver using javascript(leaflet). When user click on leaflet map a request sent to web server(apache2.4) and apache will redirct the request to tomcat 8.5 using proxy. Everything is working perfect. I want to Restrict access to Geoserver except for javascript from https://app.mydomain.com Geoserver exsist in deffrent server and we use this url to access it geoserver.mydomain.com. I used HTTP_REFERER with apache: RewriteEngine on # Options +FollowSymlinks RewriteCond %{HTTP_REFERER} "app.mydynamo.com" [NC] RewriteRule .* - [F] Can you help me to Restrict access to Geoserver except for javascript from https://app.mydomain.com -
Why Django doesnt have Error Page Handler for 405 - Method Not Allowed?
When i read Django documentation i found only handlers for: 400, 403, 404, 500 errors. Why 405 error handler doesn't exists but decorators like require_POST() is in common use? The point is, what is proper way to create custom error page for Method Not Allowed error ? -
Django Serializer lookup value from id of another model
I'm using Vue as my frontend and Django DRF as my backend. I created 2 models - Snippet and age. I'm trying to return the value from the lookup table instead of the id: POST on Snippet List by passing in {title: 'x', code: 'y', age: 21} instead of passing the age id PUT on Snippet instance by passing in {age: 21} instead of passing the age id to update the record GET on Snippet List get return results with {other_fields, age: 21}. Is it possible to modify the serializer to do these? I'm using axios to call GET/POST/PUT on the REST endpoints. Snippet data as viewed in the API **Snippet List** { "id": 1, "title": "hello", "code": "print", "age": 2 }, { "id": 2, "title": "dsd", "code": "sds", "age": 1 } **Age List** { "id": 1, "year": "21", "snippets": [ 2 ] }, { "id": 2, "year": "30", "snippets": [ 1 ] } models.py class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() age = models.ForeignKey('age', related_name='snippets', on_delete=models.CASCADE, null=True) class age(models.Model): year = models.CharField(max_length=100) serializers.py class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = ('id', 'title', 'code', 'age') age = serializers.ReadOnlyField(source='age.year') class ageSerializer(serializers.ModelSerializer): snippets = … -
Need django website to work on a local windows network through WAMP
I’ve got a python and django app built and I am able to go to http://127.0.0.1:8000/pos/index/ and it works on computer1 within a virtual environment. Now I am trying to make it work on another computer (computer2) in the network. So I installed WAMP on computer1 and am trying to configure apache to host the django. Details: Computer1: has Windows10, WAMP 3.1.1 with Apache 2.4.27 and mySQL 5.7.19, python 3.6.4 with virtualenv==15.1.0 and within the virtual environment is Django==2.0.3, mod-wsgi==4.5.24+ap24vc14, mysqlclient==1.3.12, and pytz==2018.3 Computer2: windows10 Apache currently has the following configuration: httpd.conf file: Listen 0.0.0.0:80 Listen [::0]:80 Listen 0.0.0.0:8000 Listen [::0]:8000 LoadModule wsgi_module "c:/myproject/north/env/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd" WSGIScriptAlias / "C:/myproject/north/north_system/north_system/wsgi.py" WSGIPythonHome "c:/python36" WSGIPythonPath "C:/myproject/north/north_system/pos" Alias /static/ C:/myproject/north/north_system/pos/static/ <Directory "C:/myproject/north/north_system/pos/static"> Require all granted </Directory> <Directory "C:/myproject/north/north_system/pos"> <Files wsgi.py> Require all granted </Files> </Directory> httpd-vhosts.conf file: <VirtualHost *:80> ServerName localhost ServerAlias localhost DocumentRoot C:/myproject/north/north_system/pos <Directory "C:/myproject/north/north_system/pos/"> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Directory> </VirtualHost> <VirtualHost *:8000> ServerName north.local DocumentRoot C:/myproject/north/north_system/pos <Directory "C:/myproject/north/north_system/pos/"> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Directory> </VirtualHost> -
How do I only accept uploaded images with a 1:1 (square) aspect ratio and throw an error otherwise?
The admin is able to upload an image but I would like to restrict it to only being a square image. Here is my models.py file: class Author(models.Model): author_name = models.CharField(max_length=200) author_image = models.ImageField(upload_to=upload_location, null=True, blank=True,) author_bio = models.TextField() def __str__(self): return self.author_name -
NoReverseMatch at /posts/
Just quick info I'm a beginner in python and django. Here is an issue: I'm trying to create simple blog app with django, I've created all whats needed and I'm able to render one of my main pages however when I try to access posts page(to be able to view current posts) I receive the following error: Request Method: GET Request URL: http://localhost:8000/posts/ Django Version: 2.0.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'post' not found. 'post' is not a valid view function or pattern name. I'm not sure why I receive this error as I have posts view function written and accessible, here are my files: my_blog/urls.py """Defines URL patterns for my_blog.""" from django.conf.urls import url from . import views #needed app name app_name='my_blog' urlpatterns=[ #Homepage url(r'^$',views.home,name='home'), # Show all posts. url(r'^posts/$', views.posts, name='posts'), models.py from django.db import models # Create your models here. class BlogPost(models.Model): """Post that can be viewed""" title=models.CharField(max_length=200) text=models.TextField() date_added=models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" if len(self.text)<50: return self.text else: return self.text[:50] + "..." views.py from django.shortcuts import render from .models import BlogPost from django.http import HttpResponseRedirect # Create your views here. def home(request): """The home page for Learning Log""" return … -
Debugging is not supported for python 2.5 or earlier?
I keep getting this error in visual studios. There are currently no documentation that I can find that solves this error. Im using Pythong 3.7. Also, I get this same error when I try to debug a Django web application as well as a just regular python web application. I have also tested with Google Chrome, Internet Explorer, and Firefox, all of which give me the same error. The configuration is set up for 3.7 -
Django/Postgres: Returning error: duplicate key value violates unique constraint
I have had this issue occur several times with a project I've been working on, and though I used the "python manage.py sqlsequencereset " fix that I've found on this site, it works for a while, and then begins throwing the error again. The error I keep getting is pretty straightforward: IntegrityError at /projects/v/portola/planting-sites/new/ duplicate key value violates unique constraint "urbanforest_plantingsite_pkey" DETAIL: Key (id)=(194016) already exists. In my view I have: form = PlantingSiteForm(request.POST) if form.is_valid(): f = form.save(commit=False) if PlantingSite.objects.all().exists(): last_planting_site = PlantingSite.objects.all().order_by('-created_at')[0] f.id_planting_site = last_planting_site.id_planting_site f.id_planting_site += 1 else: f.id_planting_site = 100000 if request.POST.get('neighborhood_id'): f.neighborhood = Neighborhood.objects.filter(id_neighborhood=request.POST.get('neighborhood_id'))[0] if request.POST.get('district_id'): f.district = District.objects.filter(id_district=request.POST.get('district_id'))[0] if request.POST.get('basin_type_id'): f.basin_type = BasinType.objects.filter(id_basin_type=request.POST.get('basin_type_id'))[0] if request.POST.get('aspect_id'): f.aspect = Aspect.objects.filter(id_aspect=request.POST.get('aspect_id'))[0] if request.POST.get('orientation_id'): f.orientation = Orientation.objects.filter(id_orientation=request.POST.get('orientation_id'))[0] if request.POST.get('hardscape_damage_id'): f.hardscape_damage = HardscapeDamage.objects.filter(id_hardscape_damage=request.POST.get('hardscape_damage_id'))[0] if request.POST.get('status_id'): f.status = PlantingSiteStatus.objects.filter(id_planting_site_status=request.POST.get('status_id'))[0] else: f.status = PlantingSiteStatus.objects.filter(id_planting_site_status=9)[0] if f.zipcode: f.property_zipcode = f.zipcode f.created_by_fuf = True f.created_by = request.user f.save() I've done the sqlsequencereset a couple of times now, and then the error returns after a couple of weeks. I'm not importing any data, but my coworkers are using their phone in the field to create new objects, one at a time. Running sqlsequencereset gets me this code: SELECT setval(pg_get_serial_sequence('"urbanforest_plantingsite"','id'), coalesce(max("id"), 1), max("id") IS NOT … -
How to map JSON keys with non-alphanumeric characters in Django Rest Framework Serializer
I have some JSON keys that contain non-alphanumeric characters e.g. "my-key=" I need to map this key to a field my_key in my Django model. The traditional way to do this is to add a custom field to the ModelSerializer where you specify the source: class MyModelSerializer(serializers.ModelSerializer): my_key= = serializers.CharField(source='my_key') class Meta: model = MyModel fields = ('my-key=',) However this obviously doesn't work because: my_key= = serializers.CharField(source='my_key') is not valid python for declaring an attribute. How do I map my JSON key to the model field? -
Reusable admin form generator always checks last field
(This is all pseudocode and is not guaranteed to run.) I am trying to make a "django admin form generator function" that outputs a django form. The current use case is to write reusable code that disallows admins from leaving a field empty, without also marking these fields as non-nullable. So suppose there exists a model Foo, in which are some nullable fields: class Foo(Model): field1 = FloatField(null=True, blank=True, default=0.0) field2 = FloatField(null=True, blank=True, default=0.0) field3 = FloatField(null=True, blank=True, default=0.0) and corresponding FooAdmin and FooForm, such that these fields cannot be made None from the admin. class FooAdmin(ModelAdmin): class FooForm(ModelForm): class Meta(object): model = Foo fields = '__all__' def _ensure_no_blanks(self, field): value = self.cleaned_data.get(field) if value is None: raise forms.ValidationError(_('This field is required.')) return value # repeat methods for every field to check def clean_field1(self): return self._ensure_no_blanks('field1') def clean_field2(self): return self._ensure_no_blanks('field2') def clean_field3(self): return self._ensure_no_blanks('field3') form = FooForm As you can see, having to write clean_field1, clean_field2, and clean_field_n are repetitive and error-prone, so I write this helper function to generate model admins (pseudocode): def form_with_fields(model_class, required_fields): class CustomForm(ModelForm): class Meta(object): model = model_class fields = '__all__' def _ensure_no_blanks(self, field): print field value = self.cleaned_data.get(field) if value is None: raise … -
Idiomatic translation of Django models to different API schemas, perhaps with Django Rest Framework
Whats the best/idiomatic way to create and pass data between different API integrations in Django or with Django Rest Framework? I'm imaging something like a translation serializer that hooks between APIs that could be reused everywhere, and wanted to see what the best practices are. Say I have a standard Django Rest Framework based API and model that I expose via DRF that looks something like this : (But has alot more complexity and nested relationships class Person(models.Model): first_name = models.CharField(max_length=255, blank=True, null=True) middle_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) company = models.ForeignKey(Company, blank=True, null=True) class PersonSerializer(serializers.HyperlinkedModelSerializer): company = CompanySerializer(required=False) class Meta: model = Person fields = '__all__' class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer Response looks something like this { "first_name": "Oliver", "middle_name": null, "last_name": "Zhou", "company": { "name": "Company ABC", "url": "http://localhost:8000/companies/1234/" } } Now, depending on different actions in the application, I have a different API I need to integrate with and pass the Person data to, for example, an API with a schema with something like this : { "first_name": "Oliver", "middle_name": null, "last_name": "Zhou", "company": { "name": "Company ABC" } } What I've been doing is ugly and a spaghetti network … -
How to pass a user instance in a class-based view
I would like to pass the user instance of the current user in a class-based view and feed it in a second step to a model containing the column author. Related to that column I get the following integrity error: NOT NULL constraint failed... From the traceback I can see that my variable loggedUser which I had attributed self.request.user is a SimpleLazyObject. How can I pass my user instance? Thank you! View: class PlotGraphView(LoginRequiredMixin, TemplateView): redirect_field_name = '' login_url = '' template_name = "plot.html" def get_context_data(self, **kwargs): loggedUser = self.request.user context = super(PlotGraphView, self).get_context_data(**kwargs) context['logger'] = Logger.objects.get(name=logger_name) context['plot'] = plots.plotgraph(logger_name, loggedUser) Model: class Data(models.Model): logger = models.ForeignKey('Logger', on_delete=models.CASCADE) date = models.CharField(max_length=20) relative_humidity = models.FloatField(max_length=5) temperature = models.FloatField(max_length=5) author = models.ForeignKey(User, on_delete=models.PROTECT) -
Express multiple one-to-many and one-to-one relationship in Django
I am designing a delivery app. It has User, Address and Store models. I have following requirements: User can have multiple delivery address Store is located at only one location. An address cannot be linked with both user and store. Models looks as follow: class User(AbstractBaseUser): ... class Address(models.Model): ... class Store(models.Model): ... First requirement can be shown as: user = models.ForeignKey(User, on_delete=models.CASCADE) Second requirement can be shown as(in Address model as): store = models.OneToOneField(Store, on_delete=models.CASCADE) Also, second requirement can be shown as(in Store model as): address = models.OneToOneField(Address, on_delete=models.CASCADE) What is the best way to represent the third requirement. And how do I take care of serialization in this case? Thanks. -
view is correct, but django templates aren't rendering
I'm trying to figure my URLs out. My views seems to function in the console, but nothing renders in the templates after the search is completed. My search seems to function regardless of what i have in the user_list function as long as the user is defined with the following: user_list = Employee.objects.all() args = {'users':users} return render(request, 'user_list.html', args) My user_list falls under search and functions correctly with the filter. return render(request, 'user_list.html', args) It's after the filter that I try to render a view called results with: return render(request, 'results.html', args) The navigation is correct and it takes me to the URL and I can view the POST from the previous view in the console and it is correct. However, the template is empty when there is code in results.html In settings INSTALLED_APPS I have my app defined as: 'mysite.search', My application structure is laid out as the following: My project urls.py is setup as: from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django_filters.views import FilterView from mysite.search.filters import UserFilter urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'), url(r'^search/$', FilterView.as_view(filterset_class=UserFilter, template_name='search/user_list.html'), name='search'), url(r'^admin/', include(admin.site.urls)), ] My application urls.py is setup as: from django.conf.urls import … -
Recommendation for REST API using Python
I will be working on a project that consists of developing some REST API for a web app with MongoDB database using Python (Django framework to be particular ) I have the basic knowledge with Python , so in order to accelerate the learning phase and get things going much faster I need some advice on what should I learn first and if possible some suggestions Please help me :) thank you -
Django CMS on Raspberry Pi 3 Fails
Today I tried to install django CMS for a while on my Raspberry pi but it will not work. I Installed a fresh "RASPBIAN STRETCH LITE" then i entered following commands via an ssh connection: sudo wget https://bootstrap.pypa.io/get-pip.py sudo python get-pip.py sudo pip install Django==1.10 sudo pip install virtualenv cd /srv sudo mkdir django_cms cd django_cms sudo virtualenv env source env/bin/activate sudo pip install --upgrade pip sudo pip install djangocms-installer sudo mkdir django_site cd django_site/ sudo djangocms -f -p . web_site All this follows this guide And this error get thrown after executing the last command above: Creating the project Please wait while I install dependencies ERROR: cmd : [u'pip', u'install', u'-q', u'django-cms>=3.5,<3.6', u'djangocms-admin-style>=1.2,<1.3', u'django-treebeard>=4.0,<5.0', u'https://github.com/divio/djangocms-text-ckeditor/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-file/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-link/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-style/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-googlemap/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-snippet/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-picture/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-video/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-column/archive/master.zip?1520455195.14', u'easy_thumbnails', u'django-filer>=1.3', u'Django<2.0', u'pytz', u'django-classy-tags>=0.7', u'html5lib>=0.999999,<0.99999999', u'Pillow>=3.0', u'django-sekizai>=0.9', u'six'] :Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-FFzxtb/Pillow/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-CPB18v-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-FFzxtb/Pillow/ The installation has failed. ***************************************************************** Check documentation at https://djangocms-installer.readthedocs.io ***************************************************************** Traceback (most recent call last): File "/usr/local/bin/djangocms", line 11, in <module> sys.exit(execute()) File "/usr/local/lib/python2.7/dist-packages/djangocms_installer/main.py", line 33, in execute verbose=config_data.verbose File "/usr/local/lib/python2.7/dist-packages/djangocms_installer/install/__init__.py", line 95, in requirements output = subprocess.check_output(['pip'] + args, stderr=subprocess.STDOUT) File "/usr/lib/python2.7/subprocess.py", … -
Bad magic number when deploying on Heroku
I am trying to deploy a Django app to Heroku which uses a client to connect to the api of an invoice service. Everything works when running localy, but when deploying on Heroku I get a Bad magic number errror: error at /bexiopy/auth/ Bad magic number Request Method: GET Request URL: https://oust-test.herokuapp.com/bexiopy/auth/ Django Version: 2.0.3 Exception Type: error Exception Value: Bad magic number Exception Location: /app/.heroku/python/lib/python3.6/dbm/__init__.py in open, line 94 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.4 Python Path: ['/app', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages', '/app'] Server time: mer, 7 Mar 2018 19:53:24 +0000 Environment: Request Method: GET Request URL: https://oust-test.herokuapp.com/bexiopy/auth/ Django Version: 2.0.3 Python Version: 3.6.4 Installed Applications: ['jet.dashboard', 'jet', 'nested_admin', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django_celery_beat', 'django_celery_results', 'bexiopy.apps.BexiopyConfig', 'database'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py" in view 69. return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 89. return handler(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/bexiopy/views.py" in get 29. client = Client() File "/app/.heroku/python/lib/python3.6/site-packages/bexiopy/api.py" in __init__ 360. self.load_access_token_from_file() File "/app/.heroku/python/lib/python3.6/site-packages/bexiopy/api.py" in load_access_token_from_file 611. access_token … -
Django CMS -- Unregister Custom Menu?
Any idea how to unregister customized menus? The docs only show how to add them and I don't see any unregister attribute on menu_pool. I blindly tried menu_pool.clear(), but that didn't work. The prior menus remain discoverable with menu_pool.get_registered_menus() and in logging. -
Django model's clean() method not raising the expected ValidationErrors for individual fields
I have a Django model called CheckIn with (among others) two fields, min_weeks and max_weeks. I would like to build in validation such that min_weeks is always less than or equal to max_weeks. Following https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddo#django.db.models.Model.clean (in particular, the last example in which the ValidationError is passed a dictionary which maps fields to errors), I tried the following clean() method: from django.db import models from django.core.exceptions import ValidationError class CheckIn(models.Model): min_weeks = models.IntegerField(blank=True, null=True) max_weeks = models.IntegerField(blank=True, null=True) def clean(self): if self.min_weeks > self.max_weeks: raise ValidationError({ 'min_weeks': ValidationError("'min_weeks' should be smaller than 'max_weeks'", code='invalid'), 'max_weeks': ValidationError("'max_weeks' should be greater than 'min_weeks'", code='invalid')}) The model is used in a ModelForm: class CheckInForm(forms.ModelForm): class Meta: model = CheckIn fields = [ 'min_weeks', 'max_weeks', ] The fields are displayed manually in the template. Here is an excerpt: <div class="row"> <div class="input-field col s4"> <div class="js-hide-edit-field-text {% if not check_in_type or form.min_weeks.value %}hide{% endif %}"> {% if check_in_type and not form.min_weeks.value %} <span class='js-max-weeks inherited-field text'>{{ check_in_type.min_weeks }}</span> <a href='#' class='js-hide-edit-field-edit edit-icon right'><i class="material-icons">mode_edit</i></a> <label class="active"> Min Weeks </label> {% endif %} </div> <div class="js-hide-edit-field {% if check_in_type and not form.min_weeks.value %}hide{% endif %}"> {{ form.min_weeks|add_error_class:"invalid"|attr:"data-duration-weeks-mask" }} {{ form.min_weeks.errors }} {{ form.min_weeks|label_with_classes }} </div> </div> …