Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to migrate Django's local sqlite3 tables to heroku postgresql tables?
I have pushed my django app to heroku. Everything runs fine except for the database. Even after installing postgresql on my pc and creating a postgresql db on heroku server and runnung heroku run python manage.py migrate(done successfully) I still get the error of not found. (DoesNotExist) Also, surprisingly, I have just one table in models.py called 'Logged' in a folder called Link5. But when I ran \d to see all tables on heroku after going into console using heroku pg:psql, I found that heroku created a table called 'Link5_Logged'. But all my code in views.py is referencing to it as 'Logged'. The table has only one row, but when I ran select * from logged in psql, It showed as empty. I've been stuck at this for more than a week. Any suggestions would be helpful. -
How to send a variable from html page back to Django view for further processing
I am using jQuery autocomplete search (shown below): def CitySearch(request): country_search_id = <country_id> # "country_id" to be sent from html page (value stored in a field) if request.is_ajax(): q = request.GET.get('term','') names = City.objects.filter(country__id=country_search_id).filter(name__icontains=q).annotate(value=F('name'), label=F('name')).values('id', 'value', 'label') result = list(names) data = json.dumps(result) mimetype = 'application/json' return HttpResponse(data, mimetype) The first filter (.filter(country__id=country_search_id)) is intended for filtering out all countries other than the one selected in the country autocomplete field (using variable country_search_id). Is it possible to send the captured country id back to the CitySearch view so as to be able to apply the filter? The country id value is stored in a form field on the page. -
How to redirect login urls depending on if the user is admin or not in Django?
I'm still new to Django. I have an admin user and a regular user who is not an admin. When admin login he should be redirected to '/admin_section' & when a regular user login he should be redirected to the '/' front page. Beyond that, it should be possible for an admin to be able to navigate to the '/' front page and see the page as a regular user can see. I've been trying to search for an answer for this and the only thing I find is that I can use request.user.is_superuser in a view and ask whether the user is a superuser/admin or not. But the problem then becomes that admin will not have the ability to navigate to the front page ever. Here is my code so far (from the views.py file): def home(request): # if the user is not logged-in, show the loginpage if not request.user.is_authenticated: return HttpResponseRedirect('login') # if the user is logged-in, show the frontpage return render(request, 'mainapp/index.html') # return the view for the admin section def admin(request): # if the user is logged-in & is an admin - show the admin section if request.user.is_authenticated and request.user.is_superuser: return render(request, 'mainapp/admin.html') return redirect('home') # … -
Allow users to edit account details to Postgres in Django in a Class-based View
I've spent ages trying to figure out how to allow a user of my website to edit their account details. I've tried a ton of options, but none seem to be working. All my views are currently class-based, and any function based views haven't worked. I'm using Django's pre-built User model, and my database used is PostgreSQL. currently my homepage can navigate to the user's account page (If logged in, otherwise sends them to the login page), where there is a link to update_user.html. But from there I'm not sure how to either use a html form to send data to a python script, or use a Django form to collect the data to start with, nor how to write the code for that to work. Any advice? Many thanks -
Create pagination block using Django Rest Framework and vue.js
I'm beginner in DRF. I want to create pagination block as : << ... 2 3 [4] 5 6 ... >> << ... 3 4 [5] 6 7 >> << ... 5 6 [7] >> I'm include PageNumberPagination and I get in json prev and pages number. <button type="button" @click="getUsers(prevPage)" v-if="prevPage">Prev</button> <button type="button" @click="getUsers(nextPage)" v-if="nextPage">Next</button> <script> ... getUsers(nextPage) { this.$axios .get(nextPage) .then(response => ( this.usersList = response.data.results, this.nextPage = response.data.next, this.prevPage = response.data.previous ... </script> At now I can show only Prev and Next buttons. How can I make pagination? Do I need to check current page number, to check if is two or one or not next or prev pages on the vue.js? -
Hiding items from front page if in your cart
I'm very shaky with django and Python, but I'm making a second hand ecommerce site (like ebay), and I'm struggling to do something that I'm sure is simple: If an item has been added to your cart, and you continue browsing, I don't want them to be able to see this item. This is because each item is unique, so seeing it again could mean adding it again, which wouldn't make sense! So far, I've been able to hide a users own items, but I just can't get my head around this part. Here's my code: the views.py for items: def get_items(request): """Create a view that will return a list of all items and render them to the 'items.html' template""" user = request.user if request.user.is_authenticated(): items = Item.objects.exclude(owner=user).filter(date_added__lte=timezone.now ()).order_by('-date_added') else: items = Item.objects.filter(date_added__lte=timezone.now ()).order_by('-date_added') return render(request, "items.html", {"items" : items, "profile": user}) The cart views.py def view_cart(request): """ A view to render cart contents """ return render(request, "cart.html") def add_to_cart(request, id): """ A view to add item to cart """ cart = request.session.get('cart', []) if id in cart: cart[id] = int(cart[id]) print("already in list - this will not add another") else: cart[id] = cart.get(id) print("not Found") request.session['cart'] = cart return … -
Form is valid but doesn't save email field on DB
Django 3.0 I've a SingUpForm for Clients registration. It uses a custom User, that only has 2 more attributes: is_client and is_seller models.py: class User(AbstractUser): is_client = models.BooleanField(default=False) is_seller = models.BooleanField(default=False) So in the save method, I changed the is_client to True when a client is submitting. But I've realized that the email was not being saved, but empty. So in order to save the email field to DB, I've set in the save method: user.email = self.cleaned_data.get("email") I think it is not necessary at all, but don't know why my form won't save the email automatically. forms.py class ClientSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User error_messages = { 'password_mismatch': "Las contraseñas no coinciden.", } first_name = forms.CharField(label="Nombre", max_length=100, required=False) last_name = forms.CharField(label='Apellido', max_length=100, required=False) username = forms.CharField(label='Nombre de usuario', max_length=100, required=False, error_messages={'invalid': "you custom error message"}) email = forms.EmailField(label='Correo electrónico', max_length=60, required=True) password1 = forms.CharField(label='Contraseña', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirmar contraseña', widget=forms.PasswordInput) def __init__(self, *args, **kwargs): super(ClientSignUpForm, self).__init__(*args, **kwargs) for fieldname in ['username', 'password1', 'password2']: self.fields[fieldname].help_text = None def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) @transaction.atomic def save(self): user = super().save(commit=False) user.is_client = True user.email = self.cleaned_data.get("email") … -
Downloadable docx file on button click
I have files(docx file) which I need to let users download by clicking on a button. These files were uploaded to a Model FileField. This is my views.py def files_view(request):files = FileModel.objects.filter(user=request.user) return render(request, template_name='folder/files_list.html') and this is my template.html {% for serving_files in user.files.all %} <a href="{{ serving_files.url }}"><button>Download</button></a> I'm doing this but the files are unable to download. What changes do I need to make? -
How to always prefetch_related for a specific django model
One of my models has number of related objects in it's __str__. This makes the admin site run very slow. Is it possible to set up the model in a way that would always do prefetch_related, even if not explicitly requested? -
How to improvise receiving django backend emails on the terminal?
I am working on a project that uses Django email backend and I receive an email in the terminal every time an email is sent. Right now, the whole email in the terminal is showing in one line irrespective of where I used different <p> tags. I want to know, is there's a way I can preview emails the same way they would be sent to the users? -
Google sheets for django charts
I need a advice on how to use google sheets' data in my django template to draw a graph. I have a prepared the template with chart.js with all the detail required, but iam stuck on how to pass the gsheets data in that chart. Please suggest me some examples or document on how to get google sheets data for django charts. Thanks in advance :) -
How to pass js variable with ajax to django?
I'm passing an array in json format with ajax to my django views. I receive status 200 so the POST has been made. The problem is when i try to display the data passed in another template. I receive None in console. Appreciate for any help. ajax function: $.ajax({ url: 'http://localhost:8000/order-confirmation', type: 'POST', data: {"array":array}, processData: false, contentType: "application/x-www-form-urlencoded/json", dataType: "json", headers: {"X-CSRFToken":'{{ csrf_token }}'}, success: function (result) { console.log(result.d); }, error: function (result) { console.log(result); } }); urls: path("order-confirmation", views.order_confirmation, name="confirmation") views: @csrf_exempt def order_confirmation(request): array = request.POST.get('array[]') context = { "array":array } return render(request, 'main_templates/order_confirmation.html', context) -
Unable to install django inside virtual environment within Docker container. Error - ModuleNotFoundError: No module named 'django'
My Docker File #Download base image from ubuntu FROM python:3.8 #Install necessary softwares RUN apt-get update RUN apt-get upgrade -y RUN apt-get install -y python3-venv python3-pip apache2 libapache2-mod-wsgi-py3 #Set the python ENV RUN python3 -m venv venv #ENV PATH="$VIRTUAL_ENV/bin:$PATH" RUN /bin/bash -c ". /venv/bin/activate" #Install django and dependency libs RUN pip3 install django psycopg2-binary #Copy the artefacts to the python env COPY . /home/ubuntu/envio-project/envio WORKDIR /home/ubuntu/envio-project/envio #ENV APACHE_RUN_USER www-data #ENV APACHE_RUN_GROUP www-data #ENV APACHE_LOG_DIR /var/log/apache2 #Change the permission RUN chown -R root:www-data /home/ubuntu/envio-project/envio RUN chmod u+rwx,g+rx,o+rx /home/ubuntu/envio-project/envio #COPY the apache conf COPY 000-default.conf /etc/apache2/sites-available/000-default.conf COPY apache2.conf /etc/apache2/apache2.conf EXPOSE 80 #RUN service apache2 start CMD ["/usr/sbin/apachectl", "-D", "FOREGROUND"] Docker image creation was successful and container can come up ok. But apache2 didn't start correctly. On inspecting the image i could see Django was not installed properly within the virtual environment. Below is the output of the container image creation from Dockerfile. Enabling site 000-default. invoke-rc.d: could not determine current runlevel invoke-rc.d: policy-rc.d denied execution of start. Setting up libapache2-mod-wsgi-py3 (4.6.5-1) ... apache2_invoke: Enable module wsgi invoke-rc.d: could not determine current runlevel invoke-rc.d: policy-rc.d denied execution of restart. Setting up python3-secretstorage (2.3.1-2) ... Setting up python3-keyring (17.1.1-1) ... Processing triggers for libc-bin … -
Djnago ORM get each group's latest data
I want to get specific user's all terms, latest agreement data. Three is terms table which has terms name. In table TermsAgreeHistory, there exists users agreement history class TermsAgreeHistory(model.Model): user = models.CharField() terms = models.ForeignKey(Terms) date_signed = models.DateTimeField(auto_now_add=True) is_agreed = models.BooleanField(default=True) class Terms(models.Model): name = models.CharField(unique=True) terms is foreign key TermsAgreeHistory pk user terms data_signed is_agreed ---------------------------------------- 1 Jack 1 20-01-01 Y 2 Jack 1 19-01-01 Y 3 Jack 2 20-01-01 N 4 Jack 2 19-01-01 N 5 Jack 3 20-01-01 Y 6 SAM 3 20-01-01 Y Under table has terms catalog Terms pk name -------------------- 1 member_term 2 search_term 3 share_term I want to search Jack's latest agreement and signed-date of terms which is in Terms table. By using Django ORM. result ---------------------------------------- 1 Jack 1 20-01-01 Y 3 Jack 2 20-01-01 N 5 Jack 3 20-01-01 Y Most important thing is my db is mysql -> can not use distinct method on column. How should I write code? -
How to get objects from ManyToManyRel
I am using get_fields on a model that returns all fields, including ManyToManyRel: field_list = self.model._meta.get_fields(include_hidden=True) Results in: field list: (<ManyToManyRel: books.book>, <django.db.models.fields.CharField>) I am using this function to build a list of fields that I can pass to context and display in a view: def get_model_fields(self, obj, fields): model_fields = [] # for f in self.model._meta.fields: for f in self.model._meta.get_fields(include_hidden=True): # resolve picklists/choices, with get_xyz_display() function get_choice = 'get_' + f.name + '_display' if hasattr(obj, get_choice): value = getattr(obj, get_choice)() else: try: value = getattr(obj, f.name) except AttributeError: value = None # Display blank values in DetailView if value == '': value = None if f.name in fields: model_fields.append( { 'label': f.verbose_name, 'name': f.name, 'help_text': f.help_text, 'value': value, 'class': str(f.__class__) } ) return model_fields This works well for all fields that are concrete. However ManyToManyRel has no value can not be iterated. Instead for these field types I want to append a simple concatenated list of the M2M objects as a str result in the value. If this was an object I would do something like: my_list = [] for obj in self.MyModel_set.all(): my_list.append(obj) return ', '.join(my_list) How can I do this managing the ManyToManyRel? -
Why javascript block from included template not executed in Djjango?
I have a javascript block in a template that is included into base.html. I wonder why it does not work? Here's my base.html <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %} Base {% endblock title %}</title> </head> <body> {% block content %} {% endblock content %} </body> <script> console.log("print from base"); </script> {% block js %} {% endblock js %} </html> This is footer.html {% block js %} <script> console.log("print from footer"); </script> {% endblock js %} And here's index.html {% extends 'base.html' %} {% block content %} Content from index.html {%endblock%} {% include 'footer.html' %} Only "Content from index.html" and "print from base" are displayed. -
Pymongo: returning a MongoClient if already exists
I'm using pymongo in a Django command that is run multiple times. What I'm trying to do is sharing a connection instance at the project level, so in settings.py I have something like: client = MongoClient('mongodb://mongo:27017/') and in the command I have: from django.conf import settings # then do something w/ setting.client... The problem w/ this approach is that each time I run my Django command, settings are imported and I open up a new mongo connection. Is there any better strategy for returning and existing connection without opening up a new one from scratch? -
i get error in when i want to work with postgresql in django
i'm in manjaro. I just migrated from mysql to postgresql. After much difficulty installing postgresql i get error :( the final result when in want install psycopg2: pip install psycopg2 the Result is: Collecting psycopg2 Using cached https://files.pythonhosted.org/packages/84/d7/6a93c99b5ba4d4d22daa3928b983cec66df4536ca50b22ce5dcac65e4e71/psycopg2-2.8.4.tar.gz Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/nima/project/django/coders/env/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-bc661h33/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-bc661h33/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-w4_ngmz0 --python-tag cp36 cwd: /tmp/pip-install-bc661h33/psycopg2/ Complete output (36 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/psycopg2 copying lib/compat.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/errors.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_json.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/tz.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/extensions.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/__init__.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_range.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_ipaddress.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/extras.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_lru_cache.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/sql.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/errorcodes.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/pool.py -> build/lib.linux-x86_64-3.6/psycopg2 running build_ext building 'psycopg2._psycopg' extension creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/psycopg x86_64-conda_cos6-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -fwrapv -O2 -Wall -Wstrict-prototypes -march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-strong -fno-plt -O2 -pipe -march=nocona -mtune=haswell -ftree-vectorize -fPIC -fstack-protector-strong -fno-plt -O2 -pipe -fPIC -DPSYCOPG_VERSION=2.8.4 (dt dec pq3 ext lo64) -DPG_VERSION_NUM=120001 -DHAVE_LO64=1 -I/home/nima/anaconda3/include/python3.6m -I. -I/usr/include -I/usr/include/postgresql/server -c psycopg/psycopgmodule.c … -
django/apache2 serving media isn't working on production
i'm running django mod_wsgi with apache2 on GCP VM instance and when i run it on DEBUG=False the static files work fine but media files is geting 404 when i check them while clearly the files are present on the server . my conf is based on the following django doc https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/modwsgi/#serving-files #settings.py MEDIA_ROOT = os.path.join(PROJECT_ROOT, "media") MEDIA_URL = os.environ.get("MEDIA_URL", "/media/") STATIC_ROOT = os.path.join(PROJECT_ROOT, "static") STATIC_URL = os.environ.get("STATIC_URL", "/static/") #apache2 Alias /media/ /home/ubuntu/myshop/media/ Alias /static/ /home/ubuntu/myshop/static/ <Directory /home/ubuntu/myshop/media> Require all granted </Directory> <Directory /home/ubuntu/myshop/static> Require all granted </Directory> tried restarting apache2 and even the server but didnt work either -
Django is not loading cx_Oracle libraries on Centos 7 at startup
After install my django app following this doc with all the requirements I noticed that the module cx_Oracle was not loading on startup. Myy intention is as follow. I have a code which needs to be executed once django starts and one time only. I put that code inside urls.py. The app starts successfully but it always raises the exception that there is no cx_Oracle module to import(this is inside the function I call from urls.py) I though it was the environment variables inside the venv were not loading so I added this code inside settings.py, but without expected results. ORACLE_HOME = os.environ.get('ORACLE_HOME') ORACLE_SID = os.environ.get('ORACLE_SID') LD_LIBRARY_PATH = os.environ.get('LD_LIBRARY_PATH') PATH = os.environ.get('PATH') On the other hand when I execute a script from console it works perfectly and python3.6 is able to load the environment variables. scl enable rh-python36 bash python3.6 test.py Questions Why the module cx_Oracle is not found if it is properly installed on virtual environment? How can I execute code at django startup and make sure I all modules can be loaded and used? Thanks in advance! -
google-appengine project: using a proxy to bypass SSL issues gives me "redirected too many times" only on the login page
When i ran "dev_appengine.py" to run the appengine application in the localhost, i would get an SSL issue when i would go to the sign in page. Inorder to fix that, i got a reverse proxy set up. This time, when i go to the 'signin' page through the proxy, i get the following error. This page isn’t workinglocalhost redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS I have tried to clear out the cookies. The 're-direct' error does not come when i push to production because when i push to production i do not have any SSL issues . -
2 buttons single form django for file upload
I'm working on a CRUD app to alter a MySQL database with Django, and I'm trying to add 2 options for a csv upload one that appends data to the table and another one that replaces the data with the uploaded csv ( delete and add) for that I tried to make 2 buttons for a single form but it not working for me. views.py: basecaseform = BaseCaseForm(request.POST) BaseCase_columns = [key for key, value in BaseCase.__dict__.items()] BaseCase_columns = BaseCase_columns[5:-1] basecase = BaseCase.objects.all() if request.method == 'GET': return render(request,'basecaselist.html',{'basecaseform':basecaseform,'basecase':basecase,'BaseCase_columns':BaseCase_columns}) if 'replace' in request.GET: BaseCase.objects.all().delete() else: pass csv_file=request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request,'this is not a csv file') data_set=csv_file.read().decode('UTF-8') io_string=io.StringIO(data_set) next(io_string) for column in csv.reader(io_string,delimiter=',',quoting=csv.QUOTE_NONE): _, created=BaseCase.objects.update_or_create( base_case_name= column[0], version= column[1], default= column[2], ) if basecaseform.is_valid(): basecaseform.save() else: basecaseform = BaseCaseForm() return render(request,'basecaselist.html',{'basecaseform':basecaseform,'basecase':basecase,'BaseCase_columns':BaseCase_columns}) html file : <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="file-upload" class="btn btn-primary"> Add </label> <input id="file-upload" type="file" name="add" onchange="this.form.submit()"/> <label for="file-upload" class="btn btn-primary"> Replace </label> <input id="file-upload" type="file" name="replace" onchange="this.form.submit()"/> </form> this solution throw an error : Exception Type: MultiValueDictKeyError at /basecase/ Exception Value: 'file' -
Not redirecting to home page in Django. While putting http://127.0.0.1:8000/home/connect/jhvjhb/3 in url
Image Showing Error and Request When entering http://127.0.0.1:8000/home/connect/jhvjhb/3 in url as url is defined to take some random letters and at last primary key. It should redirect to home but its not working. I do not have idea about regular expressions. urls.py from django.urls import path from home.views import HomeView from . import views app_name = 'home' urlpatterns = [ path('', HomeView.as_view(), name="home"), path('connect/(?P<operation>.+)/(?P<pk>\d+)/', views.change_friends, name='change_friends') ] moddels.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): post = models.CharField(max_length=500) user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Friend(models.Model): users = models.ManyToManyField(User) current_user = models.ForeignKey(User, related_name='owner', null=True,on_delete=models.CASCADE) @classmethod def make_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user=current_user ) friend.users.add(new_friend) @classmethod def lose_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user=current_user ) friend.users.remove(new_friend) views.py from django.views.generic import TemplateView from django.shortcuts import render, redirect from django.contrib.auth.models import User from .forms import HomeForm from .models import Post class HomeView(TemplateView): template_name = 'home/home.html' def get(self, request): form = HomeForm() posts = Post.objects.all().order_by('-created') users = User.objects.exclude(id=request.user.id) args = {'form':form, 'posts':posts, 'users':users} return render(request, self.template_name, args) def post(self, request): form = HomeForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() form = HomeForm() return redirect('home:home') args = … -
Django Rest Framework With JWT user authentication (getting anonymous user )
I am using JWT with Django to Authenticate requests from Ajax jquery . My Jquery is $.ajax({ url: "/customerapi/get-customer-detail/", type: 'GET', // headers: {"Token": localStorage.getItem('token')}, beforeSend: function (xhr) { /* Authorization header */ xhr.setRequestHeader("Authorization", "Token " + localStorage.getItem('token')); xhr.setRequestHeader("X-Mobile", "false"); }, success: function (res) { } }); And when I get this request on server I authenticate like this from rest_framework.permissions import IsAuthenticated class GetCustomerData(APIView): authentication_classes = (JSONWebTokenAuthentication, ) permission_classes = (IsAuthenticated ,) def get(self, request): try: Customer.objects.get(id=request.user) here my Request.user is always anonymous. Why this this is happening? and my middleware classes are 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', ] -
Problem in hosting Django REST API on IIS
I was trying to host django REST API on IIS but it wasn't working properly. I worked with the same locally and it was working absolutely fine. But when I hosted it on IIS then first of all its homepage with get method for all data from the database takes longer time to load and ended up with timeout error. And, when I tried to access other pages, the same problem occurred with them too. Only a page with post method opened but when I tried to submit data it raised an error. I checked server configuration then I found that default error is timeout error. Now I am confused about why such things happened. Can anyone please tell me if they faced similar issue or if they know some kind of compatibility issue or some prerequisite for hosting REST API using Django REST Framework? Or help me how can I find and fix the issue.