Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom user foreign key TypeError: Cannot create a consistent method resolution order (MRO)
How can I add foreign key with user type foreign key? Models have one to many relationship through foreign keys. Django docs show that I can add a model and reference through a foreign key. I want to add a user type: admin, staff, and guest. Then add permissions: up to delete, up to edit, and up to read respectively. python3 manage.py runserver TypeError: Cannot create a consistent method resolution order (MRO) for bases Model, HistoricalRecords, SoftDeletableModel, TimeStampedModel from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models import CharField from django.urls import reverse from django.utils.translation import gettext_lazy as _ from model_utils.models import SoftDeletableModel, TimeStampedModel from simple_history.models import HistoricalRecords class User_Type(models.Model, HistoricalRecords, SoftDeletableModel, TimeStampedModel): name = models.CharField(max_length=100) class User(AbstractUser): """ Default custom user model for project. If adding fields that need to be filled at user signup, check forms.SignupForm and forms.SocialSignupForms accordingly. """ #: First and last name do not cover name patterns around the globe name = CharField(_("Name of User"), blank=True, max_length=255) first_name = None # type: ignore last_name = None # type: ignore user_type = models.ForeignKey(User_Type, on_delete=models.CASCADE) def get_absolute_url(self): """Get url for user's detail view. Returns: str: URL for user detail. """ return reverse("users:detail", kwargs={"username": self.username}) -
How can I add a related field to serializer instance?
I have the following model + serializer where I send a post request to create a new model instance. The user sending the post request is related to a Company which I want to pass as related model instance to the serializer. But how to actually define this instance and attach it to the serializer instance within the post view? # views.py class OfferList(APIView): """ List all Offers or create a new Offer related to the authenticated user """ def get(self, request): offers = Offer.objects.filter(company__userprofile__user=request.user) serializer = OfferSerializer(offers, many=True) return Response(serializer.data) def post(self, request): serializer = OfferSerializer(data=request.data) # Add related company instance company = Company.objects.get(userprofile__user=request.user) serializer['company'] = company # this doesn't work if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # offer/models.py class Offer(models.Model): """ A table to store Offer instances """ # Relations company = models.ForeignKey(Company, on_delete=models.CASCADE) .. # serializers.py class OfferSerializer(serializers.ModelSerializer): class Meta: model = Offer fields = '__all__' user/models.py class UserProfile(models.Model): """ Extends Base User via 1-1 for profile information """ # Relations user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True) -
django.urls.exceptions.NoReverseMatch - django-smart-selects
I am trying to implement django-smart-selects in my project but get errors when trying to add a record in my model from django admin. Here's my code: models.py class PricingConfiguration(CreateUpdateMixin): name = models.CharField(max_length=50) description = models.CharField(max_length=250) appointent_category = models.ForeignKey( AppointmentCategory, null=True, blank=True, related_name="pricing_appointment_category", on_delete=models.CASCADE, ) speciality = models.ForeignKey( Speciality, null=True, blank=True, related_name="pricing_speciality", on_delete=models.CASCADE, ) sub_speciality = ChainedForeignKey( SubSpeciality, chained_field="speciality", chained_model_field="speciality", show_all=False, auto_choose=True, sort=True, null=True, blank=True, ) urls.py from django.urls import include, path, re_path from django.contrib import admin from rest_framework.routers import DefaultRouter app_name = "configuration" urlpatterns = [ re_path(r"^admin/", admin.site.urls), re_path(r"^chaining/", include("smart_selects.urls")), ] Errors: django.urls.exceptions.NoReverseMatch django.urls.exceptions.NoReverseMatch: Reverse for 'chained_filter' not found. 'chained_filter' is not a valid view function or pattern name. Traceback (most recent call last) File "/usr/local/lib/python3.9/site-packages/django/contrib/staticfiles/handlers.py", line 76, in __call__ return self.application(environ, start_response) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ response = self.get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 130, in get_response response = self._middleware_chain(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner response = response_for_exception(request, exc) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 149, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/usr/local/lib/python3.9/site-packages/django_extensions/management/technical_response.py", line 40, in null_technical_500_response raise exc_value.with_traceback(tb) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 204, in _get_response response = response.render() File "/usr/local/lib/python3.9/site-packages/django/template/response.py", … -
pytest-django RuntimeError : Database access not allowed,
I'm testing my django application using pytest / pytest-django. my urls.py file contains from django.urls import include, path from . import views urlpatterns = [ path('', include('django.contrib.auth.urls')), path('users/', views.users, name='users'), path('add-user/', views.add_new_user, name='add_new_user'), ] in my tests.py file, I have import pytest from django import urls def test_users_url_resolves_to_users_view(client): url = urls.reverse('users') resp = client.get(url) assert resp.status_code == 200 I get RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. when i run this. -
Is it possible to edit a crispy form using styles.css? Like change the background color, etc.? Because I can't make mine work. Thanks
I am a beginner in studying Python Django and I am trying to create a login page for my website using crispy forms. But I can't control the styling of it, I am wondering if it is possible and if it is, how can I possibly do it? Thanks. Here is the Django HTML codes: {% extends 'users/base.html' %} {% load crispy_forms_tags %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'users/register.css' %}"> <div class="register-container"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Create An Acount </legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit"> Sign Up </button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have An Account? <a class="ml-2" href="#">Log In</a> </small> </div> </div> {% endblock content %} CSS: base.css transition: margin-left .5s; padding: 16px; background: rgb(255,255,255); background: radial-gradient(circle, rgba(255,255,255,1) 0%, rgba(33,208,178,1) 100%); } -
Please Help Django Function Working But I Get Error: Int object has no attribute mete
Hello kindly help my function works i can see the added results returned but i get an error: int object has no attribute meta. Thank You All. Views.py @api_view(['POST']) def swimmersUpdate(request, pk): sw = get_object_or_404(Swimmers,id=pk).sessions current_sessions = sw + 10 serializer = SubSerializer(instance=current_sessions, data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, safe=False, status=status.HTTP_201_CREATED) return JsonResponse(data=serializer.errors, safe=False, status=status.HTTP_400_BAD_REQUEST) -
Button image not showing
I'm just learning how to use Django and HTML, and I encountered such a problem that my image is not displayed on the button, I don't understand what the error is and I will be grateful if someone can help me fix it <!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8"> <title></title> <style> button { background-image: url("/main/static/main/img/i.jpg"); padding-left: 32px; padding-top: 10px; padding-bottom: 10px; background-repeat: no-repeat; width: 320px; height: 320px; } </style> </head> <body> <button></button> </body> </html> -
How to add comment on Logged in 'User Form' from Admin Panel in Django?
---- I need a comment section under a form, where Logged in User can see a comment. This comment must be made by Admin from Django Admin Panel. ____ **Model.py File:** class Comment(models.Model): complain = models.ForeignKey(Complain, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=80) body = models.TextField(max_length=190) date_added = models.DateTimeField(default=now) class Meta: db_table = "Comment" def __str__(self) : return self.complain.email I need a comment section under a form, where Logged in User can see a comment. This comment must be made by Admin from Django Admin Panel. This is the Complain.html file where Logged in User can submit any Complain via the form. **Complain.html Form:** <form method='POST' enctype="multipart/form-data"> {% csrf_token %} Email: &nbsp; <input type="email" name="email" required/> <br /><br /> What is the complain: &nbsp; <input type="text" name="complain" required/><br /><br /> Who's against the complain (Enter Userame): &nbsp; <input type="text" name="against" required/><br/><br/> <br/> Position of the person you are complaining against: &nbsp; <input type="text" name="position" required/><br/> <br/> <div class="mb-3"> <label class="form-label">Evidence</label> <input class="form-control-file" type="file" name="image" required /> </div> </div> <div class="mt-1" style="text-align: center"> <button class="btn btn-danger mt-5" style="border-radius: 16px" type="submit">Submit</button> </form> //Comment here <h2> Comment From Admin... </h2> <br/> {% if not complain.comments.all %} - No Comments yet... {% else %} {% for … -
Django - how can i return data from a class bades view dynamically?
I created an API using Django, and i have a class based view where i'm using a cache with a 1.5 seconds TTL. Here is an example: class Sales_View(APIView): http_method_names = ['get'] @method_decorator(cache_page(1.5)) def get(self, request, format=None): ... return JsonResponse({'page': page, 'records': len(data), 'data': data}, safe=False) I would like to use another function with a different cache TTL when a specific parameter sale_value is provided in the URL, here is another example: class Sales_View(APIView): http_method_names = ['get'] @method_decorator(cache_page(1.5)) def get(self, request, format=None): ... return JsonResponse({'page': page, 'records': len(data), 'data': data}, safe=False) @method_decorator(cache_page(30)) def get_large_sales(self, request, format=None): ... return JsonResponse({'page': page, 'records': len(data), 'data': data}, safe=False) When the URL 127.0.0.1:8000/api/sales/?some_query=<some_value>&... is requested, data should be returned by get. When the url 127.0.0.1:8000/api/sales/?sale_value=, data should be returned by get_large_sales since it contains the sale_value parameter. To summarize, i need to be able to use a different cache expire time when a query to my API contains a specific parameter. Is it possible to do this without using redirect? -
Django CORS CSRF_TRUSTED_ORIGINS does not work
Im working on a DRF (Django project) where my backend django rest api is hosted on a server and my ReactJS frontend is also hosted on the same server. I had made sure to follow all the steps needed as what I've read in the ff documentations: https://github.com/adamchainz/django-cors-headers http://www.srikanthtechnologies.com/blog/python/enable_cors_for_django.aspx I have added corsheaders INSTALLED_APPS and my middleware in settings.py is: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] And my CORS Settings in settings.py is: CORS_ALLOW_ALL_ORIGINS=False CSRF_TRUSTED_ORIGINS = [ "https://samplefrontend.tech", ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] However, when I try to do some requests using Postman from my local PC (not from the frontend server), example, get token, the rest api returns the refresh and access tokens. This also holds true with other HTTP requests. What I needed is that only requests coming from the frontend server should be accepted. Can anyone help me on this? -
how to display 6 of the latest properties
I am trying to show only 6 of the latest properties on my site by inserting each property literal inside their respective HTML tag because I have a fixed HTML layout for it I only know how to display everything in a for loop. and also how do I upload multiple images in Django here are the models, views, and HTML codes below. #views.py from random import randint from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages from django.contrib.auth.decorators import login_required from django.http import HttpResponse from .models import Userprofile, Property import random # Create your views here. def index(request): l_property = Property.objects.order_by('-listed_on').last() return render(request, 'index.html', {'l_property':l_property}) #models.py built_on = models.DateTimeField(null=True) listed_on =models.DateTimeField(auto_now_add=True, auto_now=False, null=True) last_updated = models.DateTimeField(auto_now=True, null=True) video_link = models.URLField(max_length=350, null=True, blank=True) def __str__(self): return self.property_name #html {% for properties in Property %} <div class="grid-item-holder gallery-items gisp fl-wrap"> <!-- gallery-item--> <div class="gallery-item for_sale"> <!-- listing-item --> <div class="listing-item"> <article class="geodir-category-listing fl-wrap"> <div class="geodir-category-img fl-wrap"> <a href="listing-single.html" class="geodir-category-img_item"> <img src="images/all/3.jpg" alt=""> <div class="overlay"></div> </a> <div class="geodir-category-location"> <a href="#" class="single-map-item tolt" data-newlatitude="40.72956781" data-newlongitude="-73.99726866" data-microtip-position="top-left" data-tooltip="On the map"><i class="fas fa-map-marker-alt"></i> <span> 70 Bright St New York, USA</span></a> </div> <ul class="list-single-opt_header_cat"> <li><a href="#" class="cat-opt blue-bg">{{ Property.list_type}}</a></li> <li><a href="#" … -
How to clear RAM after deleteng all variables from python
I have Django project where i need to get data from postgres DB and then manipulate with it (1GB in postgres). After that when i executed all postgres data what i needed my ram increase, after another operation like this RAM also increase and so on... If i have 64GB RAM and after execution postgres data my RAM increase ~1GB then if I run that function 10 times my ram will be ~10GB I tried to delete all variables from Python with del or gb, but after that i also have full RAM. Only option to clear RAM is to close Django project. Is there option to clear RAM after i execute data from postgres? -
Django multi-table inheritance: How to assign parent object to child class
Referring to Django documentation example: from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) I have: p = Place.objects.create(name='some_place', address='some_address') Since I have already created parent class object. I want to add Restaurant object assigned to the Place object I created above. In short, I want to do something like. r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False) r.save() Note: In the multi-table inheritance - "parent_link=True". Therefore the above code doesn't work. While it will work perfectly if we use it as One-to-one relation without inheriting the Place class. Meaning: class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __str__(self): return "%s the place" % self.name class Restaurant(models.Model): place = models.OneToOneField( Place, on_delete=models.CASCADE, primary_key=True, ) serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) -
DJANGO How to do arithmetic operations in django Rest POST method
How to do arithmetic operations in django view so a user can click on a button add to be able to add and save in the database. Thank You Views.py @api_view(['POST']) def swimmersUpdate(request, pk): sw = Swimmers.objects.get(id=pk) current_sessions = sw.sessions sw.sessions = current_sessions + 1 serializer = SubSerializer(instance=sw, data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, safe=False, status=status.HTTP_201_CREATED) return JsonResponse(data=serializer.errors, safe=False, status=status.HTTP_400_BAD_REQUEST) -
How do I add a description to a field in GraphQL schema language?
How do I add a description to a field in GraphQL schema language !! btw I'm working with django framework. Thnx for advance -
How to store and get dependent data in Django Model
I'm creating a course website using Django. I'm stuck in storing the sub-sections of the course. like in a course there is a section that could be divided into sub-section and those subsections could be divided into sub-section. I'm stuck on the part of how can achieve something like this with Django models. What I got in my mind is that I make a boolean field for the sections if it's a sub-section of any other section. but then another question where I'm really stuck is, if I store course sections like this how will I get all the subsections, like a section of a sub-section of another sub-section. If I somehow filter the data and get the main section then How can get all the other sections that are sub-sections of that section. I know it's a little confusing but please if you understood what I'm asking for please help me with this. it's taken so much time for me. for example, I have a course which has 2 sections A & B. and then A have another 3 sections A1, A2, and A3, and then A1 can have 2 more sections like A11, A12. so what's the way … -
Display dropdown values on change of other dropdown in django admin
I have two dropdowns in my django admin form: specialty and sub-specialty. I need to display values in sub-specialty dropdown based on the selected value of specialty dropdown. Is there a better (or more django-ish) way to achieve this without having to create a separate API that will fetch sub-speciality on dropdown change event in jQuery? -
Django from django.core.wsgi import get_wsgi_application , No module named Django
ve been struggling with deploying my Django app, when i do it with 0.0.0.0:8000 everything works fine but as soon as i am using apache then i get Django from django.core.wsgi import get_wsgi_application , No module named Django. Ive tried changing my python version on Ubuntu 18.04 as well for Python3.6.9 to the 3.9.12 and i get the same error on both versions . i am running it in a VENV as well as Django is installed when i do a pip freeze, ive also tried adding paths in my WSGI directly but same error , my also ive doubled check my conf file as that should not be the problem since i copied and adjusted from my other django app that is running with no problems here is the code Alias /static /home/YOURUSER/YOURPROJECT/static <Directory /home/YOURUSER/YOURPROJECT/static> Require all granted </Directory> Alias /media /home/YOURUSER/YOURPROJECT/media <Directory /home/YOURUSER/YOURPROJECT/media> Require all granted </Directory> <Directory /home/YOURUSER/YOURPROJECT/YOURPROJECT> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/YOURUSER/YOURPROJECT/YOURPROJECT/wsgi.py WSGIDaemonProcess django_app python-path=/home/YOURUSER/YOURPROJECT python-home=/home/YOURUSER/YOURPROJECT/venv WSGIProcessGroup django_app Also ive tried some examples that i read about such us sudo apt-get remove libapache2-mod-python libapache2-mod-wsgi sudo apt-get install libapache2-mod-wsgi-py3 but that also did not do anything so i can't seem to get … -
How to get rid of TypeError at /task_create/, quote_from_bytes() expected bytes
I am on django 4.0.4 and have a benign but annoying problem with the above error code. Previous responses to similar questions don't help me. When I backspace, (an incovenience a user may not think of) everything has actually gone well, the list and detail views are correctly updated. The create form is however as it was as if it was not saved, and the view doesn't change to the detail view as suggested by the get_absolute_url, which may lead one to process it again. The code from previous models is exactly the same where it matters. An example is the TaskCreate view which is giving the problem and the ObjectiveCreate view just before it which works as expected. In the views, I find the user and his/her entity (even though there is one entity), and process that user as a supervisor1 and also automatically process the entity. The error finds fault with the TaskCreate view's "return super().form_valid(form)" but not with that in the ObjectiveCreate view. Here is the code for the two views`class ObjectiveCreate(LoginRequiredMixin, CreateView): model = Objective form_class = ObjectiveCreateForm template_name = "internalcontrol/objective_create_form.html" def form_valid(self, form): user = self.request.user profile = Profile.objects.get(user=user) entity = profile.entity new_profile = Profile.objects.get(user=user, … -
Need a condition where User can't complain about himself in Django
This is a Complain form where a logged in user can submit. I want a condition in views.py file, where a logged in user can't submit a complain form against himself. ***views.py file:*** def complain(request): if request.method=='POST': email = request.POST['email'] complain = request.POST['complain'] against = request.POST['against'] image = request.FILES.get('image') if User.objects.filter(username = against).exists(): complain = Complain(email = email, complain=complain, against = against, image=image) complain.save() messages.success(request, 'Complain Submit Successful') return redirect('complain') else: messages.error(request, 'You are complaining against Non-User (-,-)') return redirect('complain') else: return render(request,'complain.html') ---- Please help to find the condition where Logged in user can't submit the form with typing his username or email address in the 'Against' input. ***Model.py file:*** class Complain(models.Model): email = models.EmailField(max_length=100) complain = models.CharField(max_length=200) against = models.CharField(max_length=200) image = models.ImageField(upload_to = 'static', null=True, blank=True, default='2.png') class Meta: db_table = "Complain" def __str__(self) : return self.email ---- Please help to find the condition where Logged in user can't submit the form with typing his username or email address in the 'Against' input. **Complain Form (Complain.html):** <div class="container mt-5"> <div class="heading1">Complain Form</div> <br> {%for message in messages%} <p style= "text-align:center ;font-weight: bold; color: rgb(48, 167, 247); font-size: 21px;"> {{message}} </p> {% endfor %} <div class="form mt-5"> <form … -
Migrating from Client-Django-S3 image/file upload to Client-S3 Presigned URL upload, while maintaining FileField/ImageField?
The current state of our app is as follows: A client makes a POST request to our Django + DRF app server with one or more files, the django server processes the files, then uploads and saves it to S3. This is done using the amazing django-storages & boto3 libraries. We eventually will have the reference url to our S3 files in our Database. A very simplified example looks like this: # models.py class TestImageModel(models.Model): image = models.ImageField(upload_to='<path_in_bucket>', storage=S3BotoStorage()) # serializers.py class TestImageSerializer(serializers.ModelSerializer): image = serializers.ImageField(write_only=True) The storages library handles uploading to S3 and calling something like: TestImageModel.objects.first().image.url will return the reference to the image url in S3 (technically in our case it will be cloudfront URL since we use it as a CDN, and set the custom_domain in S3BotoStorage class) This was the initial approach we took, but we are noticing heavy server memory usage due to the fact that images are first uploaded to our server, then uploaded again to S3. To scale efficiently, we would like to move to an approach where to instead upload directly from Client to S3 using presigned URLs. I found documentation on how to do so here: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-presigned-urls.html. The new strategy I … -
settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details
I'm using MongoDB and docker container. when I run the same code on the local machine it's working perfectly but when I'll using the same code on the docker container it gives me errors information are given below: i am tryed to convert the code into mongoengine but it was not worked. from pathlib import Path from django.contrib.messages import constants as messages import os # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASE = { 'default': { 'ENGINE': 'djongo', 'NAME': 'react_vision', 'CLIENT': { 'host': 'mongodb://mongodb:27017', 'username': 'root', 'password': 'mongoadmin', 'authSource': 'admin', 'authMechanism': 'SCRAM-SHA-1', } } } Traceback (django-env) root@0d9c579987c5:/home/react-vision/dev/reactVision-StreamerApp/reactVisionWeb# python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 18, 2022 - 10:54:09 Django version 4.0.3, using settings 'reactVisionWeb.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: / Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/usr/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/react-vision/dev/reactVision-StreamerApp/reactVisionWeb/home/views.py", line 9, in index return render(request, 'homeMenuTemplates/index.html', {'menuItems':menuItems}) File "/usr/lib/python3.8/site-packages/django/shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) File "/usr/lib/python3.8/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/usr/lib/python3.8/site-packages/django/template/backends/django.py", line 62, in … -
Event on change in select tag in Django
I have my home.html as <select name="PublicWords"> <option value="">All</option> <option value="">Draft</option> <option value="">Approved</option> <option value="">Approved ZWNJ</option> <option value="">Rejected</option> </select> I would like to perform some action on change in this select tag in my django project How can i perform this action? -
drf-yasg Django restframework Swagger Page return blank page with django login a href link
Hi I try to add to my project swagger but it return 401 error , please help me about it it is my router from . import router schema_view = get_schema_view( openapi.Info( title='EduOn API', description="EduOn API", default_version='v1', terms_of_service='https://www.google.com/policies/terms/', contact=openapi.Contact(email="algoritmgateway@gmail.com"), license=openapi.License(name='EduOn License'), ), public=True, permission_classes=(permissions.AllowAny,) ) register my routers: urlpatterns += router.router.urls in urlpatterns inside list : #documents url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), and register in INSTALLED_APPS I get my expecct output in onluy localhist:8000 but if i restart nginx and enter production website it get this output ( enter image description here -
I face a problem that variable name I assigned to each path in urls.py, and then create a link But it not works
this is my django+html code {% extends "tasks/layout.html" %} {% block body %} <h1>Tasks Lists</h1> <a href="[% url 'tasks:add' %]"> Add a task</a> {% endblock %} this is where i use varriable name add and link it to another page. Urls.py from django.urls import path from . import views app_name = "tasks" urlpatterns=[ path("",views.index,name="index"), path("add",views.add,name="add") ] this is where i use the varriable name "add".