Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Authenticate using email and uuid
I have a custom authentication model that contains a uuid field. In case the user forgets his password, a link will be sent to his email that will allow him to reset the password. The link contains the uuid. The form contains only password1 and password2 fields. Is there any way to change the password when user is not logged in ?(auth.authenticate cannot be used as the user does not remember his/her password.) If not, I want to authenticate using his email and uuid itself. How can it be done? -
Django AJAX POST login CSRF error in IE, EDGE, etc
I'm using Django 1.10. I want to log in via Jquery AJAX, but CSRF is set on. In order to pass the CSRF check, I have the following code. /* CSRF-config Start */ $.ajaxSetup({ beforeSend: function(xhr, settings) { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { // Only send the token to relative URLs i.e. locally. xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); $(document).ajaxSend(function( event, xhr, settings ) { if (settings.type == 'POST' || settings.type == 'PUT' || settings.type == 'DELETE') { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); … -
Images on first load don't show on canvas
I want to pass a list of images and draw them each one for canvas. My view.py: def myview(request): ... lista=Myobject.objects.filter(tipo=mytipo) numero_oggetti = range(len(lista)) lista_formattata=[] for elem in lista: lista_formattata.append('/media/'+str(elem.myfield)) context_dict['lista']=lista_formattata context_dict['numero_oggetti']=numero_oggetti return render(request, 'mytemplate.html', context_dict) My template.html: <script> <!-- window.onpageshow = function() { myfunction({{lista|safe}}); }; --> </script> {% for c in numero_oggetti %} <canvas id='componenti_canvas{{ c }}' width='60' height='75' style="border:1px solid #000000;"> Your browser does not support the HTML5 canvas tag. </canvas> {% endfor %} My script.js: function myfunction(lista) { lista=lista for (i=0; i<lista.length; i++) { var canvas = document.getElementById('componenti_canvas'+i); var ctx = canvas.getContext("2d"); var base = new Image(); base.src = lista[i]; ctx.scale(0.5,0.5); ctx.drawImage(base, 0, 0); }; }; This code works but sometimes the images show, sometimes don't (all of them or no one). When I load the page they don't show, when I re-load the page they show up. If I wait some minutes and re-load they don't show again. I'm using firefox and in the console log when say GET image_name.png HTTP/1.0 200 they don't show (sometimes they are in cache, sometimes not... it don't make difference), when it don't say nothing they show. I tried: -setTimeout -call the list with an ajax request with cache: false, … -
how to show date name table in django admin
class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() class Meta: db_table = 'book' I want to date table name. ex) book_201601, book_201602, book_201603, ........... I shoud table backup. I am able to view the different tables in view.py. Table name in the same column at I want to show the admin page. How to show date table name in admin page? -
Is using ISO-8601 date strings to compare against a DateField in Django's ORM officially supported and portable?
It seems that with Django's ORM I can consistently use an ISO-8601 date string instead of a datetime.date when querying against a model's DateField. For example, if I have a model like: from django.db import models class Sitting(models.Model): start_date = models.DateField() Then in my experience queries like the following work fine: Sitting.objects.filter(start_date='2015-12-25') Sitting.objects.filter(start_date__gte='2016-01-01') ... as well as: Sitting.objects.filter(start_date=datetime.date(2015, 12, 25)) Sitting.objects.filter(start_date__gte=datetime.date(2016, 1, 1)) My questions are: Is this officially supported, or might there be some underlying database for which using ISO-8601 strings doesn't work? I might well be missing something obvious, I couldn't find this documented anywhere - is there somewhere in the Django documentation that describes how values used in queries against DateField fields are used? -
Django & Postgresql: Override locale for sorting?
I have a simple Django app with a Postgresql database. The database is configured with nn_NO.UTF-8 locale. mything=>\l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------+----------+----------+-------------+-------------+----------------------- mything | postgres | UTF8 | nn_NO.UTF-8 | nn_NO.UTF-8 | =Tc/postgres + | | | | | postgres=CTc/postgres+ | | | | | me=CTc/postgres Let's say there's a table MyTable. I want MyTable.objects.order_by('name') to sort according to en_US rules, not nn_NO. Is it possible to override the sorting locale from Python/Django, or do I have to recreate the entire database? settings.py contains LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True -
Changing class of HTML element according to current file
I'm using Django and HTML files and I'm trying to change the class of one element depending on the current file. So, I have this base.html file, which is some kind of "super-class" file, which most of my other .html extends, thanks to Django, using {% extends 'base.html' %} Among other things, in that file, I have a navigation bar on top, which all files must have. This navigation bar has various elements, one of them being the current active element. For example, in the "foo.html" page, I'd like the navigation bar element holding to 'foo' tab to be underlined in red. I have a .css class for this, I just type class="active" and I'm good to go. But I'm in base.html. I can't. If I do, it's obviously active for every single child. Is there a solution for this or am I SOL? To be clear, I want foo.html to somehow tell base.html that "this div" should be active, while other files will tell base.html differently. Also, I would like some kind of clean solution, this is a long lasting project and I'd rather not start with any hacks. I know I could duplicate the navigation bar in all … -
Django send email in parts to avoid overhead
I have a non-profitable website that I need to handle newsletter emails to probably thousand people (lets be realistic and give an upper bound of at most 2000 - 2500 registered users). I have implemented email this way: @login_required def SendEmail(request): receivers = [] users = Users.objects.all() receivers.append(user.Email for user in users) emailTypeSelected = request.POST.get('email_type', -1) email_factory = EmailFactory() emailManager = email_factory.create_email(emailTypeSelected) emailManager.prepare("Some Title") emailManager.send_email_to(receivers) return render(request, 'new_user_email.html') And here is the "abstract" class. class Email(object): title = "" plain_message = "" html_message = "" def send_email_to(self, receivers): send_mail( self.title, self.plain_message, SENDER, receivers, html_message=self.html_message ) I have tested this code and it takes a while to send 1 email to 1 user. My concern is that for thousand emails will put a big overhead to the server. I was thinking to do the following: Break the users into group of 100 and send email to those users every 30 minutes. But I am not sure how this can be implemented. Seems that I will need to implement a sort of threads that will be triggered independently and handle the email for me. Is there any design pattern that you are aware on how to solve this problem? Now I know … -
Why does Django not update my models?
I'm trying to update my SQLite3 database with ./manage.py shell like so: >>> objs = Model.objects.all() >>> for obj in objs: ... obj.set_current_language('ru') ... obj.full = obj.full.replace("foo", "bar") ... obj.save() ... print obj.full I get some string with bar on output, but it doesn't seem my database was actually updated, because on the website it is still some string with foo. Why so? -
Django admin ManyToManyField add button and list display
Let's say I have models: from filer.fields.image import FilerImageField() class Image(models.Model): name = models.CharField(max_length=128) image = FilerImageField() class City(models.Model): name = models.CharField(max_length=128) images = models.ManyToManyField(Image, blank=True) admin.py: class ImageAdmin(admin.ModelAdmin): def thumb(self, obj): return '<img src=%s />' %obj.image.icons['64'] thumb.short_description = 'Preview' thumb.allow_tags = True list_display = ('image', 'name', 'thumb', ) class CityAdmin(models.ModelAdmin): filter_horizontal = ('images', ) admin.site.register(Image, ImageAdmin) admin.site.register(City, CityAdmin) Questions: 1. How to add "+" button in CityAdmin above m2m widget? Currently what i have: 2. Is it possible in CityAdmin m2m widget have some list display where I can see image thumbnail? Ideally like in ImageAdmin: What I have tried: In Image model __unicode__ function return '<img src=%s />' %self.image.icons['64'], but then in admin it just displays raw text. -
How to make Django button appear with javascript?
This is my code: {% extends "global/Base.html" %} {% load otree_tags %} {% block title %}Chart{% endblock title %} {% block content %} {% next_button %} {% endblock %} {% block scripts %} <script> //scripts </script> {% endblock %} I would like to make {% next_button %} not visible at first, then appear with javascript. I am currently trying to write an oTree app. The page in concern inherits from a Base.html (also in Django), which in turns inherits from otree/FormPage.html (link: https://github.com/oTree-org/otree-core/blob/master/otree/templates/otree/FormPage.html). FormPage.html in turns inherits from BaseParticipant.html (link: https://github.com/oTree-org/otree-core/blob/master/otree/templates/otree/BaseParticipant.html). Code for Base.html: {% extends "otree/FormPage.html" %} {% load staticfiles otree_tags %} {% block global_styles %} {% endblock %} {% block global_scripts %} {% endblock %} -
ImportError: no module named gravatar
I use Django1.10, when I process python manage.py migrate, I got an ImportError: no module named gravatar. Before that, I have installed python2.7 and run in virtual enviroment, as well as django_gravatar. what's the problem?the detail of command line Error -
Django rest framework CRUD API for model with foriegn key elements
Okay so here I am with another problem I'm facing with Django. This time it's the REST framework. I have a Model with Foreign Key dependencies in my project. I had to retrieve the foreign key field as an object, not just an ID field and was successful in that using Serializer Relations. So my Serializer.py looks like: class EventSerializer(serializers.ModelSerializer): owner = EventUserSerializer(read_only=False) severity = EventSeveritySerializer(read_only=False) type = EventTypeSerializer(read_only=False) cause = EventCauseSerializer(read_only=False) subcause = EventSubcauseSerializer(read_only=False) impact = EventImpactSerializer(read_only=False) point_location = PointLocationSerializer(read_only=False) class Meta: model = models.Event fields = ('id', 'description', 'owner', 'status', 'severity', 'type', 'cause', 'subcause', 'impact', 'is_public', 'occurrence_time', 'reporting_agency', 'estimated_duration', 'confirmed_timestamp', 'rejected_timestamp', 'closed_timestamp', 'point_location', ) Making a GET request, I get the result I wanted: { "meta": { "count": 1, "previous": null, "next": null }, "results": [ { "id": 8, "description": "test event 1", "owner": { "user": { "id": 1, "username": "venus", "email": "venus.saini@ibigroup.com" } }, "status": "confirmed", "severity": { "id": 2, "created": "2016-08-24T07:27:24.722000Z", "modified": "2016-08-24T07:27:24.723000Z", "name": "Severe", "is_enabled": true, "sortorder": 1 }, "type": { "id": 2, "created": "2016-08-24T07:27:45.203000Z", "modified": "2016-08-24T07:27:45.204000Z", "name": "Accident", "event_category": "unplanned", "sortorder": 2 }, "cause": { "id": 2, "created": "2016-08-24T07:28:16.088000Z", "modified": "2016-08-24T07:28:16.092000Z", "name": "Whether Conditions", "sortorder": 3, "event_type": 2 }, "subcause": { "id": 2, "created": … -
JWT Signature Validation Failed after deploying new backend version to server
I got a django backend hosted on a debian server backed by a couchbase database. After deploying a new version of the backend with some changes I get a JWT Decode Error with Signature Validation Failed for every token, that worked before the deploy. I logged the encoded payload and the resulting token. Then I manually tried to encode the payload and decode it in ipython which worked fine: payload = {u'userID': u'U-14109e71b853472ea2b118054454ac0f', 'exp': 1473313003} In [55]: jwt.encode(payload, signing, ALGO_ES256) Out[55]: 'eyJhbGciOiJFUzI1NiIsInR5cCI6IkpVCJ9.eyJ1c2VySUQiOiJVLTE0MTA5ZTcxYjg1MzQ3MmVhMmIxMTgwNTQ0NTRhYzBmIiwiZXhwIjoxNDczMzEzMDAzfQ.MEUCIQCJyk23BK6vk8F3ptNyMJlLZP7dvxhyqA9mqxETG759zQIgKjpkXEXJD925aRLYta5_chagvA-6VoS6loEjGT0QqZI' In [56]: token = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpVCJ9.eyJ1c2VySUQiOiJVLTE0MTA5ZTcxYjg1MzQ3MmVhMmIxMTgwNTQ0NTRhYzBmIiwiZXhwIjoxNDczMzEzMDAzfQ.MEUCIQCJyk23BK6vk8F3ptNyMJlLZP7dvxhyqA9mqxETG759zQIgKjpkXEXJD925aRLYta5_chagvA-6VoS6loEjGT0QqZI" In [57]: jwt.decode(token, secret, 'ES256') Out[57]: {u'exp': 1473313003, u'userID': u'U-14109e71b853472ea2b118054454ac0f'} In the backend I do it like this: Creation of the token: def create_token_for_user(self, user_id): payload = { m.USER_ID: user_id, self.EXPIRES_KEY: int(self._generate_expires_datetime(self.EXPIRATION_DELTA).strftime("%s")) } logger.debug(payload) token_str = jwt.encode(payload, SIGNING_SECRET, ALGO_ES256) logger.debug(token_str) exp = int(self.EXPIRATION_DELTA.total_seconds()) # save session in database cb = self.get_cb_bucket() session_obj = { m.TYPE: self.type, m.TOKEN: token_str, m.USER_ID: user_id, m.EXPIRES: exp } key = self._generate_key_from_token_str(token_str) cb.set(key, session_obj, ttl=exp) logger.debug("LoginTokenDAO::createTokenForUser Success ID: %s" % key) return token_str, payload[self.EXPIRES_KEY] Decoding in the token authentication: def authenticate(self, request): auth_prefix, token_str = self._extract_auth_information(request) if auth_prefix not in self.AUTH_PREFIXES: return None try: token_payload = jwt.decode(token_str, VERIFYING_SECRET, ALGO_ES256) if not self._is_valid_payload_structure(token_payload, expected_fields=self.TOKEN_FIELDS): logger.info("invalid payload structure for '%s' auth: … -
django authorization without using request.user.is_authenticated()
I am working on django website and I am using django Auth for user authentication and for authorization of user i am using request.user.is_authenticated() code in django view but using this i have to write this code in each and every view, because in my site there is only homepage, registration page and login page which can be accessed without login. So in each and every view i have to right this code. def dashboard(request): if request.user.is_authenticated(): return render(request, 'home/dashboard.py') else: return HttpResponse('User is not logged In') That's why I want to ask is there any way to write code only once for all views those can not be accessed without login as we do in CakePHP using authcomponent. -
Django Related to image fetch error from media folder
File "C:\Python34\lib\site-packages\django-1.10-py3.4.egg\django\utils\deprecation.py", line 126, in call response = self.process_response(request, response) File "C:\Python34\lib\site-packages\django-1.10-py3.4.egg\django\middleware\clickjacking.py", line 32, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'function' object has no attribute 'get' [25/Aug/2016 12:51:47] "GET /media/python_SQyGoaQ.png HTTP/1.1" 500 56085 Internal Server Error: /favicon.ico Traceback (most recent call last): File "C:\Python34\lib\site-packages\django-1.10-py3.4.egg\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Python34\lib\site-packages\django-1.10-py3.4.egg\django\utils\deprecation.py", line 126, in call response = self.process_response(request, response) File "C:\Python34\lib\site-packages\django-1.10-py3.4.egg\django\middleware\clickjacking.py", line 32, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'function' object has no attribute 'get' [25/Aug/2016 12:51:47] "GET /favicon.ico HTTP/1.1" 500 55930 Internal Server Error: /favicon.ico Traceback (most recent call last): File "C:\Python34\lib\site-packages\django-1.10-py3.4.egg\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Python34\lib\site-packages\django-1.10-py3.4.egg\django\utils\deprecation.py", line 126, in call response = self.process_response(request, response) File "C:\Python34\lib\site-packages\django-1.10-py3.4.egg\django\middleware\clickjacking.py", line 32, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'function' object has no attribute 'get' [25/Aug/2016 12:51:50] "GET /favicon.ico HTTP/1.1" 500 55928 -
Oauth Authentication For Own Service Access
I am working with an android application where i have to implement oauth authentication to identify my user within the app and then to access my services which are deployed on azure server. Is there any third party for oauth authentication framework. I need to implement facebook, g+ login as well within the application. I have gone through the django oauth, but didn't find the appropriate solution. -
Issue storing media to S3 using cookie-cutter-django
I'm not able to save ImageField in my models to s3. I am able to save my static files to s3 without any issue. I am the most recent version of cookie cutter django. I have deployed to heroku and store my environment variables there, I've double check my AWS settings there and can see the static files in my s3 bucket. production.py from __future__ import absolute_import, unicode_literals from boto.s3.connection import OrdinaryCallingFormat from django.utils import six from .common import * # noqa # SECRET CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key # Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ SECRET_KEY = env('DJANGO_SECRET_KEY') # This ensures that Django will be able to detect a secure connection # properly on Heroku. SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Use Whitenoise to serve static files # See: https://whitenoise.readthedocs.io/ WHITENOISE_MIDDLEWARE = ('whitenoise.middleware.WhiteNoiseMiddleware', ) MIDDLEWARE_CLASSES = WHITENOISE_MIDDLEWARE + MIDDLEWARE_CLASSES # SECURITY CONFIGURATION # ------------------------------------------------------------------------------ # See https://docs.djangoproject.com/en/1.9/ref/middleware/#module-django.middleware.security # and https://docs.djangoproject.com/ja/1.9/howto/deployment/checklist/#run-manage-py-check-deploy # set this to 60 seconds and then to 518400 when you can prove it works SECURE_HSTS_SECONDS = 60 SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool( 'DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS', default=True) SECURE_CONTENT_TYPE_NOSNIFF = env.bool( 'DJANGO_SECURE_CONTENT_TYPE_NOSNIFF', default=True) SECURE_BROWSER_XSS_FILTER = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True SECURE_SSL_REDIRECT = env.bool('DJANGO_SECURE_SSL_REDIRECT', default=True) CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = … -
Authentication and authorize, djangorestframework
I have a problem with django rest framework token-based authentication. I can create user, but his password not hash, then I wrote implementation of method create in my serializer. This didn't worked. Only root can receive token and his password is hashed. Even user receive a Token. Code here: https://github.com/XxXAsmoXxX/DjangoBlogAuthorization and authentication in folder restapi, folder with settings tasks -
Django exception : django.core.exceptions.ImproperlyConfigured:
When i run the same code in django shell it works fine for me. but when I fire up the Python interpreter (Python 2) to check some things, I get the an error when I try importing - from django.contrib.auth.models import User import smtplib import sys import dateutil.relativedelta from django.conf import settings from django.contrib.auth.models import User from opaque_keys.edx.keys import CourseKey from courseware.models import StudentModule from datetime import datetime def PCSurvey_email(): for student in StudentModule.objects.filter(module_type="PCSurvey"): two_months_date = datetime.now().date() - dateutil.relativedelta.relativedelta(months=2) created = student.created.date() if created == two_months_date : user_id = student.student_id user_email = User.objects.get(id = user_id).email FROM = "user@example.com" TO = [user_email] # must be a list SUBJECT = "Hello!" TEXT = "This message was sent with Python's smtplib." # Prepare actual message message = """\ From: %s To: %s Subject: %s %s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) # Send the mail server = smtplib.SMTP('outlook.net') server.sendmail(FROM, TO, message) server.quit() #deleting the module smod = StudentModule.objects.get(module_type="PCSurvey", course_id = student.course_id, student_id= student.student_id) smod.delete() The error that I get is Traceback (most recent call last): File "/edx/app/edxapp/edx-platform/lms/djangoapps/courseware/PCSurvey_email.py", line 8, in <module> from django.contrib.auth.models import User File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/base_user.py", line 52, in <module> … -
Django: Redirecting to another url based on user input in form
I am trying to achieve something really simple and having no luck after reviewing the Django forms documentation as well as the section in the Django Tutorial on Forms (Part 4), and several SO threads. I have a home page which has a form in which the user should be able to enter the name of some basketball player. When they hit submit it should redirect to my other page, the player_stats page, which will show some information about that player. I would ideally also like to have this same form available on the player_stats page itself so that the user can go from player to player without having to go back to the home page in between. forms.py from django import forms class NameForm(forms.Form): name = forms.CharField(label='Name', max_length=100) index.html <div> HOME PAGE </div> <form action="{% url 'player_stats' name %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Go"/> </form> views.py def index(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in … -
Django upload Photo via Httpie
I'm using DRF 2.3.13 , I want to upload photos by typing from terminal, so I use Httpie. But I got MultiValueDict: {} , empty. Am I missing the headers="multipart/form-data" ?? If true, so how to set the headers in Httpie?? Ex: I've sent it , but still get empty. http -f -a username:password localhost:8000/photo/ FILES="path_to_image" author="AUTHOR" -h {'Content-Type':"multipart/form-data"} tks for taking a look at this. -
Celery and Flower, with Django and Redis, No queues info in 'Broker' tab
I'm using celery with Django, redis as broker. But I'm unable to get queues info in flower. Searched this problem for two days but got no solution. Please help. In "Dashboard"/"Tasks" tab, everything seems fine, the numbers are updating in realtime. But in "Broker" tab, the message number of queues are all 0 and one queue is missing. I've checked redis, the usage shows it is impossible that every queue is empty. The "Queued tasks" graph in the "Monitor" tab is always empty while the rest of the four graphs are working. I'm running Django 1.8.9, Celery 3.1.20, django-celery 3.1.17, and flower 0.9.1 on Ubuntu 12.04.5 LTS. Tried to start flower with "python manage.py celery -A proj flower --broker=redis://xxxx:6379", "celery -A proj flower --broker=... --broker_api=..." and several other variations. -
Django admin many to many horizontal filter not working
I'm using a many-to-many field in my django model, exposing it on the admin interface and trying to use a filter_horizontal widget. Now, I've added some custom html to my change_form.html so simply adding a filter_horizontal = ('teams', 'players', ) is not helping. I googled around, and found out that the widget requires some default js, so I went ahead and included the following in my change_form.html <script type="text/javascript" src="/static/admin/js/vendor/jquery/jquery.min.js"></script> <script type="text/javascript" src="/static/admin/js/vendor/jquery/jquery.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> <script type="text/javascript" src="/static/admin/js/core.js"></script> <script type="text/javascript" src="/static/admin/js/SelectBox.js"></script> <script type="text/javascript" src="/static/admin/js/SelectFilter2.js"></script> <script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"></script> I see the following error in my browser's console right now: Uncaught ReferenceError: interpolate is not definedinit @ SelectFilter2.js:47 (anonymous function) @ (index):1275 Digging into the SelectFilter2.js, I found that it requires a file addevent.js. I'm guessing this is where the interpolate function would've been defined since all other imports are satisfied. But I cannot find any such file in my project, and google did not help out on this. Can anyone help me here? What am I missing? -
Adding Choice To ManyToMany Field If Not Exist In Database ManytoMany Table - Django
Model.Py class LanguageTags(models.Model): language = models.CharField(_('User Languages'), max_length=10, unique=True) def __str__(self): return '%s' % self.language class Meta: verbose_name = 'User language' verbose_name_plural = 'User Languages' # ...... class User(models.Model): languages = models.ManyToManyField(LanguageTags) specialties = models.ManyToManyField(SpecialtiesTags) hobbies = models.ManyToManyField(HobbiesTags) Forms.py class UserForm(ModelForm): languages = forms.ModelMultipleChoiceField( label=_("Languages (Type Your Language)"), required=True, widget=forms.SelectMultiple(attrs={'data-tags': "true", 'data-placeholder': "Type your Language and Press Enter"}), queryset=LanguageTags.objects.all() ) # ....... Now I want to make it away whenever a language user type that is not the database, the system creates an entry of it. Currently, I am getting an error like Not a Valid Choice If Choice is Not in The Database. How is this possible.