Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying with zappa, Django project in subfolder
I'm new to Docker, AWS Lambda and Zappa, but I'm trying to configure a project with very little success. I connect to Docker (docker-compose run web bash), activate the environment, configure the AWS credentials and run zappa init and zappa deploy. However, after deployment I get an error (executing zappa tail): ModuleNotFoundError: No module named 'project' I believe that that's because my dir structure is not the standard: Dockerfile zappa_settings.json requirements.txt project\ - manage.py - root\ - settings.py - wsgi.py - ... So, my django project is inside the project folder, as I don't like having all the files thrown there and mixed with other configuration files. My zappa config file looks like this: { "dev": { "aws_region": "us-east-2", "django_settings": "project.root.settings", "profile_name": "default", "project_name": "task", "runtime": "python3.6", "s3_bucket": "bucket-name" } } And Dockerfile: FROM lambci/lambda:build-python3.6 # Copy in your requirements file ADD requirements.txt /requirements.txt # Copy your application code to the container RUN mkdir /code/ WORKDIR /code/ ADD . /code/ ENV PS1 'zappa@$(pwd | sed "s@^/var/task/\?@@")\$ ' ADD zappa_settings.json /var/task/zappa_settings.json WORKDIR /var/task RUN virtualenv /var/venv && \ source /var/venv/bin/activate && \ pip install -U pip zappa && \ pip install -r /requirements.txt && \ deactivate CMD ["zappa"] Can you tell … -
Django custom filter error. Returns "invalid filter"
I've been trying to create this custom filter in Django, and I can't for the life of me make it work. in my templatetags folder I have the files __init__.py and alcextra.py in my template I first load the static files and then the templatetags. I've tried reseting the server and deleting and creating the files again. {% load staticfiles %} {% load alcextra %} Which is then extended to my main html file. I have tried putting it in the main html file. in alcextra.py I have written from django import template register = template.Library() @register.filter def multiply(value, arg): return value * arg I have tried loads of different @register versions like @register.filter("multiply", multiply) @register.filter(name="multiply") @register.filter() @register.simple_tag(takes_context=True And all return the same error, invalid filter: 'multiply'. At this point I don't know what to do or what to try. Overview of the directory -
Wagtail admin - default ordering of child pages
In the admin area I have to activate the "Enable ordering of child pages" every time. Is there a way to set this as a permanent option? The main problem is that the listing in the child pages view changes depending on if this is activated or not(if you have changed the ordering), which might be a bit confusing for some. Potentially one could change the default ordering of the children list to match the manually ordered list somehow? -
How to route a multi-part form in django
I'd like my users to be able to place orders. For this kind of order, the user uploads a csv. The app parses, the CSV, serializes the data, and then needs to show the user a new view with the data and a "confirm order" button. I'm not sure how to do this in django. class UploadSampleSheetView(LoginRequiredMixin, FormView): form_class = UploadSampleSheetForm template_name = 'pages/upload.html' def form_valid(self, form): uploaded_sample_sheet = self.request.FILES['uploaded_sample_sheet'] sample = _parse_sample_sheet_to_sample_model(uploaded_sample_sheet) sample.save() return super().form_valid(form) def get_success_url(self): return reverse("orders:create") # how do I get the data over? class CreateOrderView(LoginRequiredMixin, CreateView): model = Order form_class = NewOrderForm template_name = 'pages/complete_order.html' What I'm looking for is some way that, on success, the UploadSampleSheetView can return a CreateOrderView with sample data. In general, I'd love to be pointed to a reference about how to build user flows like this one. How does one view defer to another? I'm seeing a lot of return HttpResponseRedirect('url') which seems a little messy. How do I pass data around views? -
Django 1.11 don't included urls.py
Hello I'm working in my first Django App and I have the next problem: The included URLconf 'eventus.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. . ├── eventus │ ├── eventus │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── wsgi.cpython-36.pyc │ │ ├── db.sqlite3 │ │ ├── settings │ │ │ ├── __init__.py │ │ │ ├── __pycache__ │ │ │ │ ├── __init__.cpython-36.pyc │ │ │ │ ├── base.cpython-36.pyc │ │ │ │ └── local.cpython-36.pyc │ │ │ ├── base.py │ │ │ ├── local.py │ │ │ ├── prod.py │ │ │ └── staging.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ └── myapps │ ├── __init__.py │ ├── __pycache__ │ │ └── __init__.cpython-36.pyc │ ├── events │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── admin.cpython-36.pyc │ │ │ ├── forms.cpython-36.pyc │ │ │ ├── models.cpython-36.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── views.cpython-36.pyc │ │ ├── admin.py │ … -
geodjango with mysql not migrating
I am working on geodjango and just got an issue here geodjango with mysql database resolved. When I ran migrate I got the following error Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/base.py", line 327, in execute self.check() File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 62, in _run_checks issues.extend(super(Command, self)._run_checks(**kwargs)) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/checks/model_checks.py", line 30, in check_all_models errors.extend(model.check(**kwargs)) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/models/base.py", line 1283, in check errors.extend(cls._check_fields(**kwargs)) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/models/base.py", line 1358, in _check_fields errors.extend(field.check(**kwargs)) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 219, in check errors.extend(self._check_backend_specific_checks(**kwargs)) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 322, in _check_backend_specific_checks return connections[db].validation.check_field(self, **kwargs) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/db/backends/mysql/validation.py", line 49, in check_field field_type = field.db_type(self.connection) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/contrib/gis/db/models/fields.py", line 126, in db_type return connection.ops.geo_db_type(self) AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type' This is my database settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'arbithub', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': '3306', } } further codes would be supplied on request -
Right strategy for segmenting Mongo/Postgres database by customer?
I’m building a web app (python/Django) where customers create an account, each customer creates/adds as many locations as they want and a separate server generates large amounts of data for each location several times a day. For example: User A -> [locationA, locationB] User B -> [locationC, locationD, locationE] Where each location is an object that includes name, address, etc. Every 3 hours a separate server gathers data from various sources like weather, check-ins etc for each location and I need to store each item from each iteration so I can then perform per-user-per-location queries. E.g. “all the checkins in the last week group by location for User A” Right now I am using MongoDB and storing a collection of venues with a field of ownerId which is the ObjectID of the owning user. What is the best strategy to store the records of data? The naïve approach seems to be a collection for checkins, a collection for weather records etc and each document would have a “location” field. But this seems to have both performance and security problems (all the access logic would be in web app code). Would it be better to have a completely separate DB for … -
Django - check if a request has timed out
I have a Django app where multiple users could edit the same object at the same time, which would result in data loss/corruption. I want to prevent this. Therefore, I am using a flag in the database (ID of a user currently editing the object) alongside with atomic locking (I am using Redis for this) for as much thread safety as possible. However, the following scenario might still happen: User A clicks that they want to edit an object. The request gets stuck, so they click it again. This time everything gets alright and they edit and save the object. The lock is returned. User B now edits the object and saves it. Now, the request which got stuck wakes up. If it managed to acquire the lock for user A before and user B has already returned it, the request is ready to make some mess here. Please, be aware that this is really simplified (and probably does not make that much sense, but I do not want to explain all the stuff going on, as it is not that much relevant). I know that this scenario is very unlikely, but I want to be 100% thread safe. The … -
Django: include html saved as string in template rendering
I build an HTML table in my view.py function and I want to include it in a template that I already have when rendering. I see that the div is created, but the HTML table is not created. What is the problem? this is the line in view.py: render(request, 'aztracker/import_data.html', {'my_html':html_data}) where html_data is like "<table><tr><th>column1</th></tr><tr><td>data1</td></tr> ....</table>" and I have this section in my import_data.html: <div class="bootstrap-iso"> <div class="tbl_container_numbers"> {{ my_html }} </div> </div> -
geodjango with mysql database
I am developing an application with geodjango and I have been running into some difficulties. following the procedures on the official django website https://docs.djangoproject.com/en/1.11/ref/contrib/gis/tutorial/#use-ogrinfo-to-examine-spatial-data . I first used the orginfo to check spatial data I got a failed message FAILURE: Unable to open datasource `world/data/TM_WORLD_BORDERS-0.3.shp' with the following drivers. then I followed the remaining process creating the models and the error I got when I ran migration was Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/Olar/Desktop/arbithub/src/geolocation/models.py", line 5, in <module> from django.contrib.gis.db import models File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/contrib/gis/db/models/__init__.py", line 3, in <module> from django.contrib.gis.db.models.aggregates import * # NOQA File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/contrib/gis/db/models/aggregates.py", line 1, in <module> from django.contrib.gis.db.models.fields import ExtentField File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/contrib/gis/db/models/fields.py", line 3, in <module> from django.contrib.gis import forms, gdal File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/contrib/gis/forms/__init__.py", line 3, in <module> from .fields import ( # NOQA File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/contrib/gis/forms/fields.py", line 4, in <module> from django.contrib.gis.geos import GEOSException, GEOSGeometry File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/contrib/gis/geos/__init__.py", line 18, in <module> HAS_GEOS = geos_version_info()['version'] >= … -
Unable to upload external file on server for graph(d3 js) , Django
I am trying to upload file on the server in Django and wants to populate data in the graph, I tried in xampp server it is working. But Django I have no idea, Any help would be appreciated. My code is- var bardata = []; d3.tsv('data.txt', function(data) { console.log(data); for (key in data) { bardata.push(data[key].value) } while uploading in django, in console error is coming Failed to load resource: the server responded with a status of 404 (Not Found) -
Django - Issues passing String correctly to template after replacing characters in view
I'm having a bizarre issue with passing a particular string from a view to a template. The string originates from a form, and contains text that I want to simplify into a split-able string later. So, I substitute potential separator characters with a comma like so: # views.py mystring = myform.cleanedData['mystring'] mystring = str(mystring) # convert from unicode mystring = mystring.replace("\n", ",").replace("\r\n", ",").replace(" ", ",").replace(";", ",") # Then I pass it to the template: return render(request, 'html/mytemplate.html', {'mystring': mystring}) Now, take this form data for example: %15 %16 If I print out mystring to a file just before rendering the template, it looks like this: %15,%16 All good so far. The problem, though, comes from trying to render this string into the template. If I try to render the string like this: {{ mystring }} The result is this (leading spaces included): %15 ,%16 It preserves the comma, but adds some other funky stuff, which I don't want because it makes some of my JS get pretty darn confused. I've tried to prevent escaping with the safe filter, but it doesn't seem to change anything in this case. Another thing to note is that if the original form data is … -
Is there a way to declare a mock model in Django unit tests?
Title says it all. I'll illustrate the question by showing what I'm trying to do. I have extended Django's ModelForm class to create a ResourceForm, which has some functionality built into its clean() method for working with Resources, the details of which are unimportant. The ResourceForm is basically a library class, and there are no models in the app where the ResourceForm class is defined, so I can't just use an existing model from the app. I am trying to unit test ResourceForm, but I can't figure out the right way to mock a Django Model, which is required since ResourceForm inherits from ModelForm. This is one of several efforts I have tried (not using mock in this case, but it serves to illustrate what is being attempted): class ResourceFormTestCase(TestCase): class SampleModel(Model): sample_field = CharField() class SampleResourceForm(ResourceForm): class Meta(): model = SampleModel fields = ['sample_field'] def test_unsupported_field_raise_validation_error(self): print('Test validation error is raised when unsupported field is provided') form_data = {'sample_field': 'FooBar', 'unsupported_field': 'Baz'} form = self.SampleResourceForm(data=form_data) But that raises: RuntimeError: Model class customer.tests.tests_lib_restless_ext.SampleModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I'm open to suggestions if I'm way off-base in how I'm trying to test this. -
manage.py: error: unrecognized arguments: runserver 8000, Google Analytics API Django
Here is my Models.py import argparse import os from django.db import models from django.db import models from django.contrib.auth.models import User from oauth2client import tools from oauth2client.client import flow_from_clientsecrets, Storage CLIENT_SECRETS = os.path.join( os.path.dirname(__file__), 'client_secrets.json') TOKEN_FILE_NAME = 'credentials.dat' FLOW = flow_from_clientsecrets( CLIENT_SECRETS, scope='https://www.googleapis.com/auth/analytics.readonly', message='%s is missing' % CLIENT_SECRETS ) def prepare_credentials(): parser = argparse.ArgumentParser(parents=[tools.argparser]) flags = parser.parse_args() # Retrieve existing credendials storage = Storage(TOKEN_FILE_NAME) credentials = storage.get() # If no credentials exist, we create new ones if credentials is None or credentials.invalid: credentials = tools.run_flow(FLOW, storage, flags) return credentials class FlowModel(models.Model): id = models.ForeignKey(User, primary_key=True) flow = FLOW class CredentialsModel(models.Model): id = models.ForeignKey(User, primary_key=True) credential = prepare_credentials() When I run python manage.py runserver It gives me the error below usage: manage.py [-h] [--auth_host_name AUTH_HOST_NAME] [--noauth_local_webserver] [--auth_host_port [AUTH_HOST_PORT [AUTH_HOST_PORT ...]]] [--logging_level {DEBUG,INFO,WARNING,ERROR,CRITICAL}] manage.py: error: unrecognized arguments: runserver 8000 I have tried searching for solutions but this error still persists. Kindly help me solve this as I am running out of time. -
django storages and setting ACL per object
I am using django-storages and google-cloud-storage backend. what I currently have is the following. from django.conf import settings from storages.backends.gcloud import GoogleCloudStorage from storages.utils import clean_name from django.conf import settings class PublicImageUploadStorage(GoogleCloudStorage): bucket_name = settings.IMAGES_BUCKET_NAME or None file_overwrite = settings.IMAGES_OVERWRITE or True def make_public(self, name): name = self._normalize_name(clean_name(name)) blob = self._get_blob(self._encode_name(name)) return blob.make_public() this is slow because it looks up blob object by name then return it so I can make it public. what is the most efficient way of setting object ACL to be public-read before saving the object to google storage ? -
Trying to create a Django model instance via a form, but I only want to extract some fields from the form and set others manually
I'm trying to create a gallery app in Django. I have two models: Pic and Profile, which represent an individual picture and a user profile respectively. Each user has a profile instance created when they sign up for the website. Here are the models: class Profile(models.Model): user = models.OneToOneField(User, related_name="profile") class Pic(models.Model): profile = models.ForeignKey(Profile, blank=True, null=True) photo = models.ImageField(upload_to = "photos/%Y/%m/%d/") I want users to be able to upload an image through an HTML form. When they upload the image I want to create a Pic whose ImageField corresponds to the upload. I've created a ModelForm for the Pic model to accomplish this. Here's the form as of now: class PicForm(forms.ModelForm): class Meta: model = Pic fields = ('photo',) And the upload_image view: def upload_image(request): if request.method == "POST": form = PicForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: return redirect('upload_image') else: form = PicForm() return render(request, 'pics/upload_image.html', { 'form': form }) So the problem is, I want the user to be able to set the photo field of the new Pic via the form, but not the profile field. I want that to be set to the user's profile. How can I accomplish this? -
How to compile a .java file which is been arbitrarily named different from public class name
I had been creating an online judge platform like codeforces.com on Django recently. Now, I'm struck across a problem that the user may possibly upload a Java file for testing with the filename different from the public class defined inside it. Yet, I should compile it automatically. So, what could be a possible solution to this? -
django check if user is allowed to add Post
i am creating a blog just for practice and i want to allow some users to add/delete a post how to add this BooleanField to users and check if allowed in templates -
How can I load data from tables before project refactoring and add them to new tables?
I was refactoring my project and after that I have situation in my database shown below. I changed name of my project from backend2 to backend. Normally I could delete all backend2 tables however I have there data that I need. Backend tables are empty. My goal is to have data from tables from backend2 in my backend tables. Then I don't need backend2 tables and I can delete them. Any ideas how can I do this? public | backend_table1 public | backend_table2 public | backend_table3 public | backend_table4 public | backend_table5 public | backend2_table1 public | backend2_table2 public | backend2_table3 public | backend2_table4 public | backend2_table5 -
How to check dates basing on year and week number in Python
I'd like to check the days for a given week_number. for an instance, if I input year 2017 and weekNumber 43, I would like to receive all dates for that week, in this case 22-28.10.2017. Is it possible to do in Python ? was trying to find something using google, but unsuccessfully Thanks in advance, -
Use cookiecutter-django with Celery 4.x
I use cookiecutter-django with celery==3.1.25. Now I need use tasks scheduler, and my opinion, best way for this - it's celery beat. But here I found information that celery-beat works with Celery version 4.x Here I saw the information that pyup-bot on July 24 offered to update Celery to version 4.1.0, but this issue is still open. Prompt, how to be in my situation? I like cookiecutter-django and I'm using it now in my project, but also, I really need a task scheduler. I have not yet tried to replace the version of Celery, but I think that this will lead to a number of mistakes, otherwise it would have been done before me. -
Unable to keep content in the left sidebar data in django page
I am building a website based on django.Below find my models: model.py class Projectname(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Jenkinsjobsname(models.Model): projectname=models.ForeignKey(Projectname) jobsname = models.CharField(max_length=200) def __str__(self): return self.jobsname view.py def index(request): project_name=Projectname.objects.order_by('-name')[:5] context = {'categories': project_name} return render(request,'buildstatus/index.html', context) def detail(request,projectname_id): jobs=Projectname.objects.get(pk=projectname_id) context = {'jobs': jobs} return render(request,'buildstatus/detail.html', context) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<projectname_id>[0-9]+)/$', views.detail, name='detail'), ] detail.html {% extends "base.html" %} {% block text %} <ul class = "nav nav-tabs" > {% for jenkinsjobsname in jobs.jenkinsjobsname_set.all %} <li><a href= "#">{{jenkinsjobsname.jobsname}}</a></li> {% endfor %} </ul> {% endblock %} index.html {% extends "base.html" %} {% block text1 %} {% if categories %} <ul> {% for category in categories %} <li><a href ="{% url 'detail' category.id %}">{{category.name }}</a></li> {% endfor %} </ul> {% else %} <strong>There are no test categories present.</strong> {% endif %} {% endblock %} base.html <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container-fluid"> <div class="nav-collapse collapse"> <ul class="nav pull-right"> <li><a href="/admin/">Login</a></li> </ul> <ul class="nav navbar-nav"> <li class="active"><a href="/buildstatus/">Home</a></li> </ul> </div> </div> </div> </div> <div class="container-fluid"> <div class="row-fluid"> <div class="span3"> <div class="well sidebar-nav"> <h3>PROJECTS</h3> {% block text1 %} {% endblock %} </div> </div> <div class="span3"> {% block text %} {% endblock %} </div> … -
i can not import py module when i using python django
that'my first time to ask question here. i'm learning django now, I start a project in virtualenv. that's my file file picture when I trying from polls import views module under urls.py. module picture it shows : No module named 'polls' I search for the python documents and tring to modify it like: from . import views or from .polls import views but it shows:Parent module '' not loaded, cannot perform relative import some people say it's sys.path problem.So I added a current sys.path in the virtualenv. But it can not work either. How to solve the problem ? .... -
Order Django Query by DateTime Field Day - 1.9
I have a model in my Django application that has a DateTime field, and want to order those models simply by day, and than by that models first name. I have a meta class on my model that sets the ordering by its date time field in descending order, but it is picking up the time as well. This SO question showed promise, but the two accepted answers are for any Django version 1.8 or lower, and 1.10 or higher, and I am using Django 1.9 hah. I looked through the Django documentation to try and find a way to do this, but am have a lot of difficulty. Maybe I am just getting tunnel vision. Does anyone know of an equivalency to Django.db.models.functions.Trunc so I can use the accepted answer from the Stack Overflow answer mentioned, or do they know of a way to only order on a date time fields day ? Model import datetime import logging from django.db import models, IntegrityError from django.db.models import DateTimeField #from django.db.models.functions import Trunc <- only available in 1.10 from account.models import Account from dealer.models import Dealer class DealerLead(models.Model): user = models.ForeignKey(Account) dealer = models.ForeignKey(Dealer) assigned = models.BooleanField(default=False) assigned_to = models.ForeignKey(Account, related_name='leads', … -
Django, TinyMCE field serialization inconsistencies
In Django I have a form. There is one form field that has TinyMCE editor attached to it. I want to check if form has changed so if it has, pop up modal should show. I achieve this by this code which runs on every page load: $($('my-form').each(function() { $(this).data('init') = $(this).serialize(); }) $(window).bind('beforeunload', custom_validator); ); And of course the custom_validator function is in the same file: function custom_validator() { $('my-form').each(function() { if ($(this).data('init') != $(this).serialize()) { return "Form has unsaved changes."; } }) } When page loads, the data('init') is serialized with the TinyMCE field as well. If the TinyMCE field contains multiple lines, serialize() represents them with '%0D%0A'. Which is fine. If I want to navigate away from the page or just reload it after changing the form, the 'beforeunload' event triggers the custom_validator function and prevents me to do that which is good as well. Now, the problem begins when I load the page and I don't make any changes to the form and just want to navigate away from page, the popup window occurs and warns me that there are changes on form, even I didn't change anything. It turns out that if I have multiple …