Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remove Margin from Paragraphs in CKEditor5
I am working on a project where I am utilizing the django-ckeditor package and wish to remove the margin on top and below paragraph elements. Unfortunately, I am having a lot of difficulty doing so. To add context, I am working with CKEditor 5. Is there a way to affect the styling using the configuration available with the django-ckeditor package, or some other way via CSS? I initially thought to try targeting the element via traditional CSS: .cke_editable p { margin: 0 !important; } However this caused no change. -
React and Django REST Framework login system
I'm trying to create a simple login system using React and Django Rest Framework. The userLogin function works but the userLogout doesn't and returns an error. Error details: POST http://127.0.0.1:8000/api/logout/ 403 (Forbidden) Uncaught (in promise) Status: 403 "CSRF Failed: Origin checking failed - http://127.0.0.1:3000 does not match any trusted origins." AuthContext.js import React, { createContext, useState, useEffect } from "react"; import axios from "axios"; const AuthContext = createContext(); export default AuthContext; export const AuthProvider = (props) => { axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.withCredentials = true; const api = axios.create({ baseURL: "http://127.0.0.1:8000/api/", }); const [user, setUser] = useState( () => JSON.parse(localStorage.getItem("user")) || null ); const [error, setError] = useState(null); const userLogin = async (email, password) => { try { const { data } = await api.post("login/", { username: email, password: password, }); if (data.error) { setError(data.error); } else { localStorage.setItem("user", JSON.stringify(data)); setUser(data); } } catch (error) { return; } }; const userLogout = async () => { await api.post("logout/"); localStorage.removeItem("user"); setUser(null); }; const authContextData = { api, user, userLogin, userLogout, error, }; return ( <AuthContext.Provider value={authContextData}> {props.children} </AuthContext.Provider> ); }; views.py # --------------------------------------------- # # ------------------- Login ------------------- # # --------------------------------------------- # @api_view(['POST']) @permission_classes([AllowAny]) @authentication_classes([SessionAuthentication]) def user_login(request): if request.method … -
Django Template and Static folders arrangement
I know that similar topics exist but for a half of the day i haven't found a single answer which could clear my doubts. So the question is : I've just started to practice with Django 3.2. But i have an issue with loading a templates and static files from specified folders. ├───project │ ├───first_app │ ├───migrations │ ├───static │ │ └───core │ ├───templates │ │ └───core │ └───__pycache__ ├───project │ ├───static │ └───css └───templates So i want to keep some "global" templates and static files in "project_root/templates" / "project_root/static" and some specific templates/statics within an assigned app (example of path: "project_root/app_name/templates/app_name/index.html" and "project_root/app_name/static/app_name/index.css". The option to keep templates and static files within an app works just well. But when i try to render some .html file from "project_root/templates/" in view.py it doesn't work. Is it correct to store templates/statics in such a way? How to arrange the file structures to make it work? How to point django which exactly template i want to render: from an app folder or from a root folder? Thanks for any response in advance! -
Error While Changing a field From CharField to ForeignKey
models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator from django.core.validators import MinValueValidator # Create your models here. class student(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE) student_name = models.CharField(max_length=100) semester = models.IntegerField(default=1, validators=[MaxValueValidator(8), MinValueValidator(1)]) stream = models.CharField(max_length=50) address = models.CharField(max_length=200) date_of_birth = models.DateField(auto_now=False, auto_now_add=False) roll_number = models.CharField(max_length=20) This is the model I have also registered the model in admin.py and in settings.py. When I am trying to see the student table it hits me with this error, after changing the username coloumn from CharField to ForeignKey, When I change back to Charfield the problem gets fixed. I cleared all the data using python manage.py flush. Then used makemigration and migrate. But the problem exists still. -
Django redirecting to home after login does not work
I am trying to redirect to homepage after login with no sucess settings.py LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', home, name='home'), path('defaultsite', home, name='home'), ] views.py def home(request): return render(request, 'general/index.html') ] I do not have a personalized Django login system (usying system default) but nothing seems to work. Changing LOGIN_REDIRECT_URL = 'home' to LOGIN_REDIRECT_URL = '/' does not work either. Strangely, LOGOUT_REDIRECT_URL = 'home' works like a charm. Any help? Using Django 4.1.7 & python 3.10.5 -
Is it possible to mock SimpleUploadedFile?
I have a function like this: def my_func(): [...] with open(full_path, "rb") as file: image.image = SimpleUploadedFile( name=image.external_url, content=file.read(), content_type="image/jpeg", ) image.save() print(f"{file_name} - Saved!") I would like mock the "SimpleUploadedFile" for a test (calling print...). Is it possible? A little bit of context: the function download and upload files. Maybe the test is not necessary... -
How to update articles in Python Django?
I made a blog using Django. I watched a lot of videos to make a function that the user can update/edit own articles. But I did not get it work. I'm new in Django, so if anyone can help me, I would be thankful. Here is my views.py: from django.shortcuts import render, redirect from .models import Article from django.http import HttpResponse from django.contrib.auth.decorators import login_required from . import forms #from django.core.paginator import Paginator from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger @login_required(login_url="/accounts/login/") def article_list(request): articles = Article.objects.all().order_by('-date') paginator = Paginator(Article.objects.all().order_by('-date'), 6) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) index = items.number - 1 max_index = len(paginator.page_range) page_range = paginator.page_range[0:max_index] return render(request, 'articles/article_list.html', {'articles':articles, 'items':items, 'page_range':page_range}) @login_required(login_url="/accounts/login/") def article_details(request, slug): article = Article.objects.get(slug=slug) return render(request, 'articles/article_details.html', {'article':article}) @login_required(login_url="/accounts/login/") def article_create(request): if request.method == 'POST': form = forms.CreateArticle(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('articles:list') else: form = forms.CreateArticle() return render(request, 'articles/article_create.html', {'form':form}) @login_required(login_url="/accounts/login/") def article_edit(request, slug): article = Article.objects.get(slug=slug) form = forms.CreateArticle(request.GET, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('articles:list') return render(request, 'articles/article_edit.html', {'form':form}) I was trying to do the view in article_edit. Here … -
Django Session works in localhost but not in remote server
I have set a session value during my login view upon successful user authentication. However, this session value is returning None in another view while i am trying to access it(The same code works in my local environment) login_view @csrf_excempt @api_view(['POST']) def login_view(request): # Authenticate user - upon success authentication request.session['username'] = username request.session['password'] = password # Able to print the stored session value here as well print(request.session.get('username')) **Redirect to landing.html** Once the user is authenticated and the landing page is loaded upon session check. def index(request): print("the session value is : ", request.session.get('username')) #this returns None if request.session.get('username') return render(request, 'landing.html') # if session present, render the landing.html page else: return render(request, 'auth.html') #if session not present, reload the login page again what am i missing here? I tried a lot to debug, but to no avail. while running in my local environment, i can see the cookies in the browser while i inspect the page, but it is not the case while i run it over my apache server. Also, i am using file based sessions and i have set the SESSION_ENGINE and SESSION_FILE_PATH accordingly. I also tried looking at similar questions already being asked on the same, … -
When QuerySet is evaluated when get_queryset is overridden
Have not understand very well how QS is evaluated when overriden. Based on leedjango question, we are able to override get_queryset in a view class. In this same example, I have not been able to understand when the get_queryset method is returning the QS evaluated. We know how QS are evaluated in general, as it is explained in eugene question. For instance, I have the following components: Front End sending GET request to the appropriate URL: //Dashboard.js: export default function Dashboard() { const [tableData, setTableData] = useState([]); const getUserSchools = () => { getUser({ email: keycloak.email }).then((response) => { const { data: users } = response; if (users.length) { const appUser = users[0]; axios .get(`/api/school/list/?user_id=${appUser.id}`) .then((data) => { setTableData(data.data.results); }) .catch((err) => { /* eslint-disable-next-line */ console.error(err); setTableData([]); }); } }); }; Then, it hits the school-urls.py looking for which view is related to that URL: urlpatterns = [ url(r"^list/$", SchoolsList.as_view()), ] SchoolsList is the appropriate View which is overriding get_queryset and returns the queryset: #list.py class LargeResultsSetPagination(pagination.PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 100 class SchoolsList(generics.ListAPIView): pagination_class = LargeResultsSetPagination serializer_class = SchoolGetSerializer def get_queryset(self): queryset = School.objects.all() user_id = self.request.query_params.get('user_id', None) if (user_id is not None): queryset … -
How to load the display name when using `values()` of a `CharField` when using `models.TextChoices` in Django
I have a model that looks like this: models.py class Client(models.Model): class Status(models.TextChoices): CD = "CD", "Closed" UC = "UC", "Under Contract" status = models.CharField( max_length=2, choices=Status.choices, default=Pipeline.CD, ) and a view that looks like this: views.py class ClientsListView(generic.ListView): queryset = Client.objects.all() If I wanted to grab the display name of the status field, it would look something like this: clients.html {% for client in object_list %} {{ client.get_status_display }} {% endfor %} I want to change the ClientsListView class in views.py to use values() so I can limit the number of fields that are loaded so I changed it to this: class ClientsListView(generic.ListView): def get_context_data(self, **kwargs): context = super().get_context_data() context["clients"] = Clients.objects.all().values() return context But now I don't have access to the display name of status. How would I go about loading that into what is returned in values()? -
my registration view is not saving user data to database django python (only through admin panel)
I just started learning Django and got somewhat into it so far, but I've been stuck on why my views are not saving the model data successfully to the database (I'm using postgres). I found out that I'm able to add the models through the admin panel so I believe the fields are fine, I think it may be due to configuration? I'm not too confident on that, any help would be appreciated! Here's the project structure and code below Project Structure views.py from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect from .forms import RegistrationForm, LoginForm from django.contrib import messages from django.http import * from .models import newUser, userEvents def registerView(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): # if the form is filled and data is valid if User.objects.filter(username=form.cleaned_data['user_name']).exists(): # Check if the record exists # in the DB already # redirects to the success page redirect('login/') else: createUser = newUser(user_name=form.cleaned_data['user_name'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], email_address=form.cleaned_data['user_email'], date_of_birth=form.cleaned_data['date_of_birth']) createUser.save() # save the user to the database User.objects.create_user(createUser.user_name, createUser.email_address, form.cleaned_data['user_pass']) return render(request, 'login.html') # if a GET (or any other method) we'll create a blank form else: form = RegistrationForm() # TODO: Create register.html template and then test! … -
Django tutorial, Page not found <int:question_id>
My views.py from django.http import HttpResponse, Http404 from django.shortcuts import render, get_object_or_404 from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) My urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('/', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), ] When I going at 'http://127.0.0.1:8000/polls/1/' I receive 'Page not found' error but I definitely have this question_id, I can see this question_id in shell, it doesn't matter what ID I have write I always receive the same issue. -
Django session is lost after redirection to the same host
I've a class based django view where at some certain point I've some variables in the request.session, the user has been logged in in that view (just a few lines before), and I make a redirection to /sth/ . When the browser reaches /sth/, it has none of the previously set variables, they're gone, and no idea why. Checking the browser, the sessionid is different, but no idea why. Anyone would have an idea what can be problem, what to check? Thanks. -
Reverse for 'products_category' with keyword arguments '{'products_po_category': <QuerySet [<Product: Maybach>]>}' not found
Hi I need to implement the following: I have a form with a category selection, and based on the selected category, I need to redirect the user to a page with products for this category. URLS.PY from django.urls import path from first.views import productsHTML, productHTML, products_category urlpatterns = [ path("products_category", products_category, name = "products_category"), path("productsHTML/<str:uuid>", productHTML, name = "productHTML"), path("productsHTML/", productsHTML, name = "productsHTML"), ] VIEWS.PY from django.shortcuts import render, redirect from .models import Product from .forms import CategoryChoice def productsHTML(request): form = CategoryChoice(request.POST or None) if request.method == 'POST' and form.is_valid(): category = form.cleaned_data['category'] products_po_category = Product.objects.filter(category=category) return redirect('products_category', products_po_category=products_po_category, permanent=True) all_products = Product.objects.all() context = { 'form': form, 'products': all_products, } return render(request, "products.html", context) def products_category(request,products_po_category): context = { "products_po_category": products_po_category } return render(request, "product_category.html", context) Through form.cleaned_data['category'] I get data about the selected category and then, through Product.objects.filter(category=category) I get the objects of this category and after all this I redirect to the page with the products of this category, passing the list of objects of the selected categories. FORMS.PY from django import forms from .models import Product class CategoryChoice(forms.ModelForm): class Meta: model = Product fields = ('category',) widgets = { 'category': forms.Select(), } full text … -
Celery raises an Received unregistered task of type 'default.add error
I have a simple Django based Celery application. The folder structure is: celery_poc | |--db |----celery.py |----settings.py | |--demoapp |----apps.py |----models.py |----tasks.py The content of celery.py is : import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "db.settings") app = Celery("db") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() The content of settings.py is: INSTALLED_APPS = [ 'django_celery_results', 'demoapp', ] CELERY_BROKER_URL = "amqp://guest@localhost//" CELERY_RESULT_BACKEND = 'django-db' The content of tasks.py is: from celery import shared_task @shared_task def add(x, y): return x + y if __name__ == "__main__": add.delay(4, 4) I'm using RabbitMQ as the broker and Postgres as the results backend. When I ran tasks.py I get the following error from Celery: [2023-03-23 15:33:37,528: ERROR/MainProcess] Received unregistered task of type 'default.add'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: '[[4, 4], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (81b) Thw full contents of the message headers: {'lang': 'py', 'task': 'default.add', 'id': '65488acd-5591-441a-b7d6-f5ff73a564e1', 'shadow': None, 'eta': None, 'expires': None, 'group': None, 'group_index': None, 'retries': 0, 'timelimit': [None, None], 'root_id': '65488acd-5591-441a-b7d6-f5ff73a564e1', 'parent_id': None, 'argsrepr': '(4, 4)', 'kwargsrepr': '{}', … -
Django No records found on query
I'm trying to filter web search results of apartments on django3 but it doesn't matter what I put on the filters while filling the form, It shows the message "no records found" no mater how do I fill the form. The database is already populated. my views.py def apartments_list(request): name = request.GET.get('name') address = request.GET.get('address') status = request.GET.get('status') price_range = request.GET.get('price_range') no_of_person = request.GET.get('no_of_person') bed_type = request.GET.get('bed_type') query = Q() if name: query &= Q(title__icontains=name) if address: query &= Q(apartmentaddress__city__icontains=address) if no_of_person and no_of_person.isdigit(): query &= Q(persons=int(no_of_person)) if bed_type: query &= Q(bed=bed_type) if price_range: min_price = price_range.split('-')[0] max_price = price_range.split('-')[1] query &= Q(price__gte=min_price) query &= Q(price__lte=max_price) page = request.GET.get('page', 1) apartments = Apartment.objects.filter(query).order_by('price') paginator = Paginator(Apartment.objects.filter(query), 10) try: apartments = paginator.page(page) except PageNotAnInteger: apartments = paginator.page(1) except EmptyPage: apartments = paginator.page(paginator.num_pages) context = {} context['apartments'] = apartments context['name'] = name context['address'] = address context['no_of_person'] = no_of_person context['bed_type'] = bed_type context['price_range'] = price_range My models.py class Apartment(models.Model): APARTMENT_CHOICES = ( ("Available", "Available"), ("Booked", "Booked") ) clean_status = models.BooleanField(default=False) inspected_status = models.BooleanField(default=False) title = models.CharField(max_length=100) apartment_status = models.CharField( max_length=255, choices=APARTMENT_CHOICES, default='Available') services = models.CharField(max_length=255) capacity = models.IntegerField() bed = models.CharField(max_length=100) price = models.IntegerField() persons = models.IntegerField() category = models.ForeignKey(ApartmentCategory, on_delete=models.CASCADE) owner = … -
Better approach to serialize data that contains multiple related Models using Django Rest Framework
Background I am new to Django and DRF and I am currently writing a view that handles a GET request. The view will return a JSON that contains data associated with 5 related models. Here is a visualization of my database . And this is what I expect to get [ { "word": "hello", "entries": [ { "tag": null, "link": "", "value": "TEST" }, { "tag": null, "link": "", "value": "STUFF" } ] }, { "word": "Hello", "entries": [] } ] Problem My current approach is to use Django query to construct a self defined object and then define a DRF serializer to serialize it. The code looks like this # Inner Object class DetailEntry(): def __init__(self, tag, link, value): self.tag = tag self.link = link self.value = value # Outer Object class ReviewEntry(): def __init__(self, word, entries): self.word = word self.entries = entries class GetReview(APIView): def get(self, request, format=None): # get current user currentUser = User.objects.get(id=request.user.id) records = Record.objects.filter(user_id=currentUser) reviewEntries = [] for record in records: word = record.word_id quotes = Quote.objects.filter(record_id=record) detailEntries = [] for quote in quotes: tag = quote.tagAssignment_id link = quote.link value = quote.value detailEntries.append(DetailEntry(tag, link, value)) reviewEntries.append(ReviewEntry(word, detailEntries)) s = ReviewSerializer(reviewEntries, many=True) return Response(s.data) … -
How to send django template form to telegram bot in Django
I can't find way to send django template form to telegram bot in Django like send message to telegram bot via website! I don't know how to do this so i need help with explaining -
i have creating my app django but i can't use it
i'm using django i create my app with this commande django-admin startapp Bplan first it look everythings is right the new folder was added with all his fles i also add it in INSTALLED_APP [ ...'Bplan',...] but when i try to check the list off installed app with this commande : "python manage.py shell -c "from django.apps import apps; print([app.name for app in apps.get_app_configs()])" it show only the default app also when i try to migrate to database with python3 manage.py migrate every this look ok in the terminal but i cant see the new tables on my postgresql can you help me please -
django-fsm can't transition state
Why do I get the error below when I tried to do the transition? Is this a bug? Thanks >>> t = Task.objects.first() >>> t.state "(0, 'Open')" >>> t.to_in_progress() Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/dingli/projects/personal/django_history_fsm_guardian/lib/python3.11/site-packages/django_fsm/__init__.py", line 573, in _change_state return fsm_meta.field.change_state(instance, func, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/dingli/projects/personal/django_history_fsm_guardian/lib/python3.11/site-packages/django_fsm/__init__.py", line 339, in change_state raise TransitionNotAllowed( django_fsm.TransitionNotAllowed: Can't switch from state '(0, 'Open')' using method 'to_in_progress' Here is the model. STATES = ('Open', 'In Progress', 'Resolved', 'Re Opened', 'Closed') STATES = list(enumerate(STATES)) class Task(models.Model): title = models.CharField(max_length=100, null=False) description = models.TextField() state = FSMField(default=STATES[0], choices=STATES) def __str__(self): return f'{self.title}: {self.description}' @transition(field=state, source=['Open', 'Re Opened'], target='In Progress') def to_in_progress(self): pass @transition(field=state, source='In Progress', target='Resolved') def to_resolved(self): pass I also tried the following approach, but got the same error. @transition(field=state, source=[(0, 'Open'), (3, 'Re Opened')], target=(1, 'In Progress')) def to_in_progress_1(self): pass -
Trying to setup formsets for related models in Django (form_kwargs issues?)
Model code looks like this: class Question(models.Model): text = models.CharField(max_length=500) def __str__(self): return self.text def has_choices(self): return self.choices.exists() class Camp(models.Model): # Other attributes questions = models.ManyToManyField( Question, through="CampQuestion", related_name="camps" ) class CampQuestion(models.Model): camp = models.ForeignKey( Camp, on_delete=models.PROTECT, related_name="camp_questions" ) question = models.ForeignKey( Question, on_delete=models.PROTECT, related_name="camp_questions" ) def __str__(self): return f"{self.camp.name} - {self.question.text}" class Choice(models.Model): question = models.ForeignKey( Question, on_delete=models.PROTECT, related_name="choices" ) text = models.CharField(max_length=500) def __str__(self): return self.text class Answer(models.Model): registration = models.ForeignKey( "Registration", on_delete=models.PROTECT, related_name="answers" ) question = models.ForeignKey( Question, on_delete=models.PROTECT, related_name="answers" ) user_response = models.CharField(max_length=500, blank=True, null=True) user_choice = models.ForeignKey( Choice, on_delete=models.PROTECT, null=True, blank=True ) class Registration(models.Model): person = models.ForeignKey(Person, on_delete=models.PROTECT) # Other attributes I'm trying to setup an Answer formset that contains 1 AnswerForm for every Question tied to a Camp - but I can't seem to make it happen. My AnswerForm looks like this (if a Question has Choice models we make it a Select - otherwise it's a Text field): class AnswerForm(forms.ModelForm): class Meta: model = Answer fields = ["user_response", "user_choice"] widgets = { "user_response": forms.TextInput(attrs={"class": "form-control"}), "user_choice": forms.Select(attrs={"class": "form-control"}), } def __init__(self, *args, **kwargs): question = kwargs.pop("question", None) super().__init__(*args, **kwargs) if question and question.has_choices(): self.fields["user_choice"].queryset = Choice.objects.filter( question=question ) self.fields["user_choice"].label = question.text self.fields["user_response"].required = … -
Is there a way to get my "Author" field prepopulating in my Django form?
I am making a review site and I have a Movie, Game, Show, and Review model and within my Review model I have "author" which is a foreign key and in my review form I have the "author" field and I want it to be populated with the username of the user that is logged in and leaving the review, I have searched this site and googled for hours and can't seem to find any solution ill leave my code I have at the moment below. Any help will be greatly appreciated! models.py forms.py views.py I have tried forcing it by using review.author = request.user, in my views.py and I have also tried it with request.user.username and finally I tried to do it using initials -
mod_wsgi for django with conda environment in Windows doesn't work
This is my first post in stackoverflow. I'll try to explain to you what I've done with steps and what I've done to try to solve the problems. Problem I'm struggling with the configuration of mod_wsgi for my django project. When i try to connect to localhost:8001 (port listened by mod_wsgi) I get an infinite loading or a "This site can’t be reached" page. What i've done I have installed apache2.4 with apachelounge (https://www.apachelounge.com/download/) in my C:\ drive. I have installed anaconda (I haven't set conda in path) and I created my environment for my django project (called production). It runs correctly if I run the command python manage.py runserver (if i go to http://localhost:7000/ (port set to manage.py) it works. I installed mod_wsgi in my conda environment with pip install mod-wsgi. Files httpd.conf (C:\Apache24\conf\httpd.conf) ServerName localhost Listen 8001 ... LoadFile "C:/Users/my_name/anaconda3/envs/production/python39.dll" LoadModule wsgi_module "C:/Users/my_name/anaconda3/envs/production/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "C:/Users/my_name/anaconda3/envs/production" WSGIScriptAlias / "C:/Users/my_name/my_path/Analyser/wsgi.py" <Directory "C:/Users/my_name/my_path/Analyser"> <Files wsgi.py> Require all granted </Files> </Directory> LogLevel info WSGIApplicationGroup %{GLOBAL} wsgi.py (C:/Users/my_name/my_path/Analyser/wsgi.py) import os import sys from django.core.wsgi import get_wsgi_application # add the project folder to the path (otherwise it says (core: ModuleNotFound) _BASE_DIR = r'C:\Users\my_name\my_path\Analyser' if _BASE_DIR not in sys.path: sys.path.append(_BASE_DIR) os.environ['DJANGO_SETTINGS_MODULE'] = 'core.settings' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") … -
is there any method that admin can manually verify the user who is registered an want to log in? [closed]
enter image description here this is the views.py section enter image description here And this is error i got after running try to log in enter image description here This is the models.py section My concept is simple, the new doctor is register and try to log in he can't log in because the admin is not approved him. If admin approves the verified booleanfield changes to true then doctor can log in.. kindly help to resolve this issue?? -
Split pdf files from request and send the splitted pdf's as response without saving it locally Django/Python
As mentioned in the title I have an API endpoint which receives a PDF file object from request. I need to split these PDF into multiple pdf's and send these split pdf's as response without saving any of these files locally using PYTHON inside a zip folder. Thanks in Advance!! I'm able to split and create zip if I save the files locally using pypdf2 but I just wanna know is there a way to split and put in a zip without saving locally.