Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the standard oAuth/OIDC flow for creating/logging in a user into client server?
Problem: I want to use information from ID Token (userinfo) to login or create a user for my (app) client server. I am unsure of the standard way to approach this problem as i'm new to oauth and OIDC. My problem lies on the standard flow for creating a session token for my user to access my client server protected routes. I have successfully logged in with my gmail which includes both my google access token and OIDC ID Token. I have also set up a PostgreSQL data base and user models using django. I have also verified or created a user based on my ID Token information. I can use data (email, sub, ect) to verify/create user in client database, but what is the standard approach to creating a session token to acces my client server endpoints? If I create a entirely seperate client server session token, do I use any information from the ID Token? Used this video and auth0 django quickstart tutorial for django integration below. https://www.youtube.com/watch?v=996OiexHze0 https://github.com/auth0-samples/auth0-django-web-app/tree/master -
Django, html page I cannot fix layout problem
I am trying to make layout in my html form page and I have 2 problem. 1- As you can see in screenshot number 1 below, I wanted to add a button next to the type field, but the button appears under the type field. No matter what I did, I couldn't bring side by side. 2-When I connect a modal to the button I added, it disrupts all the page layouts after it. You can find it in screenshot number 2. Here is my html code: {% extends 'base.html' %} {% load widget_tweaks %} {% block content %} <div class="container-fluid px-5 mt-5"> <div class="card card-body"> <div class="container-fluid px-5 mt-5"> <h1>Record Detail Page</h1> </div> <div class="container-fluid px-5 mt-5"> <form class="row g-4" method="post"> {% csrf_token %} <div class="col-md-3"> <label for="inputDirection" class="form-label">Direction</label> {% render_field form.Direction class="form-control"%} </div> <div class="col-md-3"> <label for="inputType" class="form-label">Type</label> {% render_field form.Type placeholder="Type" class="form-control"%} <!-- Zoom Button Start--> <div class="input-group"> <a href="" class="text-decoration-none" data-bs-toggle="modal" data-bs-target="#typeRecordModal"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-up-right-square" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M15 2a1 1 0 0 0-1-1H2a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1zM0 2a2 2 0 0 1 2-2h12a2 2 0 0 … -
sklearn LinearRegression predict returns different results for full dataframe vs iteration over rows
My model class uses StandardScaler and Linear Regression def train(self, data): features = data[self.feature_names].values target = data[self.target_name].values self.scaler = StandardScaler() scaled_features = self.scaler.fit_transform(features) self.regressor = LinearRegression() self.regressor.fit(scaled_features, target) Now I have defined two functions which should either handle a single entry (pandas Series) or multiple entries (pandas DataFrame) def predict_one(self, single_data): """ returns a float """ features = single_data[self.feature_names].values.reshape(1, -1) scaled_features = self.scaler.transform(features) return self.regressor.predict(scaled_features)[0,0] def predict_many(self, multi_data): """ returns a 1D numpy array of floats """ features = multi_data[self.feature_names].values scaled_features = self.scaler.transform(features) return self.regressor.predict(scaled_features).flatten() Then I check whether if I iterate through .iterrows() and save predict_one() results in a list, I get the same results as for predict_many(). And I don't. I have now followed the rabbit hole - it is not the StandardScaler, rather if I just call self.regressor either on full dataset or row by row I get slightly different results: array([[3.10862447e-15], [3.10862447e-15], [3.10862447e-15], [3.10862447e-15] ... vs [array([[3.55271368e-15]]), array([[3.55271368e-15]]), array([[3.55271368e-15]]), array([[3.55271368e-15]]), I just wonder why, even if it is E-15 scale. -
I am trying to deploy a django project on EC2 but can't clone the project repository
I am trying to deploy my django project on an EC2 instance, but when I run git clone, it shows following error: ubuntu@ip-172-31-45-92:~$ git clone git@github.com:Animesh0764/Codex-CP-Analyzer.git Cloning into 'Codex-CP-Analyzer'... git@github.com: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. First I was using normaurl but GitHub doesn't support that authentication so I added SSH key to my GitHub account and currently I am using Termius instead of PuTTy, so I loaded the key to it's local terminal using passphrase. Also ran ssh -T git@github.com and it showed: Hi Animesh0764! You've successfully authenticated, but GitHub does not provide shell access. but it still shows same error. Please help -
I am encountering an issue when running my Django project inside a Docker container using the Python 3.11.1 image
I am encountering an issue when running my Django project inside a Docker container using the Python 3.11.1 image. The error message I am receiving is: Locale folder already exists. Skipping creation. lang en Internal Server Error: / Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ... File "/DjangoProject/json_to_po.py", line 70, in number_format locale.setlocale(locale.LC_ALL, lang) File "/usr/local/lib/python3.11/locale.py", line 626, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting [08/Jan/2024 09:41:17] "GET / HTTP/1.1" 500 60719 My Dockerfile is as follows: FROM python:3.11.1 # Set environment variables ENV PYTHONUNBUFFERED 1 ENV LANG C.UTF-8 ENV LC_ALL C.UTF-8 # Set working directory WORKDIR /DjangoProject COPY . /DjangoProject # Install dependencies RUN apt-get update && apt-get install -y locales RUN echo "en_US.UTF-8 UTF-8" > /etc/locale.gen && locale-gen ENV LANG en_US.UTF-8 ENV LC_ALL en_US.UTF-8 RUN pip install -r requirements.txt RUN python manage.py makemigrations RUN python manage.py migrate I suspect that the issue is related to the locale settings. How can I resolve this "unsupported locale setting" error in my Dockerized Django project using Python 3.11.1? -
Django + Javascript, SCSS proper workflow
I have django project, but the question is about workflow or approach, rather than technical part currently i have a structure like this: src/ ├── apps/ │ ├── authapp/ │ │ ├── templates/ │ │ │ └── authapp/ │ │ │ ├── login.html │ │ │ └── signup.html │ │ ├── views.py │ │ └── *other files* │ └── anotherapp/ │ ├── templates/ │ │ └── anotherapp/ │ │ └── another_page.html │ ├── views.py │ └── *other files* ├── project/ │ ├── settings.py │ └── *other files* ├── static/ │ ├── scss/ │ │ ├── layout/ │ │ │ ├── _header.scss │ │ │ └── _footer.scss │ │ ├── components/ │ │ │ └── _buttons.scss │ │ └── main.scss │ └── js/ │ ├── auth.js │ └── another.js ├── staticfiles/ │ └── *here must be bundled files* └── templates/ └── base.html According to django documentation and to common sense, it's recommended to store static, which is specific for particular app - within the app itself. So, in my base.html i have common header and footer blocks that are shared across (almost) all apps. So, it turns out, in fact i have base.html with base.scss So, i really am being confused … -
How to create an encrypted password with mixer for Django testing?
I'm trying to write a functional test for my Django project where I also want to test the login. For this I want to use mixer to create a user and then log in with the access data. Unfortunately this does not work. Mixer creates a user, but no real password or no encrypted password. As a result, I cannot log in to the test. If I use Django's own function make_password and create the password with it and the user with mixer, then it works. Is there nothing from mixer itself? Code not working # enter correct credentials reg_user = mixer.blend(User) driver.find_element(By.ID, "login-username").clear() driver.find_element(By.ID, "login-username").send_keys(reg_user.username) driver.find_element(By.ID, "login-pwd").clear() driver.find_element(By.ID, "login-pwd").send_keys(reg_user.password) driver.find_element(By.XPATH, "//button[@type='submit']").click() driver.implicitly_wait(5) # assert redirected to home assert driver.current_url == f"{base_url}/" Working Code from django.contrib.auth.hashers import make_password # enter correct credentials password = make_password("test_3") reg_user = mixer.blend(User, password=password) driver.find_element(By.ID, "login-username").clear() driver.find_element(By.ID, "login-username").send_keys(reg_user.username) driver.find_element(By.ID, "login-pwd").clear() driver.find_element(By.ID, "login-pwd").send_keys("test_3") driver.find_element(By.XPATH, "//button[@type='submit']").click() driver.implicitly_wait(5) # assert redirected to home assert driver.current_url == f"{base_url}/" -
How to handle APIView for frontend, API working but unable to call it
I am a new developer so please excuse if you feel its some basic question. I have an APIview for otp verification Now I am unable to put it into forms as I have 4 register pages Please help in how to call it into frontend function. Its just email verification via otp api but don't know how to call it in front My codes are -- API View--- class RegisterAPI(APIView): def post(self, request): try: data = request.data serializer = UserSerializer(data = data) if serializer.is_valid(): serializer.save() send_OTP_via_email(serializer.data["email"]) return Response({ "status" : 200, "message" : "registration Successful check email", "data" : serializer.data, }) return Response({ "status" : 400, "message" : "something went wrong", "data" : serializer.errors }) except Exception as e: print(e) API View-- class VerifyOTP(APIView): def post(self, request): try: data = request.data serializer = VerifyAccountSerializer(data = data) if serializer.is_valid(): email = serializer.data["email"] otp = serializer.data["otp"] user = User.objects.filter(email = email) if not user.exists(): return Response({ "status" : 400, "message" : "something went wrong", "data" : "invalid email" }) if user[0].otp != otp: return Response({ "status" : 400, "message" : "something went wrong", "data" : "Wrong OTP" }) user = user.first() user.is_verified = True user.save() return Response({ "status" : 200, "message" … -
Error message shows invalid output in django
AttributeError at /signup 'function' object has no attribute 'error' AttributeError at /signup 'function' object has no attribute 'error' when i gone localhost 3000 i have error in browser AttributeError at /signup 'function' object has no attribute 'error' any person help to solve this error -
Can the AUROC of sufficiently cross-validated models be below 0.5?
I predict binary outcome using a LogisticRegressor using a Pandas data frame containing 151 features2 of 111 samples. Labels are somewhat imbalanced (42/69, 62.1% majority class). I do this for 4 data_frames (same labels, different data). Results of the code below make sense for all time points but one. For one time point, I have been struck with results I cannot explain: Using Leave-One-Out cross-validation on 111 samples, I get AUROCs substantially below 0.5 (see figure 2) This should no be possible with sufficient validation & a correct implementation. Chance of this is 1.3e-6. I cannot find the culprit. I investigated several probable causes: the code (1, 4), the labels (2), the data (5), chance (3, 6) and the number of features (7). Minimal SKLearn implementation1 This implementation is much like what I used, but I had to simplify the data to stay within the Stackoverflow Character limit, so results can somewhat differ. import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_predict, LeaveOneOut, cross_val_score, RepeatedKFold from sklearn.metrics import roc_auc_score, accuracy_score, RocCurveDisplay from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from matplotlib import pyplot as plt X = pd.DataFrame([[142, 157, 173, 188, 201, 211, 218, 223, 224, 225, … -
Django Caching Token based Authentication
I am using DRF for Token authentication as: while a user login, i am creating a token and for every user request Django is hitting database (for verifying token and get user info). So i want to cache the tokens of currently logged IN users into my Redis cache (present in same device). So that i can avoid a lot of Database hits and my request/response cycle will be faster. I am new to django and got struct to implement this. Please help me with code or should i change from tokenbased to session based authentication?. (My frontend is mobile app built with react-native) I am currently using DRF token based authentication for every view as:- @api_view(['GET','POST']) @permission_classes([IsAuthenticated]) #checks for token and gets the user object def Test_view(request): #some db queries Return Response({'test':'returned'}) created login view as follows:- from rest_framework.authtoken.models import Token from django.contrib.auth import authenticate @api_view(['POST']) @permission_classes([AllowAny]) def UserLogin(request): if request.method=='POST': username = request.data.get('username') password = request.data.get('password') user = authenticate(username=username, password=password) if user is not None: token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key,'name':user.fname+' '+user.lname, 'phone':user.phone,'username':user.username,'email':user.email}) else: return Response({'error': 'Invalid credentials'}) in my settings.py:- REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES' : ( 'rest_framework.authentication.TokenAuthentication', ), } and i am currently using redis cache:- … -
Deploying Django application to Apache running on windows using Jenkins
I have built a Django web application. I was successfully able to deploy that on Apache running on Windows. What I now need is to automate the build and deployment process using Jenkins. That is to deploy my Django application residing in GitHub, to get deployed on Apache running on Windows using Jenkins pipeline. I started that, and so far I am able to build the project successfully using Jenkins. But now I stuck and not able to figure out how to deploy it on Apache running on Windows. Any idea/direction will be highly appreciated. -
How to extract feature names used by the first tree in GradientBoostingRegressor in scikit-learn
I want to print the names of the features from my first estimator of GradientBoostingRegressor, but getting the below error. Scikit_learn version = 1.2.2 model.estimators_[0]._final_estimator.feature_names_in_ output: AttributeError Traceback (most recent call last) Cell In[115], line 1 ----> 1 model.estimators_[0]._final_estimator.feature_names_in_ AttributeError: 'GradientBoostingRegressor' object has no attribute 'feature_names_in_' -
Why this API request is not working properly
I developed an API using Django-REST Framework and am trying to connect it with my frontend. I have an endpoint to get the last four winners, and when I try it works alright async function getLastFourWinners() { const url = 'http://127.0.0.1:8000/bets/get_last_four_winners' const response = await fetch(url) if (!response.ok) { throw new Error('Failed to fetch data') } return response.json() } export default async function Home() { const winners = await getLastFourWinners() return ( <main> {winners.map((winner, index) => ( <LastWinnerItem key={index} username={winner.username} roundName={winner.round} leagueName={winner.league} nPoints={winner.points} nPlayers={winner.n_players} pool={winner.pool} imagePath={winner.profile_image} /> ))} </main> ) } However, when I login from /login and then try to get the current logged user from my home, I get an error saying that I am not authenticated. But when I do the same using Postman it returns the user properly. This is my /login: 'use client' import { useState } from 'react' import { useRouter } from 'next/navigation' import './login.css' export default function Login() { const [username, setUsername] = useState('') const [password, setPassword] = useState('') const router = useRouter() const url = 'http://127.0.0.1:8000/user/login/' const handleLogin = async(e) => { e.preventDefault(); try { const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({username, password}), … -
Error using SimpleImputer and OrdinalEncoder
I'm trying to practice a simple exercise in imputing categorical variables. I'm aware that SimpleImputer works directly on categorical variables, but I'm just doing an exercise for myself. I'm having a very strange error with the final line of this code. import pandas as pd; import numpy as np from sklearn.impute import SimpleImputer from sklearn.preprocessing import OrdinalEncoder df=pd.DataFrame({"cat":["S","M","L","M","S","S",np.nan]}) encoder=OrdinalEncoder(); imputer=SimpleImputer(strategy="most_frequent") df["encoded"]=encoder.fit_transform(df[["cat"]]) df["encoded_imp"]=imputer.fit_transform(df[["encoded"]]) #This final line is not working df["encoded_cat"]=encoder.inverse_transform(df[["encoded_imp"]]) The final line above is not working. The error is (Please note that my Python installation is installed by/within Julia): ValueError Traceback (most recent call last) Cell In[10], line 9 6 df["encoded"]=encoder.fit_transform(df[["cat"]]) 7 df["encoded_imp"]=imputer.fit_transform(df[["encoded"]]) ----> 9 df["encoded_cat"]=encoder.inverse_transform(df[["encoded_imp"]]) File ~\.julia\conda\3\x86_64\lib\site-packages\pandas\core\frame.py:4091, in DataFrame.__setitem__(self, key, value) 4088 self._setitem_array([key], value) 4089 else: 4090 # set column -> 4091 self._set_item(key, value) File ~\.julia\conda\3\x86_64\lib\site-packages\pandas\core\frame.py:4300, in DataFrame._set_item(self, key, value) 4290 def _set_item(self, key, value) -> None: 4291 """ 4292 Add series to DataFrame in specified column. 4293 (...) 4298 ensure homogeneity. 4299 """ -> 4300 value, refs = self._sanitize_column(value) 4302 if ( 4303 key in self.columns 4304 and value.ndim == 1 4305 and not isinstance(value.dtype, ExtensionDtype) 4306 ): 4307 # broadcast across multiple columns if necessary 4308 if not self.columns.is_unique or isinstance(self.columns, MultiIndex): File ~\.julia\conda\3\x86_64\lib\site-packages\pandas\core\frame.py:5040, in DataFrame._sanitize_column(self, value) … -
Storing user-specific data during a Django session
I have a question about database organization in Django. Let this be, for example, some simple browser game based on the parameters of the characters. The user creates his own The Fellowship of the Ring from standard characters that have certain initial parameters. At this point, the characters for each user are identical and can be taken from a single table. But during the session, the parameters of each character will change. Between sessions, character data can be stored in JSON. But during the game, unpacking and repacking JSON into the database every time does not sound like a very good idea(a lot of calculations on the server side and a lot of changes to the template on the client side). What's the best way to store user-specific data during a session? P.S. Of course, I know about Django Sessions, but I’m not sure that this is suitable for the described task -
Weird bug when creating a user in django
I have a weird bug in django where I have 2 different profile models for each user type and one profile model creates two profile models when I create a User. Here's my code for the user model: class User(TimeStampedModel, AbstractUser): class Types(models.TextChoices): """Default user for Side Project.""" COMPANY = "COMPANY", "Company" JOB_SEEKER = "JOB SEEKER", "Job Seeker" base_type = Types.COMPANY # Type of User type = models.CharField(_("Type"), max_length=50, choices=Types.choices, default=base_type) # First and last name do not cover name patterns around the globe name = models.CharField(_("Name of User"), blank=True, max_length=255) first_name = None # type: ignore last_name = None # type: ignore def get_absolute_url(self) -> str: """Get URL for user's detail view. Returns: str: URL for user detail. """ return reverse("users:detail", kwargs={"username": self.username}) def save(self, *args, **kwargs): if not self.id: self.type = self.base_type return super().save(*args, **kwargs) Here's my code for the seeker profile model class SeekerProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='seeker_profile') @receiver(post_save, sender=User) def create_or_update_seeker_profile(sender, instance, created, **kwargs): if instance.type == 'JOB SEEKER': SeekerProfile.objects.get_or_create(user=instance) elif instance.type == 'COMPANY': CompanyProfile.objects.get_or_create(user=instance) @receiver(post_save, sender=User) def save_seeker_profile(sender, instance, **kwargs): if instance.type == 'JOB SEEKER': try: instance.seeker_profile.save() except SeekerProfile.DoesNotExist: # Handle the case where the profile doesn't exist yet SeekerProfile.objects.create(user=instance) else: try: instance.company_profile.save() except … -
Django - Making SMS Auth with custom URL with parameters
I'm working on a company portal website and I'm running into issues that I can't resolve. What do I want to do? Creating a page where company employees can request payroll. First step: When they fill out the form and press the button, the user email, employee ID, etc. I need to make an request an external URL (SAP ERP url) with some parameters like and SAP ERP will send an sms authentication code. After this, the page "must be redirected to another page in order to forward the received SMS code." On my hand, i've got only 2 url like: To request for sms auth code: https://some_url/some_route/..?sap-language=TR&ID=15&USERID=000054 To download payroll: https://some_url/some_route/..?sap-language=TR&ID=13&USERID=000054&MONTH=02&YEAR=2022&EMAIL=NAME@DOMAIN.COM What I tried? Tried to much code but basically url = f'http://127.0.0.1:8000/sendemail/{user_id}/{email}/' # should be replaced sms request url # Django'dan CSRF token'ını al csrf_token = get_token(request) headers = {'X-CSRFToken': csrf_token} response = requests.post(url, headers=headers) print(response.status_code) if response.status_code == 200: return redirect('pageSMSCodeInputPage') return HttpResponse('not OK. error.') -
Hosting Django-Streamlit Integrated Web Apps
I've developed a web application using Django that handles user authentication, including signup and login processes. Upon successful signup, the intention is to redirect the user seamlessly to a separate Streamlit application. Detailed Overview: Application Structure: The web app comprises two distinct components: a Django-based authentication system and a Streamlit-based dashboard or app. Signup and Redirection: After a user successfully signs up through Django, the objective is to automatically redirect them to the Streamlit app without requiring an additional login. Deployment Query: My challenge lies in understanding the deployment process for this integrated structure. I'm seeking guidance on how to host both Django and Streamlit apps in a manner that allows them to interact seamlessly after the signup process. Specific Queries: Hosting Strategy: Which platforms or hosting services would be suitable for deploying these two applications? I'm relatively new to deployment and recently developed a web app using Django for user authentication (signup/login). Upon successful signup, I aimed to redirect users seamlessly to a separate Streamlit app. -
How add extra field in Django default user model? [duplicate]
How to add extra field in default user model and change login via username to email. -
How to stream video chunk by chunk in django?
I was trying to stream video saved on server. I want it to stream chunk by chunk rather than whole video at once. I found following code to stream video. range_re = re.compile(r'bytes\s*=\s*(\d+)\s*-\s*(\d*)',re.I) class RangeFileWrapper: def __init__(self, filelike, blksize=8192, offset=0, length=None): self.filelike = filelike self.filelike.seek(offset,os.SEEK_SET) self.remaining = length self.blksize = blksize def close(self): if hasattr(self.filelike, 'close'): self.filelike.close() def __iter__(self): return self def __next__(self): if self.remaining is None: data = self.filelike.read(self.blksize) #Read data in chunk if data: return data # Return the chunk of data raise StopIteration() # End of file, stop iteration else: if self.remaining<=0: raise StopIteration() #No more data to read, stop the iteration data = self.filelike.read(min(self.remaining,self.blksize)) if not data: raise StopIteration() self.remaining -= len(data) #Updates the remaing length return data def stream_video(request,path): range_header = request.META.get('HTTP_RANGE','').strip() range_match = range_re.match(range_header) size = os.path.getsize(path) #Retrieve the file size content_type, encoding = mimetypes.guess_type(path) content_type = content_type or 'application/octet-stream' # if range_match: first_byte,last_byte = range_match.groups() first_byte = int(first_byte) if first_byte else 0 last_byte = int(last_byte) if last_byte else size-1 if last_byte>=size: last_byte = size-1 length = last_byte-first_byte+1 resp = StreamingHttpResponse( RangeFileWrapper(open(path,'rb'),offset=first_byte,length=length), status=206, #status code for partial content content_type=content_type #set the mime type in the response header ) resp['Content-Length'] = str(length) #Set Content-Length header … -
502 bad gateway with nginx and gunicorn
502 Bad Gateway nginx/1.19.5 reinstall portainer and recreate docker images to solve this isssue, but didnt work. how can i solve this issue? i think something's wrong before collectstatic because if this issue was about collectstatic, webpage have been deployed with static files not applied. gunicorn container logs 0 static files copied to '/home/loldb/staticfiles', 147 unmodified. Operations to perform: Apply all migrations: accountapp, admin, articleapp, auth, commentapp, contenttypes, profileapp, projectapp, sessions, subscribeapp Running migrations: No migrations to apply. 0 static files copied to '/home/loldb/staticfiles', 147 unmodified. Operations to perform: Apply all migrations: accountapp, admin, articleapp, auth, commentapp, contenttypes, profileapp, projectapp, sessions, subscribeapp Running migrations: No migrations to apply. 0 static files copied to '/home/loldb/staticfiles', 147 unmodified. Operations to perform: Apply all migrations: accountapp, admin, articleapp, auth, commentapp, contenttypes, profileapp, projectapp, sessions, subscribeapp Running migrations: No migrations to apply. 0 static files copied to '/home/loldb/staticfiles', 147 unmodified. Operations to perform: Apply all migrations: accountapp, admin, articleapp, auth, commentapp, contenttypes, profileapp, projectapp, sessions, subscribeapp Running migrations: No migrations to apply. nginx logs /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/ /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh 10-listen-on-ipv6-by-default.sh: Getting the checksum of /etc/nginx/conf.d/default.conf 10-listen-on-ipv6-by-default.sh: Enabled listen on … -
how to test if deleted post has been removed from blog
as I'm new in Django I've tried to write a simple program for blog posts to add, update and delete a post. Now I want to test if my deleted post has been removed from my blog list by assertNotContains code and I got an assertion error. I added part of my code related to my question please feel free for more information. thanks in advance. views.py def post_delete(request,pk): post = get_object_or_404(Post,pk=pk) if request.method == 'POST': post.delete() return redirect('blog_list') return render(request,"blog/post_delete.html",{"post":post}) urls.py urlpatterns=[ path("",views.blog_list,name="blog_list"), path("<int:pk>/",views.post_details,name="post_detail"), path("create/",views.create_new_post,name="post_create"), path('<int:pk>/update/', views.post_update ,name='post_update'), path('<int:pk>/delete/', views.post_delete , name='post_delete'), ] models.py class Post(models.Model): STATUS_CHOICES=( ('pub','published'), ('drf','draft'), ) title=models.CharField(max_length=100) text=models.TextField() status=models.CharField(max_length=3,choices=STATUS_CHOICES) created_datetime=models.DateTimeField(auto_now_add=True) modified_datetime=models.DateTimeField(auto_now=True) author=models.ForeignKey(User, on_delete=models.CASCADE) test.py class TestBlogPost(TestCase): @classmethod def setUpTestData(cls): cls.user=User.objects.create(username="user1") cls.post1=Post.objects.create( title="post1", text="this is post1", status=Post.STATUS_CHOICES[1][0], author=cls.user ) def test_delete_post_view_url(self): response = self.client.post(reverse("post_delete",args=[self.post1.id])) self.assertEqual(response.status_code,302) ** self.assertNotContains(response, self.post1.title) ** **error I got: AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200) ** -
Django - How to prevent Custom Field Validator from executing unless the field has changed?
I have a custom validator that checks that the size of the uploaded gallery image is not too big. This validator runs every time the model is saved no matter if the field has changed or not. This usually wouldn't be a big issue. The problem is that I have an admin panel inline, and any time I save the parent model "Profile" the validation inside of all the children "GalleryImages" gets executed. The validation of 50 images takes a long time since it needs to load all images and check for the resolution. How can I configure this validator to only run if the field value has been updated? # models.py @deconstructible class ImageValidator(object): """ Checks that image specs are valid """ def call(self, value): # Some code to check for max size, width and height if too_big: ValidationError('Image is too big') class Profile(Model): user = models.ForeignKey(User) class GalleryImage(Model): profile = models.ForeignKey(Profile) image = models.ImageField(validators=[ImageValidator]) # admin.py class GalleryImageInline(admin.TabularInline): model = GalleryImage @admin.register(Profile) class ProfileAdmin(ModelAdmin): inlines = [GalleryImage] -
Need Help Troubleshooting Django Registration Error
I'm encountering an issue with the registration functionality in my Django project. When I attempt to register a new user, I receive a generic error message, "There was an error, please try again," instead of a successful registration confirmation. Here is my project view.py def login_user(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request, ("You Have Been Logged In!")) return redirect('home') else: messages.success(request, ("There was an error, please try again")) return redirect('login') else: return render(request, 'login.html', {}) def logout_user(request): logout(request) messages.success(request, ("You have been logged out")) return redirect('home') pages navbar.html {% if user.is_authenticated %} <li class="nav-item"><a class="nav-link" href="{% url 'logout' %}">Logout</a></li> {% else %} <li class="nav-item"><a class="nav-link" href="{% url 'login' %}">Login</a></li> {% endif %} pages urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('about/', views.about, name='about'), path('login/', views.login_user, name='login'), path('logout/', views.logout_user, name='logout'), ]