Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django (RF) : Allow child comments (MPTT model) to be created within same Post as parent comment
I have a Post model and Comment model. The second one based on MPTT model to achive comments arrangement in a tree format. Everything works but the problem is to restrict new child Comment to be linked with other then parent Post on creation. Example: Let's say I have Post objects with ID = 1 and 2. I have a parent Comment object with ID = 10 linked with Post ID = 1 (defined above). Now I can create a new child Comment object, wire it with a parent Comment but Post ID may be passed equal to 2 which is not the same as parent's one. And as a result: related comments devided in a separate Post objects. I can just make some validation like (schema without python syntax): if new_comment.post_id != new_comment.parent__post_id: return Response({"error": "Child comment must be linked with the same post as parent"}) But is there any Django way to do this to make this validation work in django-admin as well? For example when I create a Comment object and choose a parent in a dropdown section then only Post related to parent Comment will be available in a dropdown section? My code : Models: class … -
Unit test exceptions for redis in DRF
I have serializers.py like this for post request import redis redis_client = redis.Redis().json() class MySerializer(serializers.Serializer): ... def validate(self, attrs): ... try: ... except redis.ConnectionError: raise ValidationError("Redis server is down.") except redis.TimeoutError: raise ValidationError("Redis server is slow or unable to respond.") How do i write unit test cases for these two exceptions ? -
Does `cache.set()` use `version=1` by default instead of `version=None` in Django?
If I only set and get David with version=0, then I can get John and David in order as shown below. *I use LocMemCache which is the default cache in Django and I'm learning Django Cache: from django.core.cache import cache cache.set("name", "John") cache.set("name", "David", version=0) print(cache.get("name")) # John print(cache.get("name", version=0)) # David And, if I only set and get David with version=2, then I can get John and David in order as well as shown below: from django.core.cache import cache cache.set("name", "John") cache.set("name", "David", version=2) print(cache.get("name")) # John print(cache.get("name", version=2)) # David But, if I only set and get David with version=1, then I can get David and David in order as shown below so this is because John is set with version=1 by default?: from django.core.cache import cache cache.set("name", "John") cache.set("name", "David", version=1) print(cache.get("name")) # David print(cache.get("name", version=1)) # David In addition, if I set and get John and David without version=1, then I can get David and David in order as well as shown below: from django.core.cache import cache cache.set("name", "John") cache.set("name", "David") print(cache.get("name")) # David print(cache.get("name")) # David I know that the doc shows version=None for cache.set() as shown below: ↓ ↓ Here ↓ ↓ cache.set(key, value, … -
Unused path imported from django.urls
THIS IS THE ERROR Unused path imported from django.urlsPylintW0611:unused-import I don't know how to solve this. iam using vscode django version 4.2.4 Python 3.11.4 clientes/urls.py from django.urls import path urlpatterns = [ ] -
Django hosting providers [closed]
I am searching for a django hosting service provider and I found some hosting service providers which costs a little bit high. Since we are starting a small scale ecommerce startup we cant afford that much pricing they offer Can someone suggest me a hosting service provider that hosts a django application at a cheaper rate? -
mozilla_django_oidc package returning redirect error
Getting the following error while trying to login with keycloak through django application (mozilla_django_oidc). Settings, redirect URI - everything looks fine. After providing the login credentials, it suppose to redirect to the app itself and by that time encountering this error. Any idea? -
Asynchronous tasks in Django
I want to implement a telegram group parser (namely users) into the Django application. The idea is this, from the post request I get the name of the group entered into the form, I pass it to the asynchronous function (which lies in a separate file) and parsing starts. And so at a call of asynchronous function in view, constantly I receive errors. Such as "RuntimeError('The asyncio event loop must not change after connection", "RuntimeError: There is no current event loop in thread 'Thread-1'" etc. Please help me, how would this be better organized? Function for parsing users below: api_id = **** api_hash = '*****' phone = '+******' client = TelegramClient('+********', api_id, api_hash) client.start() async def dump_all_participants(url): """Writes a csv file with information about all channel/chat participants""" offset_user = 0 # member number from which reading starts limit_user = 200 # maximum number of records transferred at one time all_participants = [] # list of all channel members filter_user = ChannelParticipantsSearch('') while True: participants = await client(GetParticipantsRequest(await client.get_entity(url), filter_user, offset_user, limit_user, hash=0)) if not participants.users: break all_participants.extend(participants.users) offset_user += len(participants.users) all_users_details = [] # list of dictionaries with parameters of interest to channel members for participant in all_participants: all_users_details.append({"id": participant.id, … -
Nested folder structure getting issue while Customize the Auth User Please help me out
AUTH_USER_MODEL = 'modules.user.models.CustomUser' Please help me out how can i add more column in auth user table and use in login process. What is the best folder structure in django I want to implement the admin module, student module and teacher module and cms module in our system -
Navigate always to a specific page though all pages are public in Reactjs
I have made a PrivateRoute for a specific page. All the pages are public (Anyone can view them) except the PrivateRoute page. If a user is unauthorized then the route always navigates to the page which is declared in logUser function. I am using Python Django for building APIs. app.js import "./App.css"; import { Fragment } from "react"; import { BrowserRouter, Routes, Route } from "react-router-dom"; import Home from "./pages/Home"; import Login from "./pages/Login"; import Register from "./pages/Register"; import Post from "./pages/Post"; import Details from "./pages/Details"; import HeaderNav from "./components/Navbar"; import Footerbar from "./components/Footer"; import PrivateRoute from "./utils/PrivateRoute"; import { AuthProvider } from "./context/AuthContext"; function App() { return ( <Fragment> <BrowserRouter> <AuthProvider> <HeaderNav /> <div className="bg-gray-100 w-full h-full"> <Routes> <Route element={<PrivateRoute />} path="/post"> <Route element={<Post />} path="/post" /> </Route> <Route element={<Home />} path="/" /> <Route element={<Post />} path="/post" /> <Route element={<Details />} path="/post/:id" /> <Route element={<Register />} path="/register" /> <Route element={<Login />} path="/login" /> </Routes> </div> <Footerbar /> </AuthProvider> </BrowserRouter> </Fragment> ); } export default App; PrivateRoute.js import { Navigate, Outlet } from "react-router-dom"; import { useContext } from "react"; import AuthContext from "../context/AuthContext"; const PrivateRoute = () => { const { username } = useContext(AuthContext); return username ? <Outlet … -
Problems with save() methof of django model
My prints are cycling and then the error message appears But download_url which appears in the console seems to be correct and it works for me, but why code doesn't work It's like a recursion in save method till Yandex block my downloads with "Resource not found" def save(self, *args, **kwargs): # Сначала сохраняем объект if self.photo_url: base_url = 'https://cloud-api.yandex.net/v1/disk/public/resources/download?' public_key = 'https://disk.yandex.ru/i/EaosKvCf-SDzag' #self.photo_url # Используем поле photo_url как public_key final_url = base_url + urlencode(dict(public_key=public_key)) print(final_url) response = requests.get(final_url) print(response.json()) download_url = response.json()['href'] print(download_url) download_response = requests.get(download_url) file_content = download_response.content file_name = self.photo_url.split('/')[-1] temp_file = File(io.BytesIO(file_content), name=file_name) self.photo.save(file_name, temp_file, save=False) self.save() # Сохраняем с обновл super().save(*args, **kwargs) -
How to use @property decorator with annotate Django Query set
Model.py class InvoiceItem(models.Model): quantity = models.IntegerField() items_price = models.ForeignKey(PriceMaster,on_delete=models.CASCADE) invoices = models.ForeignKey(Invoice, on_delete=models.CASCADE,null=True,blank=True) create_at = models.DateField(auto_now_add=True) create_by = models.ForeignKey(User, on_delete=models.CASCADE) @property def net_amount(self): self.total = self.quantity * self.items_price.price self.gst = self.total * self.items_price.gst.gst / 100 self.net_total = self.total + self.gst return self.net_total View.py invoiceItem_id=InvoiceItem.objects.values("invoices__id","invoices__invoice_no","invoices__create_by__username","invoices__create_at","invoices__status").annotate(total = Sum('net_amount')) **Can we use @property decorator in above mention scenario ** -
Showing 'Import Error' when I import forms
When I try to import my forms in views.py , it is showing the following from .forms import QuestionsForm, OptionsFormSet,UserRegisterForm ImportError: cannot import name 'QuestionsForm' from 'teachers.forms' Here 'teachers' is the name of the app I created the following teachers/forms.py from users.models import Quiz,Questions,Answers,UserAnswer,Results from django.forms import ModelForm from django.forms import inlineformset_factory class QuestionsForm(forms.ModelForm): class Meta: model = Questions fields = ['text', 'quiz', 'correct'] class OptionsForm(forms.ModelForm): class Meta: model = Answers fields = ['text'] OptionsFormSet = inlineformset_factory(QuestionsForm, Answers, form=OptionsForm, extra=4) I imported this in my teachers/views.py from .forms import QuestionsForm, OptionsFormSet,UserRegisterForm @login_required @user_passes_test(email_check) def create_question(request): if request.method == 'POST': question_form = QuestionsForm(request.POST) options_formset = OptionsFormSet(request.POST, prefix='options') if question_form.is_valid() and options_formset.is_valid(): question = question_form.save() # Save the question form # Set the question instance for each option before saving the options formset options = options_formset.save(commit=False) for option in options: option.question = question option.save() return messages.success('Questions saved successfully') # Redirect to a success page else: question_form = QuestionsForm() options_formset = OptionsFormSet(prefix='options') context = {'question_form': question_form, 'options_formset': options_formset} return render(request, 'teachers/create_question.html', context) If nothing's wrong with my forms then why is it showing an import error? -
How to set proxy header host to my domain? [duplicate]
I have tried to use authorization with vk.com. In local server it worked perfect, but when I deployed the project to server I got the error answer from vk: {"error":"invalid_request","error_description":"redirect_uri is incorrect, check application redirect uri in the settings page"} I use django, gunicorn, nginx I see, that error in url that generate social-auth-app-django library that I use: https://oauth.vk.com/authorize?client_id=51715081&redirect_uri=http%3A%2F%2F**127.0.0.1%3A8001**%2Fcomplete%2Fvk-oauth2%2F%3Fredirect_state%3DsDvsG5lNFRCXvxdqaXeBHTVpPWpXkHaj&state=sDvsG5lNFRCXvxdqaXeBHTVpPWpXkHaj&response_type=code it contain redirect_uri=http%3A%2F%2F127.0.0.1%3A8001 127.0.0.1:8001 uses gunicorn, but here must be my domain name As I think the problem is in nginx config: server { listen 80; listen [::]:80; server_name my.domain; return 301 https://$server_name$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; server_name my.domain; ssl_certificate /etc/letsencrypt/live/my.domain/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/my.domain/privkey.pem; location /.well-known { alias /var/www/my.domain/.well-known; } root /var/www/html; index index.html index.htm index.nginx-debian.html; location /media { alias /home/www/trufy/my_django_project/media; } location /static { alias /home/www/trufy/my_django_project/static; } location / { proxy_pass http://127.0.0.1:8001; #proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Host $proxy_add_x_forwarded_for; # add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; # add_header Access-Control-Allow-Origin *; } } I as understand, I need to add proxy_set_header Host $host; in location / {}, but when I do it, restart nginx and open site I get: Bad Request (400) Help me please, what i need … -
django admin shows custom percentInput widget but in view mode values are not formatted
i am having this fancy percentinput widget that allows me to input values as if they were percents: like 47, and it saves as 0.47 decimal, but also shows me back 47.change this works perfectly for me but when the user has no right to "change" the object they all render as 0,4700 in view or readonly mode.readonly class PercentInput(NumberInput): def __init__(self, attrs=None): if attrs is None: attrs = {} attrs['type'] = 'number' attrs['step'] = 1 attrs['style'] = 'width:50px;' attrs['max'] = 100 attrs['min'] = 0.0 super().__init__(attrs) def format_value(self, value): if value == Decimal(0): return 0 if value is None: return '' return f"{value * 100}".rstrip('0').rstrip('.') # Format as percentage without decimal places #:.0f def value_from_datadict(self, data, files, name): value = data.get(name) if value: return Decimal(value) / 100 return None also the form i use class SubDealForm(forms.ModelForm): class Meta: model = SubDeal fields = '__all__' widgets = { 'player_percent': PercentInput(), 'sub_percent': PercentInput(), 'optional_rb': PercentInput(), 'wdfee': PercentInput(), } and ofc this enabled in my ModelAdmin: form = SubDealForm How to make them look formatted as percent too? without making custom duplicate functions in modelAdmin like def value_as_percent() or making custom template for it? -
Nginx Reverse Proxy's problematic behaviour
I need your help related to nginx and reverse proxy: I have a frontend running on port 80 and a backend running on port 8000 using reverse proxy in nginx both of them are being connected from same domain url (eg. https://abc123.com it is an https ->ALB{aws}->http->nginx and https://abc123.com:8000 )using different ports most of the time port 8000 pages work on alternate hits i.e for first they show a 404 and when I reload it connects, on next reload it again shows 404 and so on. I have added caching also but did not change any thing.. This port 8000 is routing to backend django server at 8001 port. Frontend is running perfectly.Backend is creating problems.. How can I resolve this? eg. For first abc123.com:8000/marvels show a 404 and when I reload it connects to corect page, on next reload it again shows 404 and so on... similar case is for all the paths related to django backend. -
How to redirect to home URL after Django Allauth login with Google?
I'm using Django Allauth to provide Google authentication for my website. Everything is working fine, except that I get redirected to 127.0.0.1:8000/accounts/google/login/callback/?state=2CXclEHzhr58&code=4%2F0Adeu5BW1_2pqwk7edcaJ7nLR7b8hmBcfRX2_605538Il2j3dWc0jYwWzEbwV10mMnmI2oA&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+openid&authuser=2&prompt=consent# instead of just 127.0.0.1:8000/ even tho I set LOGIN_REDIRECT_URL = "home". The redirect itself works fine, in the sense that I get the home page, but is there a way to also have the link be just 127.0.0.1:8000/? Otherwise, do you know of any alternatives I could use? I'm also thinking this could be caused by Google's API, but can't tell how. Thanks in advance! Tried to set LOGIN_REDIRECT_URL = "home" and ACCOUNT_SIGNUP_REDIRECT_URL = "home" -
Why is pipenv giving me a permission error?
I tried to install django with this: pipenv install django But, it returns this: Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Scripts\pipenv.exe\__main__.py", line 7, in <module> File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\vendor\click\core.py", line 1130, in __call__ return self.main(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\cli\options.py", line 58, in main return super().main(*args, **kwargs, windows_expand_args=False) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\vendor\click\core.py", line 1055, in main rv = self.invoke(ctx) ^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\vendor\click\core.py", line 1657, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\vendor\click\core.py", line 1404, in invoke return ctx.invoke(self.callback, **ctx.params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\vendor\click\core.py", line 760, in invoke return __callback(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\vendor\click\decorators.py", line 84, in new_func return ctx.invoke(f, obj, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\vendor\click\core.py", line 760, in invoke return __callback(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\cli\command.py", line 233, in install do_install( File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\routines\install.py", line 61, in do_install ensure_project( File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\utils\project.py", line 26, in ensure_project if project.s.PIPENV_USE_SYSTEM or project.virtualenv_exists: ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\project.py", line 252, in virtualenv_exists if os.path.exists(self.virtualenv_location): ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\project.py", line 449, in virtualenv_location self._virtualenv_location = self.get_location_for_virtualenv() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\project.py", line 274, in get_location_for_virtualenv return str(get_workon_home().joinpath(self.virtualenv_name)) ^^^^^^^^^^^^^^^^^ File "C:\Users\swayam\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\utils\shell.py", line 195, in get_workon_home os.makedirs(expanded_path, exist_ok=True) File "<frozen os>", line 225, in makedirs PermissionError: [WinError 5] Access is denied: 'C:\\Users\\swayam\\.virtualenvs' I was trying to … -
Django 'none' values from ajax
My views: def deleteDepartement(request): object_id = request.POST.get('Id') name= request.POST.get('name') print(object_id) print(name) try: D=Department.objects.get(id=object_id) except: print("NOT FOUND") return redirect('department') JavaScript code: $.ajax({ type: 'POST', url: "{% url 'deleteDepartement' %}", data: { csrfmiddlewaretoken: '{{ csrf_token }}', Id:objectId, name:'test', }, }); I got none in value in django views. When I console.log I got the id, but when i try to sent it i got none. Any suggestions please? -
Django Field comprising of other fields
enter image description here class Car(models.Model): stockid = models.AutoField(primary_key=True) galleryIndex = models.IntegerField() title = make + model + year make = models.CharField(max_length=50) model = models.CharField(max_length=200) year = models.IntegerField() price = models.IntegerField() location = models.CharField(max_length=50) mileage = models.IntegerField() transmission = models.BooleanField(default=False) engine = models.CharField(max_length=200) registration = models.CharField(max_length=200) body = models.CharField(max_length=200) color = models.CharField(max_length=200) sellerComments = models.CharField(max_length=300) I want to achieve the title field, actually i need this to find the car model! like in query i will send a string for example: "MAKE MODEL" user can either send a make a make or a model, it cant be figured out bcs theres a single search box! anyways if i have a "title field" i can use it to query data in this way " where title contains query string!" and thats the only logic i can think of! any help would be great! Query Make and Model according to a String! -
How to skip over rows causing `Integrity Error` in unique constraints?
This is a model that I have and I want to modify it so One Advisor can only have one response with status Accepted, to do that I am creating a unique constrain in class Meta: class AdvisorResponse(UUIDTimeStampedModel): chat_request = models.ForeignKey(ChatRequest, on_delete=models.CASCADE, related_name='advisor_responses', null=True) advisor = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) status = models.CharField(max_length=10, choices=ADVISOR_REQUEST_STATUS, default=ADVISOR_REQUEST_STATUS_ACCEPTED) # Data field holds calculated indexed data which is for UI consumption and doesn't change over time. data = JSONField(default=dict, blank=True) class Meta: constraints = [ models.UniqueConstraint( fields=['advisor', 'status'], name='unique_advisor_accepted_response', condition=models.Q(status=ADVISOR_REQUEST_STATUS_ACCEPTED) ) ] However, there are already existing database that has duplicate Status accepted for one response and that is causing Integrity Error: psycopg2.errors.UniqueViolation: could not create unique index "unique_advisor_accepted_response" DETAIL: Key (advisor_id, status)=(11, accepted) is duplicated I don't want to delete data in prod, how should I approach this migration so constraint on previous data is not applied like skipped over and only on new data being inserted. -
Error ```Forbidden (403) CSRF verification failed. Request aborted.``` when try to login in admin
The error occurs only on the remote server. Locally everything is fine. seems to be no problem with static Didn't touch anything here: ALLOWED_HOSTS = [] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.middleware.common.CommonMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] Using: django, nginx, docker, git actions. Where is trouble? Another problem when I insert a link without an closed bracket (my-dns.com/admin) redirects me to 127.0.0.1/admin/ without port. when link is fine, trouble with csrf token -
Add a set of 'sub-forms' (probably form set) to a ModelForm
I'm making some progress in solving this. What I want to model is this: I have a model for materials, a model for projects, and an intermediary model to specify more data to the many-to-many relationship between them. The objective is to allow a project not only to have multiple materials but also to specify a quantity for each. These are my models: class Material(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) description = models.CharField(max_length=3000, blank=True) unit = models.CharField(max_length=20) price = models.DecimalField(max_digits=9, decimal_places=2, validators=[MinValueValidator(0)]) created_by = models.ForeignKey(to=User, on_delete=models.CASCADE, related_name='materials') created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.name} (${self.price}/{self.unit})' class Project(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) description = models.CharField(max_length=3000, blank=True) materials = models.ManyToManyField(to=Material, through='ProjectMaterialSet', related_name='projects') created_by = models.ForeignKey(to=User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.name}' class ProjectMaterialSet(models.Model): id = models.AutoField(primary_key=True) project = models.ForeignKey(to=Project, on_delete=models.CASCADE) material = models.ForeignKey(to=Material, on_delete=models.CASCADE) material_qty = models.PositiveIntegerField(default=1) Now, I have successfully rendered the project form containing a checkbox list of the materials (without the quantity feature), another form listing just one material as a checkbox, and a field for the quantity (a form of the ProjectMaterialSet model). Now, the part I'm struggling with is how to combine both. So far, I think what I need to do … -
Get access token from HttpOnly cookie for server side request with getServerSideProps
So, I've been working on a project using nextjs for frontend and django for backend. I'm also using HttpOnly cookies for my access and refresh tokens that I'm setting from my django backend. So, the thing is, if I send my requests on the client side by using useEffect for example, it works just fine. My django custom authenticate can read the cookie off of the request with no trouble. The problem is for when I use any server side function like getServerSideProps. I've checked and the problem is that the cookie isn't being sent with the request to the backend. I've tried to manually add the cookie to the request headers like this : export async function getServerSideProps(context) { const { req } = context console.log('accessToken >>> ', req.cookies.access); // Undefined const response = await axiosInstance.get('http://localhost:8000/api/project/projects', { headers: { "Authorization" : `Bearer ${req.cookies.access}` } }); const data = response.data; return { props: { data, }, }; } // axiosInstance export const axiosInstance = axios.create({ baseURL: "http://127.0.0.1:8000/api/", timeout: 20000, withCredentials: true, headers: { "Content-Type": "application/json", "Accept": "application/json" } }) But the problem is that the cookie I'm trying to read always gives back an undefined value. I've tried some other … -
How to redirect user in template view's get_context_data
Does anyone know how I can redirect the user to another link using the the get_context_data? The reverse lazy below is not working def get_context_data(self, **kwargs): context = super(Name, self).get_context_data(**kwargs) if self.request.user.is_student: if self.request.user != User.objects.get(id=self.kwargs['pk']): return reverse_lazy('link_name', kwargs={'pk': self.kwargs['pk']}) else: pass -
How can I reload gunicorn server using ansible?
I have a gunicorn server which run my Django website on localhost:8000. Currently I use lsof to check for pid and shutdown it using kill -9 command. Then I start gunicorn server again. - name: Find all process using port 8000 ansible.builtin.shell: "lsof -t -i:8000" register: processes_on_port - name: Stop all processes running on port 8000 ansible.builtin.shell: "kill -9 {{ item }}" with_items: "{{ processes_on_port.stdout_lines }}" ignore_errors: yes - name: Start gunicorn server community.general.gunicorn: app: "django_my_website.wsgi" chdir: /opt/my_website/django_my_website venv: /opt/my_website_venv I want to reload it without shutting down using Ansible playbook. Is there any way I can do it ?