Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django query parameters: MultiValueDictKeyError - Key not found in QueryDict
I have a simple webpage with a single link, index.html: <a href='/dog/?owner=' + data['owner'] + '&breed="bulldog"'>Dog</a> Here data is passed dynamically via the server. urls.py has the method definition to call: ... url(r'^dog/$', TemplateView.as_view(template_name='dog.html'), name='dog'), url(r'^ajax/dog/$', views.dog, name='ajax/dog'), ... And my views.py has the method defined: def dog(request): owner = request.GET['owner'] LOG.info(owner) breed = request.GET['breed'] LOG.info(breed) ... I get the following error when I click the link in index.html: ... File "/mnt/virtualenv/local/lib/python2.7/site-packages/django/utils/datastructures.py", line 295, in __getitem__ raise MultiValueDictKeyError("Key %r not found in %r" % (key, self)) MultiValueDictKeyError: "Key 'breed' not found in <QueryDict: {u'owner': [u'kevin_lawder']}>" I'm really confused as to why one query parameter is present in the QueryDict dictionary and the other is not. I tried replacing request.GET['breed'] with request.GET.get('breed') but that returns None. What am I missing here? -
django database routing: automatic failover?
I have an application written in a Django framework that draws off a PostgreSQL database. Because we're very sensitive of downtime and redundancy, the database uses streaming replication to two hot-standby servers. However, as it currently stands when the master DB goes down I have to manually change the database server address in settings.py for Django to switch over. I'm not terribly familiar with Django database routing yet, so I'm not sure how to go about it, but would it be possible to configure all three databases in Django to have the routing layer determine which one of them is currently the active master and route its queries accordingly? -
Ensure that there are no more than 3 digits before the decimal point error when submitting a form
I am getting the error "Ensure that there are no more than 3 digits before the decimal point" when I am trying to submit a modal form. How can I fix it? my model: class Product(models.Model): quantity = models.DecimalField( "Quantity", max_digits=8, decimal_places=2, default=0) retail_price = models.DecimalField( max_digits=10, decimal_places=2, default=0, blank=True) purchase_price= models.DecimalField( max_digits=8, decimal_places=2, default=0, blank=True) timi_xondrikis = models.DecimalField( max_digits=8, decimal_places=2, default=0, blank=True) my form: class ProductForm(ModelForm): class Meta: model = Product fields=('quantity','retail_price') Giving to price field 900 or 900.00 is acceptable but giving 1000 or 1000.00 which I want, is not. The thing is that i define my retail_price field to have max_digits=10. Why this happening? -
How to delete and update a table using a modal
I'm setting up a table that queries from my postgresql database, it displays the list of employees using a for statement on a bootstrap table. The table as an action column that Updates and Deletes from the database. Since I'm using a for statement to display all employees, I researched that ill need to use a for loop counter to enable the modal to update and delete. I've been having it difficult to even display the modal. I've Tried using a forloop counter and It seems not be responding. {% if employees %} <div class="row"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-striped custom-table datatable"> <thead> <tr> <th style="width:30%;">Name</th> <th>Employee ID</th> <th>Department</th> <th>Email</th> <th>Mobile</th> <th>Role</th> <th>Status</th> <th class="text-right">Action</th> </tr> </thead> {% for employee in employees %} <tbody> <tr> <td> <a href="profile.html" class="avatar">S</a> <h2><a href="profile.html">{{employee.last_name}} {{employee.first_name}} <span>{{employee.role}}</span></a></h2> </td> <td>{{employee.employee_id}}</td> <td>{{employee.department}}</td> <td>s{{employee.email}}</td> <td>{{employee.phone_number}}</td> <td>{{employee.role}}</td> <td> {% if employee.employment_status == 'Active' %} <span class="label label-success-border">Active</span> {% else %} <span class="label label-danger-border">Inactive</span> {% endif %} </td> <td class="text-right"> <div class="dropdown"> <a href="#" class="action-icon dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><i class="fa fa-ellipsis-v"></i></a> <ul class="dropdown-menu pull-right"> <li><a href="#" data-toggle="modal" data-target="#edit_employee_{{ forloop.counter }}"><i class="fa fa-pencil m-r-5"></i> Edit</a></li> <li><a href="#" data-toggle="modal" data-target="#delete_employee"><i class="fa fa-trash-o m-r-5"></i> Delete</a></li> </ul> </div> </td> </tr> </tbody> {% … -
Web interface for sockets operating python script
I am digging around the web and can't find anything. I am currently making a control panel for a python script I created. I basically I need a (locally hosted) page with bunch of buttons just triggering method (value). I do believe there is a really simple solution to my problem, but I can't find anything similar to my problem. I know that locally run app would be best, but I need the software to be accessible from a pc, as well as a mobile phone, both android and iOS. Is there a way to simply realtime display values from the script and trigger the methods without reloading the page everytime and without using js? It seems quite a simple task... Also, where should I really put the sockets script on the server? -
Django, nginx, how i can return another type of file?
I have django project,in this project i have static file, this file is exist in /media/ folder MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/' The file is exist by link https://supersite.com/apple-app-site-association but this file is has type application/octet-stream and i need return type application/pkcs7-mime; My nginx settings is contains location /media/ { autoindex on; alias /media/; default_type application/pkcs7-mime; } location /media/apple-app-site-association { autoindex on; default_type application/pkcs7-mime; } location = /media/ { autoindex on; default_type application/pkcs7-mime; } but return file still application/octet-stream. How i can change type of file on application/pkcs7-mime ? -
Unable save table after making changes in the model.py file
I am new to django any help would be much appreciated. I have installed the django-excel tutorial app and made changes to its model.py file. I have done the following steps : 1) python manage.py makemigrations polls Output : Migrations for 'polls': polls\migrations\0001_initial.py - Create model hpcl 2) python manage.py migrate polls output : Operations to perform: Apply all migrations: polls Running migrations: No migrations to apply. Model.py file from django.db import models class hpcl(models.Model): plannedPLT = models.IntegerField(default=0) pub_date = models.DateTimeField('date published') consumption = models.IntegerField(default=0) required_PLT = models.CharField(max_length=200) def __str__(self): return self.pub_date Request Method: POST Request URL: http://127.0.0.1:8000/polls/import/ Django Version: 2.2.1 Python Version: 3.7.3 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls') Installed Middleware: ('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') Traceback: File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py" in _execute 84. return self.cursor.execute(sql, params) File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 383. return Database.Cursor.execute(self, query, params) The above exception (no such table: polls_hpcl) was the direct cause of the following exception: File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\dhaval1.desai\Documents\Notes\Feedstock\Django-excelV2\django-excel-master\polls\views.py" in import_data 53. ['plannedPLT', 'pub_date', 'consumption', 'required_PLT'] File "C:\Users\dhaval1.desai\Documents\Notes\Feedstock\Django-excelV2\django-excel-master\django_excel\__init__.py" in save_book_to_database 63. pe.save_book_as(**params) File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel\core.py" in save_book_as … -
DatabaseError at /user/login_user/ This query is not supported by the database
DatabaseError at /user/login_user/ This query is not supported by the database. Request Method: POST Request URL: http://testapi.careeranna.in/user/login_user/ Django Version: 1.6.11 Exception Type: DatabaseError Exception Value: This query is not supported by the database. Exception Location: /var/live_code/backendCA/pyenv/local/lib/python2.7/site-packages/djangotoolbox/db/basecompiler.py in check_query, line 497 Python Executable: /var/live_code/backendCA/pyenv/bin/uwsgi Python Version: 2.7.15 Python Path: ['.', '', '/var/live_code/backendCA/pyenv/lib/python2.7', '/var/live_code/backendCA/pyenv/lib/python2.7/plat-x86_64-linux-gnu', '/var/live_code/backendCA/pyenv/lib/python2.7/lib-tk', '/var/live_code/backendCA/pyenv/lib/python2.7/lib-old', '/var/live_code/backendCA/pyenv/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/var/live_code/backendCA/pyenv/local/lib/python2.7/site-packages', '/var/live_code/backendCA/pyenv/lib/python2.7/site-packages', '/var/live_code/backendCA/'] Server time: Wed, 22 May 2019 12:04:50 +0530 -
How to filter queryset based on relate objects if it contains data in django
I want to filter and get only those data related to its related objects data if only related to its parent object child objects have data. For eg: I have the following models: class Collection(models.Model): date_of_collection=models.DateField() class Product(models.Model): name=models.CharField(max_length=100) collection = models.ForeignKey(Collection) class Price(models.Model): price = models.FloatField() products = models.ForeignKey(Products, on_delete=models.CASCADE) and i have data related to models as: Collection: +----+--------------------+ | id | date_of_collection | +----+--------------------+ | 1 | 2019-01-17 | | 2 | 2019-01-30 | | 3 | 2019-02-01 | | 4 | 2019-02-02 | +----+--------------------+ Products: +----+--------------------------------+ | id | name | collection | +----+--------------------------------+ | 1 | product 1 | 3 | | 2 | product 2 | 1 | | 3 | product 3 | 1 | | 4 | product 4 | 4 | +----+--------------------------------+ Price: | id | price | product | +--------+------------------+-----------------------+ | 1 | 10.00 | 1 | | 2 | 20.00 | 1 | | 3 | 12.00 | 3 | +--------+------------------+-----------------------+ here I have price related to only 1 and 3 product so I only want those products based on queryset that i only want to filter based on specific date_of_collection. I have tried the following queryset: collection_month = … -
the most popular words on the blog (scraped HTML) Rest API using Django Rest Framework and Docker
I want to build Rest API that collecting data from every article from the blog through scraping HTML. (the most popular words on the blog) Data should be collected by processing individual HTML documents. data collected in the PostgreSQL database use Docker and docker compose. data issued in the form of a JSON document in the form of a REST API What should the structure of this project look like? -
DJANGO select FORM that is from a generated list and add an extra default value
I want to have a select drop down form. In this example, i want to have a drop down of all division but it can include one more extra record (which is default=0). How can I generate a list for select and append an additional item ? models: class Employee(models.Model): username = models.CharField(max_length=30, blank=False) division = models.ForeignKey(Division,null=True) class Division(models.Model): name_of_division = models.CharField(max_length=30) forms.py class EmployeeEditForm(forms.ModelForm): username = forms.CharField(max_length=30, required=True) division = forms.ChoiceField(widget=forms.Select, choices=XXXXWHATSHOULDIPUTHEREXXX) class Meta: model = Employee fields = ("username","division") For example: division 0 - default (this is not in the Division table) <-- i want to add this to the select list 1 - corporate 4 - human resource 7 - engineering -
Download BinaryFiled Data
how to download BinaryField Data/file using template. like we did for FileField <td><a href={{certificate.bytes.url}} download></a> Is there anyway to download BianryField Daa/File. -
Axios Delete 405 (Method Not Allowed) Error with Django Rest Framework
I am using ReactJS as client side web app and I'm using axios package. In my backend, I am using Django Rest Framework. I created Serializer for CartItem Model: class CartItemSerializer(serializers.ModelSerializer): class Meta: model = CartItem # Fields you want to be returned or posted fields = '__all__' Viewset: class CartItemViewSet(viewsets.ModelViewSet): queryset = CartItem.objects.all() serializer_class = CartItemSerializer I am trying to use default delete method of DRF in axios using so: axios.delete('cart_items/', { headers: { Authorization: 'Token token' }, data: { id: 1, }, }) .then(res => { console.log(res) }) When I call that, it gives me error in React: DELETE http://127.0.0.1:8000/cart_items/ 405 (Method Not Allowed) -
Channel django get No module named 'asgiref.sync'
I beginning use channel for my project. I follow this tutorial Raspberry PI and Django Channels for develop my project. But after runnig server python3 manage.py runsever, give me this error. root@raspberrypi:/home/pi/sensor# python3 manage.py runserver 0:8000 :0: UserWarning: You do not have a working installation of the service_identity module: 'cannot import name 'opentype''. Please install it from <https://pypi.python.org/pypi/service_identity> and make sure all of its dependencies are satisfied. Without the service_identity module, Twisted can perform only rudimentary TLS client hostname verification. Many valid certificate/hostname mappings may be rejected. :0: UserWarning: You do not have a working installation of the service_identity module: 'cannot import name 'opentype''. Please install it from <https://pypi.python.org/pypi/service_identity> and make sure all of its dependencies are satisfied. Without the service_identity module, Twisted can perform only rudimentary TLS client hostname verification. Many valid certificate/hostname mappings may be rejected. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File … -
cannot cast type character varying[] to jsonb django migration
I have alter my model from arrayfield to json field now i am receiving error cannot cast type character varying[] to jsonb LINE 1: ...LUMN "questionaires" TYPE jsonb USING "questionaires"::jsonb.How to fix this ? and how it did occur? from questionaires = ArrayField(models.CharField(max_length=4000), null=True, blank=True) to questionaires = JSONField(null = True,blank = True) -
How to fetch data from one model and display it in the form as drop down for storing it in another model in django
i have a 3 models namely category, brand, products. i have to include the category and brand in the products form for displaying it in drop down and selected value should be assigned in the products table.can anyone help me with it? -
How to get count of particular attribute [age_group e.g] in the following Django Query based on Ranges?
I have the following models.py in Django. class Study(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) age_group = models.DecimalField(decimal_places=2, max_digits=5) gender = models.CharField(max_length=40, null=True, blank=False) created_at = models.DateTimeField(auto_now=True) Now I have some values that are filled using the form which are as follows : age_group - 13 gender - male age_group - 27 gender - female age_group - 20 gender - male Now I want to group age_group type based on the ranges. For e.g my output should be : age_group 5-21 Count : 2 age_group 22 - 30 Count : 1 I have tried the following query: But I am stuck with the group part. Here's the query I have tried so far : Study.objects.filter(Q(age_group__range=[10,20])| Q(age_group__range=[21,35]) | Q(age_group__range=[36, 54])).values('age_group').annotate(Sum('age_group')).order_by('age_group') Any help will be appreciated. TIA -
psycopg2.errors.UndefinedTable: relation "user_user" does not exist
i'm new in django . i try to work on this project from github.when i installed requirement when i try python manage.py update_data as written in documentation this error occur : Traceback (most recent call last): File "/home/parsezan/work/hamclaasy-backend/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "user_user" does not exist LINE 1: SELECT (1) AS "a" FROM "user_user" WHERE "user_user"."friend... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/parsezan/work/hamclaasy-backend/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/parsezan/work/hamclaasy-backend/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/parsezan/work/hamclaasy-backend/env/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/parsezan/work/hamclaasy-backend/env/lib/python3.6/site-packages/django/core/management/base.py", line 350, in execute self.check() File "/home/parsezan/work/hamclaasy-backend/env/lib/python3.6/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/home/parsezan/work/hamclaasy-backend/env/lib/python3.6/site-packages/django/core/management/base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "/home/parsezan/work/hamclaasy-backend/env/lib/python3.6/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/home/parsezan/work/hamclaasy-backend/env/lib/python3.6/site-packages/django/contrib/auth/checks.py", line 74, in check_user_model if isinstance(cls().is_anonymous, MethodType): File "/home/parsezan/work/hamclaasy-backend/env/lib/python3.6/site-packages/django/db/models/base.py", line 459, in __init__ val = field.get_default() File "/home/parsezan/work/hamclaasy-backend/env/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 798, in get_default return self._get_default() File "/home/parsezan/work/hamclaasy-backend/apps/user/models/user.py", line 63, in gen_user_friend_invite_code if not User.objects.filter(friend_invite_code=invite_code).exists(): File "/home/parsezan/work/hamclaasy-backend/env/lib/python3.6/site-packages/django/db/models/query.py", line 718, in exists return self.query.has_results(using=self.db) File "/home/parsezan/work/hamclaasy-backend/env/lib/python3.6/site-packages/django/db/models/sql/query.py", line 516, in has_results return compiler.has_results() File "/home/parsezan/work/hamclaasy-backend/env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1035, in has_results return bool(self.execute_sql(SINGLE)) File "/home/parsezan/work/hamclaasy-backend/env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line … -
how to Give A Postgres User SuperUser Previllege Through docker-compose
This is my docker-compose file section for postgres container, These settings are fine, but my django app requires this user to have superuser previlleges through this command inside postgresql ALTER ROLE project_admin SUPERUSER; how can this be accomodated inside this docker-compose file? db: image: postgres:latest container_name: project-db environment: - POSTGRES_USER='project_admin' - POSTGRES_PASS='projectpass' - POSTGRES_DB='project' -
Django/Nginx : serving static files in production
I am trying to serve CSS and other static files on my django app using NGINX server. So I tried to configure it. Here is my /etc/nginx/sites-enabled/mydomain: server { listen 80; server_name redpillers.net; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/limited/REDPILLERS; } location / { include proxy_params; proxy_pass http://unix:/home/limited/REDPILLERS/redpillers.sock; } location /static/ { alias /home/limited/REDPILLERS/static/; } } But when I restart the service I got an error in the error logs file: 2019/05/22 07:26:44 [emerg] 11589#11589: duplicate location "/static/" in /etc/nginx/sites-enabled/mydomain:15 -
TypeError int() argument must be a string, a bytes-like object or a number, not 'InMemoryUploadedFile'
I was simply trying to upload a file in Django 2 but it's returning this error every time. my from.html have multiple filed where user can add filed if he needs. so i have to k now aobut this is have to know adfsd fasdf af af af as fasdf a f as fa sf as fa sf asf asdf asd f af a f asfd a f I was simply trying to upload a file in Django 2 but it's returning this error every time. my from.html have multiple filed where user can add filed if he needs. so i have to k now aobut this is have to know adfsd fasdf af af af as fasdf a f as fa sf as fa sf asf asdf asd f af a f asfd a f I was simply trying to upload a file in Django 2 but it's returning this error every time. my from.html have multiple filed where user can add filed if he needs. from.html image view Error In terminal Internal Server Error: /stockSale/addStockSale Traceback (most recent call last): File "/home/an2/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/an2/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, … -
Execute function after cache timeout
Scenario: I use Local-memory caching: https://docs.djangoproject.com/en/2.2/topics/cache/#local-memory-caching. I cached some data in local memory. And the timeout of it depends on something else (It mean I don't know exactly timeout). But I want to run some code after this cache timeout. Question: Are django have event or trigger for cache timeout? -
Validating HTTP_HOST headers for apache server using ebextensions
I have a Django app hosted on AWS. I use Elastic Beanstalk and use a .ebextensions/django.config file to input all my custom server side settings. I have ALLOWED_HOSTS set up so that if anybody tries to connect to my site from an invalid host header they get blocked...by Django. I get all kinds of Django error logging emails saying Invalid HTTP_HOST header: 123.456.789. -- essentially bots / scanners trying to connect and/or upload malicious content. I'd like to block these bad requests at a server side as it seems more secure to have that extra blocking layer, and I don't like getting all the emails. In the Django docs they write that "[they recommend] configuring your web server to ensure it validates incoming HTTP Host headers." I'd like to do that in my .ebextensions/django.config file. Here is my current .ebextensions/django.config file: container_commands: 01_migrate: command: "python manage.py migrate --noinput" 02_collectstatic: command: "python manage.py collectstatic --noinput" option_settings: aws:elasticbeanstalk:container:python: WSGIPath: myapp/wsgi.py aws:elasticbeanstalk:container:python:staticfiles: /static/: static/ files: "/etc/httpd/conf.d/ssl_rewrite.conf": mode: "000644" owner: root group: root content: | WSGIApplicationGroup %{GLOBAL} RewriteEngine On <If "-n '%{HTTP:X-Forwarded-Proto}' && %{HTTP:X-Forwarded-Proto} != 'https'"> RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L] </If> Header always set Referrer-Policy no-referrer Header always set Strict-Transport-Security "max-age=14400; includeSubdomains;" I believe … -
I would like to refer to the sample and apply the css layout for the modal But it does not work
I would like to refer to the sample and apply the css layout for the modal But it does not work. samplelayout https://github.com/hyunsokstar/django_inflearn2/blob/master/todo/templates/todo/tt.html result of tt.html: for example I want to separate the contents of modal as follows : left side : right side modal code <div class="modal fade" id="myModal"> <div class="modal-dialog modal-xl"> <div class="modal-content"> <h2 style="background-color:skyblue;">todo detail</h2> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">{{ object.title }}</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <!-- Modal body --> <div class="modal-body"> {{ object.get_markdown_content | safe }} <hr> <div class="card border-info mb-3" style="max-width: 60rem;"> <div class="card-header"><h2 style="background-color:lightgreen">코드 입력</h2></div> <div class="card-body"> <!-- comment insert --> <div class="comment_insert_area" style="background-color:white"> <form method="post" action="{{object.get_absolute_url}}new_comment/" id="comment_form" class="hi"> {% csrf_token %} <div class="form-group"> {{ comment_form | crispy }} </div> <button type="submit" class="btn btn-primary float-right" style="margin-right:20px;">Submit</button> <br> </form> {{ form.media }} </div> </div> </div> <hr> <!-- comment output --> <div class="card border-danger mb-3" style="max-width: 60rem;"> <div class="card-header"> <h2 style="background-color:lightgreen">Step-by-Step Code</h2> </div> <div class="card-body"> {% for comment in comments.all %} <table class="table table-bordered" id="comment_table_{{comment.id}}"> <tr> <td>author2</td> <td>{{ comment.author }}</td> </tr> <tr> <td>title</td> <td colspan="3"> <input type="text" class="form-control" name="" value="{{comment.title}}" id="todo_comment_title_{{comment.id}}"> </td> </tr> <tr> <td>file_name</td> <td colspan="3"> <input type="text" class="form-control" name="" value="{{comment.file_name}}" id="todo_comment_file_name_{{comment.id}}"> </td> </tr> <tr> <td>code</td> <td colspan="3"> <textarea name="name" rows="10" … -
How to allow only the Django authenticated users to view Wordpress contents?
I have a Django application (SaaS) and a Wordpress blog (documentation/user guide for the SaaS application). Now I want to make sure that only logged-in user in the SaaS application (Django) should have access or can view the (documentation/user guide) in Wordpress blog. In the Wordpress, I've added this block in functions.php that restricts access to content only to Wordpress members. function members_only() { global $pagenow; // Check to see if user in not logged in and not on the login page if( !is_user_logged_in() && $pagenow != 'wp-login.php' ) auth_redirect(); } add_action( 'wp', 'members_only' ); This gives one level of content protection if someone hits direct URL to Wordpress blog. I do not want to touch the Wordpress code base anymore. Can I add some authentication mechanism in Django side so that when user clicks on User Guide button, they are redirected to the Wordpress site and can view the content. And if someone has direct hit to Wordpress site they are redirected to the WP login page.