Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Inline Admin Models - Image cropping
Which library should I use for cropping image in django admin inlines. I tried with django-imagekit-cropping but cant get anything.Can anyone suggest any library or demo? -
'WebSocketProtocol' object has no attribute 'application_queue' error Django Channels
In my Django project i want to create a chat app using channels.But when i followed this tutorial https://channels.readthedocs.io/en/stable/tutorial/part_2.html, i had a problem that websocket auto disconnect after connect : Exception in callback AsyncioSelectorReactor.callLater..run() at C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\twisted\internet\asyncioreact or.py:287 handle: .run() at C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\twisted\interne t\asyncioreactor.py:287> Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\asyncio\events.py", line 145, in _run self._callback(*self._args) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\twisted\internet\asyncioreactor.py", line 290, in run f(*args, **kwargs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\twisted\internet\tcp.py", line 289, in connectionLost protocol.connectionLost(reason) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\autobahn\twisted\websocket.py", line 128, in connectionLost self._connectionLost(reason) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\autobahn\websocket\protocol.py", line 2467, in _connectionLost WebSocketProtocol._connectionLost(self, reason) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\autobahn\websocket\protocol.py", line 1096, in _connectionLost self._onClose(self.wasClean, WebSocketProtocol.CLOSE_STATUS_CODE_ABNORMAL_CLOSE, "connection was closed uncleanly (%s)" % self.wasNotCleanReason) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\autobahn\twisted\websocket.py", line 171, in _onClose self.onClose(wasClean, code, reason) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\daphne\ws_protocol.py", line 146, in onClose self.application_queue.put_nowait({ AttributeError: 'WebSocketProtocol' object has no attribute 'application_queue' -
Django+Nginx gives 404 while serving static files
I have been stuck with this for almost five hours now. Whenever I load my site it gives me a 404 error while loading the images and css. My nginx config: server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name _; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/django_project/django_project/media; } # your Django project's static files - amend as required location /static/ { alias /home/django/django_project/csite/static/csite/; autoindex on; } # Proxy the static assests for the Django Admin panel location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_buffering off; proxy_pass http://app_server; } } My settings.py: STATIC_ROOT = os.path.join(BASE_DIR, "csite/static") STATIC_URL = '/static/' You can view the directory structure here -
Problems uploading files to Amazon s3 bucket from a website on heroku
Im in the process of moving my Django website to Heroku. But I can’t figure out how to use Heroku with Amazon s3 buckets. Previously I used to save all uploaded files in the project, but I can’t do that using Heroku. I have been following the documentation on Heroku: https://devcenter.heroku.com/articles/s3 and https://devcenter.heroku.com/articles/s3-upload-python The bucket is located in Frankfurt. When uploading a file I get the following error: <Error> <Code>InvalidArgument</Code> <Message>a non-empty Access Key (AKID) must be provided in the credential.</Message> <ArgumentName>X-Amz-Credential</ArgumentName> <ArgumentValue>/20180502/eu-central-1/s3/aws4_request</ArgumentValue> … </Error> I have specified the keys in Heroku like this: "heroku config:set AWS_ACCESS_KEY_ID=xxx AWS_SECRET_ACCESS_KEY=yyy" You can go to https://eventcollective.herokuapp.com/accounts/account/ and try to upload an image. from views.py def sign_s3(request): S3_BUCKET = os.environ.get('S3_BUCKET') print(S3_BUCKET) file_name = request.GET.get('file_name') file_type = request.GET.get('file_type') s3 = boto3.client('s3', region_name='eu-central-1') presigned_post = s3.generate_presigned_post( Bucket=S3_BUCKET, Key=file_name, Fields={"acl": "public-read", "Content-Type": file_type}, Conditions=[ {"acl": "public-read"}, {"Content-Type": file_type} ], ExpiresIn=3600 ) return HttpResponse(json.dumps({ 'data': presigned_post, 'url': 'https://%s.s3.amazonaws.com/%s' % (S3_BUCKET, file_name) })) Do you have any idea on how to resolve this? -
gunicorn: Is there a better way to reload gunicorn in described situation?
I have a django project with gunicorn and nginx. I'm deploying this project with saltstack In this project, I have a config.ini file that django views read. In case of nginx, I made that if nginx.conf changes, a state cmd.run service nginx restart with - onchanges - file: nginx_conf restarts the service. but in case of gunicorn, I can detect the change of config.ini, but I don't know how to reload the gunicorn. when gunicorn starts, I gave an option --reload but does this option detects change of config.ini not only django project's files'? If not, what command should I use? (ex: gunicorn reload) ?? thank you. ps. I saw kill -HUP pid but I think salt wouldn't knows gunicorn's pid.. -
Django application high disk IOPS on EC2
I am having sudden increases of high Disk IOPS on my EC2 instances. They are all running a Django 1.9.6 web application on it. The apps installed on it are Apache, Celery, New Relic Agent and Django Wsgi itself. The application does not do any disk operations as such. Data is stored on RDS and Redis (Another server). The static files are stored on S3 and connected to cloudfront. So I am unable to determine what is the cause of this high Disk IOPS. What happens is a normal request suddenly takes forever to respond. On checking cloudwatch and new relic I see the RAM usage shoots up. Then the instance is unresponsive. All requests time out and can't SSH in. When I contacted AWS Support they said the VolumeQueueLength was increasing significantly and once it came down (15-20 mins later) the instance was working fine. Any ideas as to what could be the issue? -
IntegrityError after table restore from backup, PostgreSQL + Django
I am trying to restore a table in my database from some db backups. The backup is created via pgAdmin 4 UI tool, select a table and next backup it. And here is the command that pgAdmin executes: --file "C:\\Users\\cchie\\DOCUME~1\\DB_BAC~1\\CURREN~1" --host "localhost" --port "5432" --username "postgres" --no-password --verbose --format=c --blobs --table "public.cosmetic_crawler_currency" "last_cosmetics" The problem is that I have an AutoField in that table and when I restore a table, and next try to add new items into it - I have errors like this: psycopg2.IntegrityError: duplicate key value violates unique constraint "cosmetic_crawler_product_pkey" DETAIL: Key (product_id)=(27) already exists. The above exception was the direct cause of the following exception: django.db.utils.IntegrityError: duplicate key value violates unique constraint "cosmetic_crawler_product_pkey" DETAIL: Key (product_id)=(27) already exists. As I understand - that means that PostgreSQL server does not know that I have restored the AutoField counter and tries to count from 0? Is there a way to fix that and make it count from the last number? P.S. Restoring process is the same as backuping - manually in pgAdmin UI. -
Django how to upload file directly to 3rd-part storage server, like Cloudinary, S3
Now, I have realized the uploading process is like that: 1. Generate the HTTP request object, and set the value to request.FILE by using uploadhandler. 2. In the views.py, the instance of FieldFile which is the mirror of FileField will call the storage.save() to upload file. So, as you see, django always use the cache or disk to pass the data, if your file is too large, it will cost too much time. And the design I want to figure this problem is to custom an uploadhandler which will call storage.save() by using input raw data. The only question is how can I modify the actions of FileField? Thanks for any help. -
Django 1.11: What fails pickle in my parallel test run?
I'm on a dockerized Django 1.11 and want to run my longstanding test suite parallel now: manage.py test mainfolder --parallel -v2 Though it fails 2 minutes into my test suite (after all so-far run tests succeeded) with a pickle error. The stack trace however does not give me an indication where it occurs. How could I get closer to what fails it? tblib is installed. test_foo (myapp.some.testmodule.SomeTestCase) ... ok Traceback (most recent call last): File "./myapp/manage.py", line 34, in <module> execute_from_command_line() File "/var/venv-stable/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/var/venv-stable/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/venv-stable/lib/python2.7/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/var/venv-stable/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/var/venv-stable/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/var/venv-stable/lib/python2.7/site-packages/django/core/management/commands/test.py", line 62, in handle failures = test_runner.run_tests(test_labels) File "/var/venv-stable/lib/python2.7/site-packages/django/test/runner.py", line 603, in run_tests result = self.run_suite(suite) File "/var/venv-stable/lib/python2.7/site-packages/django/test/runner.py", line 567, in run_suite return runner.run(suite) File "/usr/lib/python2.7/unittest/runner.py", line 151, in run test(result) File "/usr/lib/python2.7/unittest/suite.py", line 70, in __call__ return self.run(*args, **kwds) File "/var/venv-stable/lib/python2.7/site-packages/django/test/runner.py", line 370, in run subsuite_index, events = test_results.next(timeout=0.1) File "/usr/lib/python2.7/multiprocessing/pool.py", line 659, in next raise value cPickle.PicklingError: Can't pickle <type 'module'>: attribute lookup __builtin__.module failed -
How to prevent admin emails for SuspiciousOperation errors
My Django application throws a lot of SuspiciousOperation error, for which the admins receive an email: SuspiciousOperation at /api/rest-auth/logout/ The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. There is nothing suspicious about this. It started happening when we introduced a auto logout timeout functionality, so now when multiple requests come in from the same user, and the auto logout timeout is reached, this error happens. Not always, but quite frequently. Is there a way of preventing this error, or at least preventing the email. I found that the code that generates the error comes from process_response in the django.contrib.sessions.middleware.SessionMiddleware, so I was thinking of overriding the the whole middleware class, and removing the line that produces the error, but it seems like an overkill. -
Django cannot configure MySQL in RHEL 7
I am a newbie with Red Hat 7 and trying to configure MySQL instead of default sqlite3 in my django project. I successfully installed MySQL which can be seen below. [user@user111 django-project]$ mysql --version mysql Ver 14.14 Distrib 5.7.22, for Linux (x86_64) using EditLine wrapper [user@user111 django-project]$ which mysql /usr/bin/mysql [user@user111 django-project]$ mysql -u root -p Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 16 Server version: 5.7.22 MySQL Community Server (GPL) Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> Now I want to configure Django with MySQL so I tried to install mysqlclient [user@user111 django-project]$ pip3 install mysqlclient Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/6f/86/bad31f1c1bb0cc99e88ca2adb7cb5c71f7a6540c1bb001480513de76a931/mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-zn7_jg6q/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/tmp/pip-build-zn7_jg6q/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/tmp/pip-build-zn7_jg6q/mysqlclient/setup_posix.py", line 26, in mysql_confi[user@user111 django-project]$ g … -
Django Channels Background Worker Instances
I am working on a Django Channels-2 project, where channel layer is used to offload information from browsers to a consumer who analyses it and send the results back to the Browsers via groups mechanism. The data comes from pusher via a pusher-client, and is therefore the same for many client browsers. My first took was to set-up the following infrastructure: layout 1: (browser1: Pusher-client, websocket; ... browserN: Pusher-client, websocket) <----> WebsocketConsumer(member of group; sends to channel, recieves from group) <----> BackgroundWorker(listens on channel; sends to group) This layout works fine and it offloads the need to burden my server with the pusher connection, which is left to individual browsers. But this also means that I propagate multiple copies of the same event down to my Worker. I understand there are solutions to this problem, but they seemed a bit awkward to me. Also, this implies a lot of JavaScript-ing in the browsers. Even more so since only one websocket connection is permitted per browser tab and I need to traffic everything trough the same socket. Therefore I use the following set-up now: layout 2: (browser1: websocket; ... browserN: websocket) <----> WebsocketConsumer(member of group; sends to channel, recieves from group) … -
how to access a file from root of django project
I have a .html file. I want to access file like this (http://my_site_name.com/somefile.html) from my Django website. I do not want to use static folder. thanks -
Integrating cryptoassets.core library with django
I am trying to integrate cryptoasstes.core library in django project using the following link :- https://pypi.org/project/cryptoassets.django/ To start helper service i am using the command below :- python3 manage.py cryptoassets_helper_service getting following error on running the command :- ImportError: No module named 'cryptoassets.core.backend.sochainwalletnotify' Please suggest how to configure these upcoming transactions. Or any other link to integrate this library in Django. Here is my settings.py file :- """ Django settings for crypto project. Generated by 'django-admin startproject' using Django 2.0. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'll8(-7j1l%$xmr269^s1%k(wkdki72zd=ngg@$mnr5-ac!%_8-' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cryptoassets.django', 'cryptoassets.core', 'django_bitcoin' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'crypto.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': … -
why laravel application dont need application server and django application needs one?
Why Laravel application don't need any application server to configure , but for Django application i have to set up uWSGI or gunicorn with Nginx. Laravel application directly handled by Nginx or Apache web server, but for Django application I have to configure application server also. -
Using 'a href' how to update url without refreshing page and save the page for back button
Problem statement : A Form is divided into no. of sections. Header is fixed only some part of html need to update on click of a button. Here are the things that i want to do using 'a href'. update part of html and url without refreshing page. open entire html when direct enter the url. able to go back to previous state on back press. Please help me. Thanks in advance. -
Django: add fields of the related model (ForeignKey) in the form
I have main model Entertainment and related model EntertainmentCollage. Now i'm doing edditing page for my models in which I will need to transfer for editing both models. I understand how to transfer one form to the form but with a related model I have difficulty. class Entertainment(models.Model): main_photo = models.ImageField(upload_to = 'where/') place = models.CharField(max_length=200) description = models.CharField(max_length=200) event_date = models.DateTimeField(auto_now_add=False, blank=True, null = True) class EntertainmentCollage(models.Model): img = models.ImageField(upload_to = 'entertainment/portfolio', blank = True) album = models.ForeignKey(Entertainment, blank = True, null = True) forms.py class WhereCreateForm(ModelForm): class Meta: model = Entertainment fields = ['main_photo','place','description', 'event_date' ] views.py def edit_where(request, pk): place = Entertainment.objects.get(id=pk) form = WhereCreateForm(instance=place) if request.user.is_authenticated(): if request.method == "POST": form = WhereCreateForm(request.POST, request.FILES, instance=place) if form.is_valid(): form.save() return redirect('entertainment:where_list') else: form = WhereCreateForm() return render(request, "entertainment/where_edit.html", {'form': form}) html <form method = "post"> {% csrf_token %} <p>{{ form.description }}</p> <p>{{ form.place }}</p> <p>{{ form.event_date }}</p> </div> <div class="col-md-9"> <section class="admin-section"> <div class="row"> <div class="col-md-4 admin__block" is-cover="false"> <div class="cover__wrapper edit__wrapper"> <a class="delete-button">Delete</a> <a class="make-cover-button">Cover</a> <img src="img/place-placeholder-1.jpg" alt=""> </div> </div> </div> <a href="#" class="button">Add photo</a> </section> <section> <h4>Description</h4> {{ form.description }} <a href="#" class="button">Save</a> <a href="#" class="button">Cancel</a> </section> </form> -
Multiple formsets only saves the number of formsets in 'extra' attribute: Why?
Short version: Creating dynamically multiple formsets only saves as much formsets specified in extra attribute instead of as many as I've. Long version: I'm doing my first project with Django and I've to create a CreateView with a Parent and a Child forms. I need to create as many nested Child forms the user wants, so I've created a small code in Javascript that adds/removes the child forms. This is working fine. The problem is: I can only save as many forms as I've specified in the extra attribute. If I say '3', it creates 3 Child forms and I can save 3 of them, even if I create/remove Child forms. If I say '1', I can create 10, but only will save 1. Seems like I'm missing something in the template, but I don't know what. Here's the relevant code: forms.py class ParentForm(ModelForm): class Meta: model = Parent exclude = () class ChildForm(ModelForm): class Meta: model = Child fields = .... ChildFormSet = inlineformset_factory(Child, Child, form=ChildForm, can_delete=True, extra=1) views.py class ParentCreateView(LoginRequiredMixin, CreateView): model = Entrada fields = ... def get_context_data(self, **kwargs): data = super(ParentCreateView, self).get_context_data(**kwargs) if self.request.POST: data['child_form'] = ChildFormSet(self.request.POST) data['materials'] = Material.objects.all() else: data['child_form'] = ChildFormSet() data['materials'] = … -
Django: get unique together fields and count how many times they appear in a table
I am trying to create a trip monitoring app whereas each trip is given a ticket and particular origin and destination. What I want to do now is that given a date range, I would like to know how many trips are made for the unique origin-destination pair. I have not found solutions to this yet and I'm hoping that somebody could enlighten me on this. Here is my models: class Location(models.Model) name = models.Charfield(max_length=50, unique=True) ... class Trip(models.Model): ticket = models.PositiveIntegerField(primary_key=True, blank=False, null=False) origin = models.ForeignKey(Location, on_delete=models.CASCADE) destination = models.ForeignKey(Location, on_delete=models.CASCADE) ... I am expecting the following output which I currently don't know what to do: Origin | Destination | Number of Trips Place #1 | Place #2 | 5 Place #2 | Place #1 | 3 Place #3 | Place #1 | 8 Place #3 | Place #2 | 1 -
Django rest update one field
I just got started with Django and got stuck on something that I believe should be simple, but I don't know how to do. I have a model like this one: id = models.AutoField(primary_key=true) ... amount = models.IntegerField() ... Basically, the user will give an amount and the model needs to be updated with the current amount + the amount that the user inputs. I use serializers to create new objects, but I don't really know how to use them to do this. -
static css file not loaded in django
Help with 404 error please. The image and js files load well but not the css file. I don't know why. My project structure: --project ----templates ----project ------urls.py ------settigns.py ----app ----static ------css ------js ------images --media --static (after collectstatic command) Settigns.py include 'django.contrib.staticfiles' settings.py BASE_DIR = os.path.abspath(os.path.dirname(__file__)) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static") urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) base.html {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'css/design.css%' %}"/> <img src="{% static 'images/slide1.jpg' %}"> -
Django storages S3: delay in webserver response
I just migrated a large existing website to a new storage backend S3. I started with static files only, but I have a major issue that I cannot debug: My setup is: settings.py from myapp.aws.conf import * STATIC_URL = S3_URL + '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') aws/conf.py AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' AWS_FILE_EXPIRE = 200 AWS_PRELOAD_METADATA = False AWS_QUERYSTRING_AUTH = False STATICFILES_STORAGE = 'appname.aws.utils.StaticRootS3BotoStorage' AWS_STORAGE_BUCKET_NAME = 'bucketname' S3DIRECT_REGION = 'eu-central-1' S3_URL = 'https://s3.eu-central-1.amazonaws.com/{}/'.format(AWS_STORAGE_BUCKET_NAME) aws/utils.py from storages.backends.s3boto3 import S3Boto3Storage StaticRootS3BotoStorage = lambda: S3Boto3Storage(location='static') If I open a url for the first time it takes up to 60 seconds until django begins (!) serving the page. During this time there is absolute silence in the logs. Increasing verbosity does not help. If I reload the same page with cmd+F5 django starts serving immediately. Storages is something doing in the back, no verbosity at all. Can anybody shed some light on whats happening here? -
Django channels install failure in Windows 10
Here is the environment: OS:windows 10 Django:2.0rc Python:3.6 pip:10.0.0 visual studio community 2017 And the error message: running build_ext building 'twisted.test.raiser' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools Command "c:\users\airy\appdata\local\programs\python\python36\python.exe -u -c "import setuptools, tokenize;file='C:\Users\Airy\AppData\Local\Temp\pip-install-0a1gjuaj\twisted\ setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\Airy\AppData\Local\Temp \pip-record-k1vjz5aa\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\Airy\AppData\Local\Temp\pip-install-0a1gjuaj\twisted\ I had already install the build tools following the link desrcption but it still dosen't work,if someone had solved it please tell me how to fixed it QAQ -
Modal body not visible
I'm designing a form inside 'modal` body. When I click the button the modal appears but only header is visible, body is not visible. It was working fine for previous form that i designed using same method but now it's not working. I'm making an ajax request to show the modal: function update_detail(id) { var id=id $.ajax({ url: "{% url 'bms:index' %}", type: "POST", data:{ 'csrfmiddlewaretoken': '{{ csrf_token }}', 'id': id, }, success: function(response){ $(".response").html(response.template) $("#editform").modal("show"); } }); } This is my form: <form action="" id="editform" name="updateform" method="POST"> {% csrf_token%} <div class = "form-group"> <label for = "your_name"> Your name: </label> <input class = "form-control" id="new_name" type = "text" name="name" value="" placeholder="Enter your name"> </div> <div class="form-group"> <label for = "course_name"> Course: </label> <input id="new_course" class = 'form-control' type = "text" name="course" value="" placeholder="Enter your course"> </div> <div class = "form-group"> <label for = "rollno"> Roll No.: </label> <input id="new_rollno" type = "text" class = 'form-control' name="roll" value="" placeholder="Enter your roll number"> </div> <div class = "form-group"> <label for ="addr"> Address: </label> <input id="new_address" type = "text" name="address" class = 'form-control' value="" placeholder="Enter your address"/> </div> <input type = "submit" value="Update" id="update" class = "btn btn-success" style="font-size:18px;" /> </form> Which … -
django: fill checkbox based on url params
i am having a form with only checkboxes: <div class="container"> <form method="GET" class="form-inline" action=""> <div> {% for temp in instance.menu_positions_tags.all %} <label class="checkbox-inline"> <input type="checkbox" name="tags[]" value="{{ temp.name}}">{{ temp.name }} </label> {% endfor %} </div> <div style="margin-top:10px"> <button type="submit" class="btn btn-default">Submit</button> </div> </form> </div> When i select few checkboxes and submit the url changes to localhost/test/?tags[]=day4&tags[]=day2. After the page loads the all checkboxes are unselected. Now, how to, in my form make day4 and day2 checkboxes checked.