Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
custom ordering in get_queryset djangorestframework
How can I implement this custom order_data into my query set so I can properly order it, I'm not understanding this well so can someone help me and explain me how to implement this? Custom ordering and filtering in get_queryset view: filter_date = self.request.query_params.get('filter_date', None) order = [ LeadContactConstants.STATUS_CLIENT, LeadContactConstants.STATUS_QUALIFIED, LeadContactConstants.STATUS_CONTACTED, LeadContactConstants.STATUS_PRISTINE ] order_data = sorted(queryset, key=lambda p: order.index(p.status)) if filter_date is not None: queryset = queryset.filter(next_action_date__lte=filter_date, status=order_data) return queryset -
how does django sort the models in django admin in chinese?
Django version: 1.10 I have an django app built for chinese end users. In django admin, the models are ordered by alphabetically for English. When I switch to Chinese, the models are re-ordered. I want to know how they are ordered and determined by which part of the Django software. -
Django re-using query results
I have a website with groups. I manage the (object-)permissions for these groups using Django-guardian. class Groups(models.Model): GROUP_ID = models.AutoField(primary_key=True) group_name = models.CharField(max_length=255) group_slug = models.SlugField(max_length=255) class Meta: permissions = ( ('group_member', 'group_member'), ) Every group member can do a number of pre-set things using a number of views which have their own set of URLs. [domain]/[group_slug]/... I am currently checking for permissions in the templates which requires the Groups-object. Moreover there are some group settings stored in the Groups-object which influence the style of the template. This means everytime I load a view I retrieve this Group-object using the [group_slug] in the url and add it to the context, resulting in a lot of (unnecessary?) queries. I think a solution would be to add the group object to a cookie and then in every view check whether the group-object exists via request.COOKIES.get(...). Is this a good (and safe?) idea or am I abusing cookies for something they aren't intended for and are there better ways to achieve the goal of avoiding the Groups queries? -
Add HTML tags into json response and render like html
I am using python django as rest api, angular 2 as front end. With every request I am getting response in form of json. I want to highlight few words in my json response. So I want to add few html tags like from python code itself and browser should renders it as html tag only. But Browser doesnt understand coming with in JSON response and displays as plain text only. Any one who have done something similar. Please help. -
Error was: No module named postgresql.base ImproperlyConfigured 'django.db.backends.postgresql'
I've installed the postgresql for my django project. Earlier when i installed it and run makemigrations,it worked fine, but due to some reasons i had to uninstall postgresql and removed its files and re-installed the postgresql,when i run it now, it was showing me this insane error. Settings File: # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '*****', 'USER': '*****', 'PASSWORD': '', Error: File "/Users/Devadanam/Desktop/trackingsys/lib/python2.7/site-packages/django/db/__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/Users/Devadanam/Desktop/trackingsys/lib/python2.7/site-packages/django/db/utils.py", line 211, in __getitem__ backend = load_backend(db['ENGINE']) File "/Users/Devadanam/Desktop/trackingsys/lib/python2.7/site-packages/django/db/utils.py", line 134, in load_backend raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgresql' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'sqlite3' Error was: No module named postgresql.base -
How to set SCOPE of Shopify in django-allauth
I tried to configure the scopes that I want in SOCIALACCOUNT_PROVIDER under shopify -> SCOPE in my settings.py, but it doesn't work. it always gives the default that was set in it which are read_orders and read_products. SOCIALACCOUNT_PROVIDER = { 'shopify':{ 'SCOPE':[ 'read_analytics', 'read_products', 'read_script_tags' 'write_script_tags' ], 'IS_EMBEDDED': True, } } I just tried doing the SCOPE of Shopify in SOCIALACCOUNT_PROVIDER, cause that's how I see other providers do it, so I assume that was also the way to define the scopes that I wanted in shopify. the other way was adding it to the link via queryparams when I'm gonna do oauth to shopify using the django-allauth. /shopify/login/?shop=<sample-shopify-shop-name>&scope=<shopify-scope> but I think this isn't the best practice? The document in django-allauth about Shopify doesn't anything about setting the scopes that you want. -
Error when run the django project
Traceback (most recent call last): File "manage.py", line 17, in "Couldn't import Django. Are you sure it's installed and " 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? I want to run this project https://github.com/adarsh2397/Online-Judge -
Django query taking too much time
I'm using django and django rest framework to make a query from all users in data that have a permission sent as a url parameter but this query is taking too long. I'm user pycharm debugger how can I try to check why is it taking to long, this is the function: @list_route(url_path='permission/(?P<permission>.+)') def read_permission(self, request, *args, **kwargs): serializer = self.get_serializer_class() qs = get_user_model().objects.filter_by_permission(self.kwargs.get('permission')) qs = qs.order_by(Lower('username')) return Response(serializer(qs, many=True).data) -
MultipleObjectsReturned - get() returned more than one ContentType -- it returned 2
everything was working fine then suddenly i got this error MultipleObjectsReturned at /rohit/post/new-post/ get() returned more than one ContentType -- it returned 2! i do not know why it returned 2 objects. it just suppose to return one and i can't figure it out. help me guys. Here's my code: models.py: class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') parent = models.ForeignKey("self", null=True, blank=True) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) objects = CommentManager() class Meta: ordering = ['timestamp'] def __unicode__(self): return str(self.user.username) def __str__(self): return str(self.user.username) def get_absolute_url(self): return reverse("comments:thread", kwargs={"id": self.id}) def get_delete_url(self): return reverse("comments:delete", kwargs={"id": self.id}) def children(self): #replies return Comment.objects.filter(parent=self) @property def is_parent(self): if self.parent is not None: return False return True Views.py: instance = get_object_or_404(Post, slug = slug) initial_data = { "content_type": instance.get_content_type, "object_id": instance.id } print(initial_data) form = CommentForm(request.POST or None, initial= initial_data) if form.is_valid() and request.user.is_authenticated(): c_type = form.cleaned_data.get("content_type") print('c_type : ',c_type) content_type = ContentType.objects.get(model=c_type) print(content_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get("content") parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user = request.user, content_type= … -
Update model field and any other fields in django
Is it possible to update a field and when saving it, it should save other fields with new changes. For example, I have the below model, class Backup(models.Model): user=models.ForeignKey(User) title=models.CharField(max_length=200) is_approve=models.BooleanField(default=False) is_bad=models.BooleanField(default=False) country=models.CharField(max_length=100) Now, my main aim is to just make is_approve field True. My secondary aim is to update other fields alongside the is_approve field, incase the user makes changes before clicking on the approve button in template. @staff_member_required def activate_moderation(request, backup_id=None): if id: vpostmod=get_object_or_404(Backup, id=backup_id) vpostmod.is_approve =1 vpostmod.save() How can I plug in instances of all fields alongside with the save(), in order to make the changes after setting is_approve to True. -
How to handle concurrency with django queryset get method?
I'm using django (1.5 with mysql) select_for_update method for fetching data from one model and serve this data to user upon request, but when two user request at simultaneously it returns same data for both of the user, see the sample code below class AccessCode(models.Model): code = models.CharField(max_length=10) state = models.CharField(max_length=10, default='OPEN') def fetch_available_code(self): with transaction.commit_on_success(): qs = self.select_for_update().filter( state='OPEN').order_by('id') if qs: return qs[0] else: return None Please guide how to handle this scenario in better way -
How do I solve the error: error: (-27) The matrix has NULL data pointer in function cvGetMat in my opencv function?
To give some background on the problem I am trying to deploy my django project to a microsoft azure server. My django project is mainly dealing with executing opencv functions. I made sure to test that all my opencv functions worked on my local host which they do but the main problem I'm having is getting them to work on an azure server. Everytime I try to call any opencv function I get the error:The matrix has NULL data pointer in function cvGetMat in my opencv function. I have tried googling the problem and have narrowed it down to my frame variable inside my function that is causing the problem. The stack trace has pointed out that the function keeps failing at this line: cv2.imshow('frame',gray). The full function is just a basic opencv function to play a video. The code is below: def PlayVideo(request): filename="app/media/traffic.mp4" cap = cv2.VideoCapture(filename) while(cap.isOpened()): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame',gray) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() return render_to_response('app/Configuration.html') When I first encountered this problem I thought it may have been that it could not find the video file but I've modified the code with different paths that would not … -
Django store aggregated data in the database?
I have a use case where I have some complex functions (involving aggregations) that take a few seconds to run, and are affecting the UX of the app (even when the rows are just about 25-30k and the relevant fields are indexed). I am thinking of storing the aggregations in the database itself (and run them nightly) since real-time-liness of the data is not very important here. Is that a common practice with Django? (I couldnt find much discussion on that on SO though) -
Error sum in sql request
I have model: class Sales(ModelWithCreator, models.Model): date = models.DateField(default=datetime.date.today) merchandise = models.ForeignKey(Merchandise) partner = models.ForeignKey(Partner) count = models.PositiveIntegerField() debt = models.PositiveIntegerField(default=0) price = models.PositiveIntegerField() cost = models.PositiveIntegerField() I have to get sum of all objects that model. I tried that: Sales.objects.all().extra(select={ 'total': 'Sum(price * count - cost)' }) But, I got error: column "sales_sales.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT (Sum(price * count - cost)) AS "total", "sales_sales"... -
Downloading a file from S3 using Boto3 in django
I want to download a file from my django application, for which i have written following code, but the file that is getting downloaded is just 4 bytes but actual is 456 kb in size. please correct me if am doing anything wrong ! #My django view that is written for downloads @login_required def large_file_download(request, slug): current_user = request.user print slug try: doc = Document.objects.get(slug=slug, file_delete=False) except ObjectDoesNotExist : return render(request, 'phoenix_app/file_404.html', status=404) if doc.owner == current_user: file_hash = doc.chash_address file_type = doc.file_type s3_client = boto3.client( 's3', aws_access_key_id= aws_settings.STORAGE_BACKEND['location']['AWS_AKey'], aws_secret_access_key= aws_settings.STORAGE_BACKEND['location']['AWS_SKey'], region_name= aws_settings.STORAGE_BACKEND['location']['AWS_RName'], ) file_data=s3_client.download_file(aws_settings.STORAGE_BACKEND['location']['AWS_BName'], file_hash, doc.file_name ) response = HttpResponse(file_data, content_type=file_type) response['Content-Disposition'] = 'attatchment; filename={}'.format(doc.file_name) return response else: return render(request, 'phoenix_app/invalid.html', status=403) #urls : from . import views from django.conf.urls import include, patterns, url urlpatterns = [ url(r'^dashboard/large_file_download/(?P<slug>[\w-]+[\w-]+)$', views.large_file_download, name='large_file_download'), ] -
Django AbstractUser doesn't show model
I'm a django beginner and i want to add a booleanfield to AbstractUser, but it's not showing the booleanfield in the admin. models.py class CustomUser(AbstractUser): selected = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['selected',] def __str__(self): return self.username admin.py admin.site.register(CustomUser, UserAdmin) settings.py AUTH_USER_MODEL = 'football_app.CustomUser' -
Why should we NOT use the default django project layout?
-THE STORY- So, I am currently working on my next application to take over the world. By the way its the first one I'm doing using django. I have gotten far into making the app and I was just about to start adding logos, buttons and etc. I now find myself encountering the STATIC_FILES part of django. Since my app will destroy everything and march its ad revenue all over the world I wanted to have great scale ability and and hopefully use a CDN in production. So, I make my way over to djangos documentation and notice a entire world of complicated stuff smacks me in the face and knocks my project back to django-admin startproject [name].(It really did not all my models are OK and such I just need to set up static files and fix my templates, urls and etc). Thats right, I made a 10 app web application with templates, views, urls and all done(ish) in the default layout provided by django. THE "PROBLEM" The reason I find myself re-making the project is because it seems I "need" to have a lot of fancy things in my project model to make an app that takes over … -
Environment variables in virtualenv through activate script with gunicorn & supervisor
My project is based on Django, Nginx, Gunicorn and Supervisor in a Virtual env. I export environmental variables at the end of the ./bin/activate script. Whenever I source the activate file, it exports environmental variables. It's pretty cool... My issue comes when I start the Supervisor script. It seems that the ./bin/activate isn't sourced as Django can't get vars such as SECRET_KEY. I heard people using a post-activate script which isn't present in my virtualenv bin dir. Am I missing something important? Why Supervisor doesn't source the ./bin/activate script? Here is my supervisor conf: command=/opt/.virtualenvs/plcweb/bin/gunicorn plcweb.config.wsgi -c /opt/plcweb/gunicorn.conf.py directory=/opt/plcweb/project user=bastien autostart=true autorestart=true redirect_stderr=True stdout_logfile=/opt/plcweb/gunicorn.log stderr_logfile=/opt/plcweb/gunicorn.log -
NoReverseMatch at /blog/2017/04/27/test_asset-purchase_2/
My first project of Django and following the book "Django by Example", i had made a html page to list all the posts i had created, and this page worked well, but if i click into anyone of the the post error occured! I had check my code with the book and found nothing different. I am so confused, please give me some help! Error Message: NoReverseMatch at /blog/2017/04/27/test_asset-purchase_2/ Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P<post_id>\\d+)/share/$'] Request Method: GET Request URL: http://127.0.0.1:8000/blog/2017/04/27/test_asset-purchase_2/ Django Version: 1.11 Exception Type: NoReverseMatch Exception Value: Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P<post_id>\\d+)/share/$'] Exception Location: E:\workspace\pycharm\djangobyexample\mysite\env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 497 Python Executable: E:\workspace\pycharm\djangobyexample\mysite\env\Scripts\python.exe Python Version: 3.5.2 Python Path: ['E:\\workspace\\pycharm\\djangobyexample\\mysite', 'E:\\workspace\\pycharm\\djangobyexample\\mysite\\env\\Scripts\\python35.zip', 'E:\\workspace\\pycharm\\djangobyexample\\mysite\\env\\DLLs', 'E:\\workspace\\pycharm\\djangobyexample\\mysite\\env\\lib', 'E:\\workspace\\pycharm\\djangobyexample\\mysite\\env\\Scripts', 'c:\\users\\richard\\appdata\\local\\programs\\python\\python35\\Lib', 'c:\\users\\richard\\appdata\\local\\programs\\python\\python35\\DLLs', 'E:\\workspace\\pycharm\\djangobyexample\\mysite\\env', 'E:\\workspace\\pycharm\\djangobyexample\\mysite\\env\\lib\\site-packages'] Models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.core.urlresolvers import reverse class PublishedManager(models.Manager): def get_query(self): return super(PublishedManager, self).get_query().filter(status='published') class Post(models.Model): STATUS_CHOICES = { ('draft', 'Draft'), ('published', 'Published'), } title = models.CharField(max_length=250, primary_key=True) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_post') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: # Telling django to … -
dajngo rest framework - filtering against date query parameter
In my view I'm receiving date parameter and I'm filtering against it so I could show my contact for today, and it goes something like this: filter_date = self.request.query_params.get('filter_date', None) for queryset in contact_lead: if filter_date is not None: queryset = queryset.filter(next_action_date__gte=filter_date) return queryset Like I said with this I can see my contacts for today, but there are some contact that are made in the past, now because datepicker have past dates restriction I can not see them and I want all my past contact to appear today, or any other day in the future, so the point is I don't want contact which are created in the past to be left behind, so can someone help me and explain how can I get that result. -
Django cache loses keys
I have a Django installation that uses the FileSystem caches. The caching system is used by an array of different views. Putting in place various logs to log when a key is not found in the cache and hence regenerated, I've found out that often the keys are lost. I don't have any "cache delete" in place and all the keys are stored to last 24 hours, but in the logs they all appear to be regenerated once in a while. Is there any hidden parameter like "don't store more than n keys" or "more than n megabytes of data" or something? I'm a bit lost because it just seems that the keys are lost and I don't know when and why. Also, I originally chose as cache location "/tmp/django-cache", so I thought that maybe the tmp directory was being cleaned by Linux, but changing the location to a "safer" one in my home directory doesn't change the anomaly. Also, the full cache directory is around 25Mb, so I don't think there is something cleaning it up because it's too big. Any idea? -
After fresh install of django 1.11 and mysql-connector-python migrations fail to run. How can I resolve
I installed on ubuntu 16.04 django 1.11 usinf pip3 and then installed the oracle mysql-connector-python. Why is this error occurring? How can I resolve it? According to the tutorial migrations will run even if there are no models defined. Installed by using pip3 pip3 install --egg http://dev.mysql.com/get/Downloads/Connector-Python/mysql-connector-python-2.1.6.zip My database configuration DATABASES = { 'default': { 'NAME': 'user_data', 'ENGINE': 'mysql.connector.django', 'USER': 'mysql_user', 'PASSWORD': 'priv4te', 'OPTIONS': { 'autocommit': True, }, } } The command that I ran python3 /home/django/workspace/mysite/manage.py migrate The Error Traceback (most recent call last): File "/home/django/workspace/mysite/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/django/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/django/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/home/django/.local/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/django/.local/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/home/django/.local/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/django/.local/lib/python3.5/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/django/.local/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): … -
I am getting MultiValueDictKeyError while editing the existing data and saving it in django admin?
I can be able to add the first data entry but after that editing the existing data or adding the new data causes MultiValueDictKeyError at /admin/api/digitalpost/9b763eae-cb8b-4473-af5d-5d4d91323ae1/change/ "u'contentlist_set-0-basemodel_ptr'". Models.py class BaseModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) version = models.FloatField(default=1.0) created_at = models.DateTimeField(auto_now_add=True) def image_tag(self): self.url = 'http://127.0.0.1:8000/' + self.picture.name return u'<img src="%s" />' % self.picture.url image_tag.short_description = 'Thumbnail' image_tag.allow_tags = True class Client(BaseModel): parent = models.ForeignKey('self',on_delete=models.SET_NULL, blank=True, null=True, related_name='brands') name = models.CharField(max_length=120, unique=True) picture = models.ImageField(upload_to="static/images/digital") list_display = ('name','parent',) description = models.CharField(max_length=250) def __unicode__(self): if self.parent: return "{} {}".format(self.parent.name, self.name) else: return self.name def parent_brand(self): return str(self) parent_brand.short_description = 'NAME' class Meta: ordering = ['parent__name','name'] class Category(BaseModel): title = models.CharField(max_length=64, unique=64) description = models.CharField(max_length=256, null=True, blank=True) def __unicode__(self): return self.title class Meta: ordering = ['-created_at'] verbose_name_plural = "categories" class DigitalPost(BaseModel): title = models.CharField(max_length=100) brand = models.ForeignKey(Client, on_delete=models.SET_NULL, blank=True, null=True, ) launch_date = models.DateField(blank=True, null=True) order = models.IntegerField() def __unicode__(self): return self.title class Meta: ordering = ['order'] class ContentList(BaseModel): title = models.CharField(max_length=100) description = models.CharField(max_length=256, null=True, blank=True) picture = models.ImageField(upload_to="static/images/digital", blank=True) post = models.ForeignKey(DigitalPost, on_delete=models.SET_NULL, null=True, blank=True) # post_category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) def __unicode__(self): return self.title class Meta: ordering = ['title'] admin.py class ContentListInline(admin.TabularInline): model = models.ContentList form = ContentListForm fk_name … -
Update sqlite database based on changes in production
I am deploying a Django App using Elastic Beanstalk on AWS. The app has a function whereby user can register their details. The problem is when I make small changes to my app and deploy this new version I loose the registered users since their information isn't in my local database (only the database on aws). Is there any way to download the modifications to the database during production so that I can keep these changes when I redeploy. I'm not using AWS RDS, I simply bundle the .SQLite file with my source code and deploy to Elastic Beanstalk. Thanks in Advance. -
Why the form has extraneous text?
Can someone say how to fix next little bag? I edit/update object data(in my case purpose data) by AJAX and then save it. I use Modal form to edit object. AJAX update works fine but I see the text inside comment form as in the picture below after successfull editing. Why? Why $("#purpose-comment-form")[0].reset(); didnt work? project_detail.html: <div class="card"> <div class="card-header"> <div class="d-flex align-items-center justify-content-between purpose-top"> {% include 'project/purpose_top.html' %} </div> </div> <div class="card-block"> <div class="collapse purpose-block" id="collapse-purpose"> {% include 'project/purpose_list.html' %} </div> </div> </div> purpose_list.html: <div class="list-group" id="purpose-list"> {% for purpose in purposes %} <div class="list-group-item flex-column align-items-start custom-list-group-item"> <div class="d-flex w-100 justify-content-start"> <p>{{ purpose.text }}</p> </div> <div class="comment-list-block"> <div class="list-group custom-list-group"> <div class="list-group-item bg-faded"> {% include 'project/purpose_comment_form.html' %} </div> <div class="purpose-comments"> {% include 'project/purpose_comment_list.html' %} </div> </div> </div> </div> {% endfor %} </div> purpose_comment_form.html: <form method="post" class="purpose-comment-form" id="purpose-comment-form"> <!--SOME HTML--> </form> js: $(function () { var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal").modal("show"); }, success: function (data) { $("#modal .modal-content").html(data.html_purpose_form); } }); }; var saveForm = function () { var form = $(this); $("#purpose-comment-form")[0].reset(); //??? $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: …