Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invoke function after all methods Django Rest Framework ModelViewSet
I would like to invoke a function after all methods in a ModelViewSet. The function itself will be used as an external event log. So the response from the views would not be modified. I was not able to figureout how to achieve this. My ModelViewSet is a very basic one with serializer class and queryset defined. Any help would be appreciated. -
How to set initial value that is reference to an object
We are trying to set object as an initial value (image, it is a foreign key to an Image). We just cannot make it work, we are always getting NULL/blank value instead. Thanks for any help! from views.py def create_comment(request, image_id): image = Image.objects.get(id = image_id) if request.method == 'POST': form = CreateComment(request.POST, initial={'image':image}) if form.is_valid(): form.save() else: form = CreateComment() return render(request, 'ImagePost/create_comment.html', {'form':form, 'image_id':image_id}) from forms.py class CreateComment(forms.ModelForm): class Meta: model = Comment fields = ['user', 'text'] from create_comment.html <html> <body> <h1>Add comment</h1> <form action="{% url 'create_comment' image_id %}" method="POST"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Add"> </form> </body> </html> -
why home.html (for adding a new post) is not showing the rendered django form with ckeditor toolbar in add new post?
i am integrating some apps to make a bigger project but the problem is when i try insert ckeditor in html login page it is not showing. for this reason i tried to make separate app is to see whats going on here. i am showing you the code in detail. editing/settings.py: .......... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'editor', 'ckeditor_uploader', 'ckeditor', ] TEMPLATES = [ { 'DIRS': [os.path.join(BASE_DIR,'templates')],........ ..................... STATIC_URL = 'editor/static/' STATIC_ROOT='editor/static/' CKEDITOR_UPLOAD_PATH='editor/static/media/' editing/urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include('editor.urls')), path('ckeditor/',include('ckeditor_uploader.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) in this case, my static folder is in editor/static when i execute python manage.py collectstatic and ckeditor folder is in editor/static directory also. editor/models.py: from django.db import models from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class Post(models.Model): title=models.CharField(max_length=255) body=models.CharField(max_length=2000) description=RichTextUploadingField() def __str__(self): return self.title editor/admin.py: from django.contrib import admin from .models import Post admin.site.register(Post) when i execute python manage.py makemigrations and python manage.py migrate, ckeditor can be seen in locahost:8000/admin's new post section perfectly. then i tried to make templates. base.html: {% load static %} <html> <head> <title>Django blog</title> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400" … -
Django Form Not Validating Properly
Code: https://dpaste.org/pwWT I want to validate the user's phone number and I want to display to the user who enters an incorrect phone number "Enter a valid phone number (e.g. +12125552368)." This message is the default of PhoneNumberField. The form is not validating and I am not sure why. I do not want any value to be accepted as the phone number. Also not sure why the recaptcha statements are not getting printed either. I would appreciate any help with this. -
Fail to load diferente content in modal Table
I Have two bootstrap tables, one of them (table_compras) call a modal (table_modal) depending on the column clicked, but i am having troubles refreshing the content rows in table, here is my code: HTML: <div id="modalTable" class="modal fade" tabindex="-1" role="dialog"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Acumulado por Obra</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" id="bodyIP"> <table id="table_modal" data-detail-view="true" data-checkbox-header="true" data-search="true" data-search-align="left" data-detail-filter="detailFilter" data-pagination="true"> <thead id="thDel"> <tr> </tr> </thead> </table> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> JS Here i am getting the row and column index to populate the modal table but when I click on a different cell it continues getting the same data rows of the first cell, i have tried the commented lines of code but none of them give me the desired result : var $table_compras = $('#table_compras') var $table = $('#table_modal') $(function() { $('#modalTable').on('shown.bs.modal', function () { $table.bootstrapTable('resetView'); }) $('#modalTable').on('hide.bs.modal', function (e) { //var table = $('#table_modal').DataTable(); //table.clear(); //$("#table_modal tr").remove(); //$('#table_modal').empty(); //$(e.target).removeData('bs.modal'); $('#table_modal').detach(); //$("#table_modal").empty(); //$("#table_modal thead").remove(); //$('#modalTable').removeData(); }) }); $('#table_compras').on('click-cell.bs.table', function (field, value, row, $el) { buildTable2($table, 2, $el.C1, value); $("#modalTable").modal(); //alert($el.C1+"-"+$el.C2+"-"+$el.C3+"---"+value); }); function buildTable2($el, cells, ano, mes) { var columns … -
Add fields to a form with django at application level
I am using django and I need to use a form that is dynamic, that at the application level the user can add fields to the form. For example, I have a beer and I want to add features, which function would allow me to place an 'add' button and a new input will appear to put a new feature to the beer unlimited times, thus being able to add the number of features inputs that you want . If anyone knows the name of a function that allows me to do it or a link to the solution! Thanks in advance. I read a little about the FormSet and the Management Form but I really didn't understand exactly how to use it! If I could add a brief example it would be helpful -
Celery schedule
I have some schedule problem in Celery. The task works, however I want it to run once on Monday, but it runs every minute. My schedule config: CELERY_BEAT_SCHEDULE = { 'kek': { 'task': 'kek', 'schedule': crontab(day_of_week=6), } } -
How to delete 0001_initial.py in Django? Django migrations are not working
I am using Django 2.2 with Python 3.7 on Windows 10. I created a project and then an app. The models.py was populated by using INSPECTDB for an existing Postgres database. I removed the line 'managed = False' from each class. I created the initial makemigrations and did the migrate. There are app migration files, 0001_initial.py and init.py I had to make changes, adding more classes, in the models.py file. Then I ran the makemigration and migrate on the app. Now I get a message '.errors.DuplicateTable: relation "INT_ORG" already exists.' Throws an exception. I tried to use 'python manage.py makemigrations' and got the message that there were no changes detected. I tried to use 'python manage.py migrate --fake-initial'. This Errored with duplicate table already exists No luck. I'm failing badly here. And while working yesterday, somehow - don't know how, another migration file shows up called '0002_auto_20191212_1137.py' The '0002_auto_20191212_1137.py' migration file has all my changes in it. But it is not being migrated either when I try to makemigrations and migrate. I need to go back to a point I can understand and not loose everything. A co-worker had a similar problem and they just started a new project and … -
Getting PostSyncDb error when I run Python manage.py runserver (Trying to update to DJango 1.9)
I am trying to update my django slowly, I just went up to 1.9 today (from 1.8) and I am running into ImportError: cannot import name post_syncdb. I made sure my signals are imported for my models and that I have implement This Link . Any one else been through this? Here is my traceback when I try python manage.py runserver (www)ubuntu@prodcopy:/opt/django/www/src$ python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/django/www/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/opt/django/www/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 302, in execute settings.INSTALLED_APPS File "/opt/django/www/local/lib/python2.7/site-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/opt/django/www/local/lib/python2.7/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/opt/django/www/local/lib/python2.7/site-packages/django/conf/__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/opt/django/www/src/site_aggrigator/__init__.py", line 2, in <module> import management File "/opt/django/www/src/site_aggrigator/management/__init__.py", line 6, in <module> from django.db.models.signals import post_syncdb ImportError: cannot import name post_syncdb -
Return more than just the Auth Token with Django Rest + Djoser?
I'm using Django REST along with Djoser as my authentication service. However, when making a post request to the djoser auth endpoints, e.g. .../auth/token/login, the only response I get back is auth_token: xxxxx Is there a way to retrieve more than just the token value, e.g user id and username? -
Pass slug or id on GET request
I'm trying to test an API view for my Django project: BOOK_URL = reverse('api:book') // '/api/book/' book_id = 1 res = APIClient().get(f'BOOK_URL${book_id}') This works, but as you can see I need to interpolate the book_id into the string. Is there a way I can send a request without interpolating? I tried: res = APIClient().get(BOOK_URL, data={'book_id': book_id}) This is my views.py class BookView(APIView): def get(self, request, book_id): book = get_object_or_404( Book.objects.all(), id=book_id ) return book -
Problem with redirection on save form in UpdateView
I'm using Class Based Views in my project. After create object IdentityDocument in CreateView it redirects to correct Person DetailView (IdentityDocument owner), but after update in UpdateView redirects to current logged user detailed view (who is not parent owner object IdentityDocument). I have classes: class Person(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... def get_absolute_url(self): return reverse('person-detail', kwargs={'pk': self.pk}) class IdentityDocument(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) person = models.ForeignKey(Person, on_delete=models.CASCADE) ... def get_absolute_url(self): return reverse('person-detail', kwargs={'pk': self.person.pk}) My views: class PersonDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView): model = Person context_object_name = 'person' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['identity_documents_list'] = get_newest_identity_documents(self.kwargs.get('pk')) return context def test_func(self): person = self.get_object() if self.request.user == person: return True return self.request.user.is_admin class IdentityDocumentCreateView(LoginRequiredMixin, CreateView): model = IdentityDocument ... def dispatch(self, request, *args, **kwargs): self.person = get_object_or_404(Person, pk=kwargs['person_id']) return super().dispatch(request, *args, **kwargs) def form_valid(self, form): form.instance.person = self.person return super().form_valid(form) class IdentityDocumentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = IdentityDocument ... def form_valid(self, form): form.instance.person = self.request.user return super().form_valid(form) def test_func(self): identity_document = self.get_object() if self.request.user == identity_document.person: return True return self.request.user.is_admin -
The POST method in DJANGO returns "None" when a form is submitted
I have built a small web application that will get the data from a HTML table and dump it into sqlite database. When I use the POST method to capture a particular cell value, it returns none. Could someone please help me how to get the data from the table I created below in table.html ? models.py from django.db import models class people(models.Model): Company = models.TextField() Contact = models.TextField() Country = models.TextField() def __str__(self): return self.Contact urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.getvalue, name='myapp'), ] views.py from django.shortcuts import render def getvalue(request): value = request.POST.get("R1") print("The R1 values is", value) return render(request, 'myapp/table.html') table.html <html> <head> </head> <body> <form id="form1" class="form1" method="post"> {% csrf_token %} <input type="submit" value="Update DB" /> <table> <tr> <th>Company</th> <th>Contact</th> <th>Country</th> </tr> <tr> <td name='R1'>Alfreds Futterkiste</td> <td name='R2'>Maria Anders</td> <td name='R3'>Germany</td> </tr> </table> </form> </body> </html> -
Django rest framework - Optimizng serialization of nested related field
Given the following models: class Model_A: ... class Model_B: ... class Model_C: model_a = ForeignKey(Model_A, related_name='c_items') model_b = ForeignKey(Model_B) ... And the following model serializers setup: class Model_A_Serializer: class Model_C_Serializer: class Meta: model = Model_C fields = ( 'model_b', ... ) c_items = Model_C_Serializer(many=True) class Meta: model = Model_A fields = ( 'c_items', ... ) And a basic vieweset: class Model_A_Viewset: model = Model_A queryset = model.objects.all() serializer_class = Model_A_Serializer ... When the user POST's the following JSON payload to create an instance of Model_A along with instances of Model_C: { 'c_items': [ { 'model_b': 1 }, { 'model_b': 2 }, { 'model_b': 3 } ] } Note: Model_B instances with IDs 1, 2, and 3 already exist, but no Model_A and no Model_C instances exist in the above example. Then I noticed that django seems to execute the following queries when serializing the incoming data: SELECT ... FROM Model_B WHERE id = 1; SELECT ... FROM Model_B WHERE id = 2; SELECT ... FROM Model_B WHERE id = 3; This seems unnecessary to me as a single SELECT ... FROM Model_B WHERE id IN (1,2,3) would do the job. How do I go about optimizng this? I have tried … -
registration with username and email, and login with email only
I am creating a login that requests for username and email with Django-rest-auth, the email is key as it will be used to log in to the user. but the username also has its importance in my app as when searching up a user, I would want to do something like this "accounts//". in trying to do this I have added a backend as advised in a former post. please, what can I do, so when signing up I can input my username and email, but when logging in i use only email? backend.py class EmailAndUsernameBackend(ModelBackend): """ this model backend would help me use both username and email, remember to overide your AUTHENTICATION_BACKENDS to this one """ def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: user = UserModel.objects.get(Q(email=username) | Q(username=username)) except UserModel.DoesNotExist: UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user in my settings.py, apart from my installed apps and the authentication backends, I have: AUTHENTICATION_BACKENDS = ( # 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', 'core.backends.EmailAndUsernameBackend', ) # to use old_password when setting a new password OLD_PASSWORD_FIELD_ENABLED = True LOGOUT_ON_PASSWORD_CHANGE = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_EMAIL_FIELD = … -
Django Form Validation And Google Recaptcha Not Working
I have a form that is not validating phone numbers and emails properly even though I am using PhoneNumberField and EmailField. When a user inputs invalid data, no error messages are showing up such as "Enter a valid email address." or "Enter a valid phone number (e.g. +12125552368)." Maybe the validation is not working because I am passing the form class itself and not the instance? Otherwise I have no clue. The form successfully processes when a user inputs valid data though. My Google Recaptcha code is also not working properly because the print statements for result, recaptcha_response, and result_success are not printing. The recaptcha symbol is displaying though at the bottom right of the webpage. Code: https://dpaste.org/KSJY I would appreciate any help with this. -
Add dynamic attribute to serializer
I'd like to add a dynamic attribute to my serializers whenever they are called. Note that I'm talking about an attribute, not a field. Here's the idea: User call the API Viewset calls the serializer with the data I manage to set self.my_key = my_dynamic_value Checks and returns the serializer data (normal process) To set my dynamic value, I need to use self.context meaning I can't override the __init__ method of the serializers (they are called on server start and context is empty) Any idea on how I could do it? -
Django get_or_create not getting data back
i have created a FBV for Modal form (popup) i want to have the same view to handle both create and update, the reason i am using FBV is that am assigning the foreign key through queries rather that passing the id through the URL. Please note the JS script am using to call the Modal and render the form in it. **Models.py:** class Startup ( models.Model ) : author = models.OneToOneField ( User , on_delete = models.CASCADE ) startup_name = models.CharField ( 'Startup Name' , max_length = 32 , null = False , blank = False ) class Startup_About ( models.Model ) : str_about = models.OneToOneField ( Startup , on_delete = models.CASCADE ) about = models.TextField ( 'About Startup' , max_length = 2000 , null = False , blank = False ) problem = models.TextField ( 'Problem/Opportunity' , max_length = 2000 , null = False , blank = False ) business_model = models.TextField ( 'Business Monitization Model' , max_length = 2000 , null = False ,blank = False ) offer = models.TextField ( 'Offer to Investors' , max_length = 2000 , null = False , blank = False ) def __str__(self) : return str(self.str_about) **forms.py:** class startupform(forms.ModelForm): class Meta: … -
The view didn't return an HttpResponse object. It returned None instead, using Django
So, I am trying to display a form into my html using Django, it has to be a form that creates a new page in the database. I am using ModelForm since I've read is the best way to provide the user with the tools to input data in the database. in views.py: from django.shortcuts import redirect, render from django.http import HttpResponse from .models import Pages, PagesForm from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import login, logout, authenticate from django.contrib import messages from .forms import NewUserForm def homepage(request): return render(request = request, template_name='main/home.html', context = {}) def pages(request): if request.method == "POST": form = PagesForm(request.POST) if form.is_valid(): pass #nada, solo activa la validación else: form = PagesForm() return render(request, template_name='main/pages.html', context = {"Pages":PagesForm.objects.all}) in models.py: from django.db import models from datetime import datetime from django.forms import ModelForm # Create your models here. #Pages son entradas del diario class Pages(models.Model): title = models.CharField(max_length=300) content = models.TextField() author = models.CharField(max_length=50) published_date = models.DateTimeField("Published: ", default=datetime.now()) def __str__(self): return self.title class PagesForm(ModelForm): class Meta: model = Pages fields = '__all__' in pages.html: {% extends "main/header.html" %} {% block content %} <div> {% for page in Pages %} <h2>Display recent pages</h2> <div class="col s12 … -
Python manage.py runserver issuing the no module Error
Trying to runserver but I'm getting this errors Traceback (most recent call last): File "manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/usr/lib/python2.7/dist-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/lib/python2.7/dist-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/lib/python2.7/dist-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/prezine/Desktop/project/djangopinmgmt/settings.py", line 14, in <module> import dj_database_url ImportError: No module named dj_database_url I'm not sure what to change or how to go this, I've also tried installing dj_database_url, but it seem to not work still pip install dj_database_url -
Django - grabbing an additional field from related table
I have the following models: class User(AbstractBaseUser, PermissionsMixin): SUPERVISOR = 1 REVIEWER = 2 VERIFIER = 3 READ_ONLY = 4 USER_TYPE = [ (SUPERVISOR, 'Supervisor'), (REVIEWER, 'Reviewer'), (VERIFIER, 'Verifier'), (READ_ONLY, 'Read Only'), ] email = models.EmailField(max_length=50, unique=True) name = models.CharField(max_length=100) phone = models.CharField(max_length=50, null=True) role = models.IntegerField( choices=USER_TYPE, default=READ_ONLY ) is_active = models.BooleanField(default=True) class Comment(models.Model): text = models.TextField() user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT ) View: class CommentViewSet(BaseCertViewSet): queryset = Comment.objects.all() serializer_class = serializers.CommentSerializer Serializer: class CommentSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField( read_only=True, slug_field='name' ) class Meta: model = Comment fields = ('id', 'text', 'user') read_only_fields = ('id',) My question: when I hit the comment API endpoint, I'd like it to return the user role from the user model as well. How do I go about doing that? -
How send a request error inside the save function?
I need to validate the video duration before the video is saved,but he only message error i found is the forms.ValidationError. The upload request is getting error 500 because of the raise. def save(self, *args, **kwargs): ... result = subprocess.Popen(["ffprobe", video_path], stdout = subprocess.PIPE, stderr = subprocess.STDOUT) t = [x for x in result.stdout.readlines() if "Duration" in x] if duration > 30: raise forms.ValidationError('The Video must have 30 secs') ... But i need a response instead of raise like: return Response({'detail': 'This video must have 30 secs'}, status=status.HTTP_400_BAD_REQUEST) But i only know how to use Response inside the Views, is there a way to use Response inside the save function? -
How to create my own endpoint in Django with rest_framework_json_api?
I am new to Django and need some help to understand! I have been able to create the Api and it works! But ... how do I create an endPoint to do something specific that I want? For example, validate an email? In other words, with a views.ModelViewSet how to define for example def validate (request): I tell you that I have created the endpoint that mentions them but I have to make some arrangements so that the answer is as I expect it. class SomeViewSet(views.ModelViewSet): allowed_methods = ('GET', 'PATCH', 'POST', 'OPTIONS') queryset = Some.objects.all() serializer_class = SomeSerializer def validate(request): email = request.GET.get("email", None) if email and Some.objects.filter(email=email).exists(): return JsonResponse({'message': 'Email already exists.'}, status=status.HTTP_200_OK) return JsonResponse({'message': 'Email does not exist.'}, status=status.HTTP_400_BAD_REQUEST) rest_framework.response.Response does not work here! Thanks! -
Django raising AppRegistryNotReady after update from to 1.9
I have read many similar posts with the same situation and tried a few things suggested if they were at all related. I just updated to Django 1.9 and I received this traceback: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/django/www/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/opt/django/www/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 302, in execute settings.INSTALLED_APPS File "/opt/django/www/local/lib/python2.7/site-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/opt/django/www/local/lib/python2.7/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/opt/django/www/local/lib/python2.7/site-packages/django/conf/__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/opt/django/www/src/site_aggrigator/__init__.py", line 2, in <module> import management File "/opt/django/www/src/site_aggrigator/management/__init__.py", line 4, in <module> from django.contrib.auth.models import Permission File "/opt/django/www/local/lib/python2.7/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/opt/django/www/local/lib/python2.7/site-packages/django/contrib/auth/base_user.py", line 49, in <module> class AbstractBaseUser(models.Model): File "/opt/django/www/local/lib/python2.7/site-packages/django/db/models/base.py", line 94, in __new__ app_config = apps.get_containing_app_config(module) File "/opt/django/www/local/lib/python2.7/site-packages/django/apps/registry.py", line 239, in get_containing_app_config self.check_apps_ready() File "/opt/django/www/local/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. All my apps are installed on my virtual env for sure because the app was running fine before I made the update. I also received this right before my update: /opt/django/www/local/lib/python2.7/site-packages/Django-1.8-py2.7.egg/django/contrib/auth/models.py:41: RemovedInDjango19Warning: Model class django.contrib.auth.models.Permission doesn't declare an explicit app_label … -
How can I modify this JS function so that it runs whenever the field is equal a certain length?
I have a function that currently runs whenever the user clicks/tabs out of the employee_number field. I would like it to run whenever the length of the numbers entered is equal to 6, without having to leave the field, since when I try using the tab, it conflicts with loading the next field which is a drop-down that is part of the function ran. I tried by running it using .change and putting the constraint within the function, but it did not work and I don't know what else to try. enter_exit.html {% extends "base.html" %} {% load core_tags staticfiles %} {% block main %} <form id="warehouseForm" action="" method="POST" data-employee-activity-lookup-url="{% url 'operations:employee_activity_search' %}" novalidate > {% csrf_token %} <div> <div> <div id="employee-name" style="margin-bottom: 10px">&nbsp;</div> <label>Employee #</label> {{ form.employee_number }} </div> <div=> <label>Work Area</label> {{ form.work_area }} </div> <div style="display: none" id="my-hidden-div"> <label>Station</label> {{ form.station_number }} </div> </div> <div> <div> <button>Enter Area</button> <button>Exit Area</button> </div> </div> </form> <script> // Grab the employee name and their current active work log (if any) $(document).on('blur', "#{{ form.employee_number.id_for_label }}", function(){ var url = $("#warehouseForm").attr('data-employee-activity-lookup-url'); var employeeId = $(this).val(); # ... more fields ... if (employeeId !== "") { # .. Rest of function ... }) …