Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Incorporating a blog into a django project
So, I have built an ecommerce app, so a primary use case is to sell products, but I also have a blog page, my question is to what is the best way to tackle this? Is it to use a WYSIWYG like CKEditor which I am currently using or are there better ways. The blogs will be simple with normal photo uploads. -
Django 3.2.3 trying to access admin url getting 403 CSRF verification failed
Settings.py MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CSRF_COOKIE_SECURE = False # Hosted with Apache 2 with no SSL. I'm trying to access my admin section. -
twilio: KeyError: 'TWILIO_ACCOUNT_SID'
client = Client(os.environ['TWILIO_ACCOUNT_SID'], os.environ['TWILIO_AUTH_TOKEN']) ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^ File "", line 679, in getitem KeyError: 'TWILIO_ACCOUNT_SID' alwise shows the error import os import sys from twilio.rest import Client from twilio.base.exceptions import TwilioRestException client = Client(os.environ['TWILIO_ACCOUNT_SID'], os.environ['TWILIO_AUTH_TOKEN']) verify = client.verify.services(os.environ['TWILIO_VERIFY_SERVICE_SID']) def send(phone): verify.verifications.create(to=phone, channel='sms') def check(phone, code): try: result = verify.verification_checks.create(to=phone, code=code) except TwilioRestException: print('no') return False return result.status == 'approved' -
Deploy multiple services in docker-compose.yml using hub, on own server (django)
I've a Django project, and i'm using docker with a docker-compose file + DockerFile and .env folder with user/pass for access. Locally, it's working fine. I wonder if I can push all the services (web, postgres and pgadmin) in the same times. After, on my own server, I would pull them all. For now, I push 2 services (web + postgres) on the docker's hub, and pull them. But when I run the postgres/postgis image with "-e" parameter. But I don't like this solution because the docker-compose file don't "help me" to deploy. And, how can I use the ".env/" folder (see docker-compose.yml) instead of using "-e" parameter ? #./dj/docker-compose.yml version: '3.7' services: web: env_file: - ./env/django.env build: context: ./my_project dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 container_name: web_container_my_project image: my_company/my_project_web_api_my_project volumes: - ./my_project:/opt/my_project ports: # HOST:CONTAINER - "8050:8000" depends_on: - db restart: always db: environment: - TZ=Europe/Paris env_file: - ./env/postgresql.env image: postgis/postgis container_name: postgres_container_my_project hostname: db volumes: - /var/lib/postgresql/data-my_project:/var/lib/postgresql/data ports: # HOST:CONTAINER - "5433:5432" restart: always pgadmin: env_file: - ./env/pgadmin.env image: dpage/pgadmin4 container_name: pgadmin_container_my_project ports: # HOST:CONTAINER - "8059:80" volumes: - /var/lib/pgadmin/data:/var/lib/pgadmin/data links: - "db:pgsql-server" restart: always logging: driver: none volumes: pgadmin_data: postgres_data: driver: local Thanks a lot F. -
React TypeError: Cannot read properties of undefined (reading 'source')
I am getting this error from my frontend when i tried to register a new user, the error message from my useEffect hooks each time i click the register button Cannot read properties of undefined (reading 'source') Here is the code snippet function Register() { const navigate = useNavigate(); const [sendRequest, setSendRequest] = useState(false); const [usernameValue, setUsernameValue] = useState(''); const [emailValue, setEmailValue] = useState(''); const [passwordValue, setPasswordValue] = useState(''); const [password2Value, setPassword2Value] = useState(''); function FormSubmit(e) { e.preventDefault(); console.log('The form has been submitted'); setSendRequest(!sendRequest) } useEffect(() => { if (sendRequest) { const source = Axios.CancelToken.source(); async function SignUp() { try { const response = await Axios.post( "http://localhost:8000/apiv1-auth-djoser/users/", { username: usernameValue, email: emailValue, password: passwordValue, re_password: password2Value, }, { cancelToken: source.token } ); console.log(response); } catch (error) { console.log(error.response) } } SignUp(); return () => { source.cancel(); }; } }, [sendRequest]); return ( <div style={{ width: "50%", marginLeft: "auto", marginRight: "auto", marginTop: "3rem", border: "5px solid black", padding: "3rem", }} > CREATE AN ACCOUNT <Grid item container style={{ marginTop: "1rem" }}> <TextField id="username" label="Username" variant="outlined" fullWidth value={usernameValue} onChange={(e) => setUsernameValue(e.target.value)} /> </Grid> <Grid item container style={{ marginTop: "1rem" }}> <TextField id="email" label="Email" variant="outlined" fullWidth value={emailValue} onChange={(e) => setEmailValue(e.target.value)} /> </Grid> <Grid … -
Cannot redirect logged in users to home page in django
When I log in I cannot get the site to redirect me to the home page. Instead, it simply logs me out again. urls.py urlpatterns = [ path("", views.home, name='home'), path("accounts/login/", views.login, name="login"), path("accounts/register/", views.register, name="register"), path("accounts/", include("django.contrib.auth.urls"), name="accounts"), path("search/", views.search), ] views.py def home(request): return render(request, template_name="home.html", context={"session":request.session.items}) def login(request): if (request.method == "POST"): form= UserLoginForm(request.POST) user = authenticate(username=request.POST["username"], password=request.POST["password"]) if (user.is_authenticated): user.save() return HttpResponseRedirect(reverse("home", kwargs={"user":user})) else: return render(request, "registration/register.html", {}) else: return render(request, "registration/login.html", {}) Then I handled logging in and registering by inheriting the default classes used for that. So this is what it looks like: forms.py class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) username = forms.CharField(max_length=32, help_text='username') class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user class UserLoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(UserLoginForm, self).__init__(*args, **kwargs) username = UsernameField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': '', 'id': 'hello'})) password = forms.CharField(widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': '', 'id': 'hi', } )) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user Lastly the error is: django.urls.exceptions.NoReverseMatch: Reverse for 'home' with … -
Danjgo Model update_or_create with field pre-processing
I am new to Danjgo and it maybe a simple thing, but random searching does not seem to have helped. I am using Django Ninja API example, but I think this is not about Ninja. In a simple model e.g. models.py class Person (models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) schemas.py class PersonIn(ModelSchema): class Config: model = Person model_fields = ["first_name", "last_name"] I want to have simple create/read api e.g. api.py def create_person(request, payload: PersonIn): data = payload.dict() try: person, created = Person.objects.update_or_create(**data) except Exception: return { "mesg": "Some error happened"} What I wanted was to ensure that First Name and Last names are capitalized, before storing in DB. I found that one method is to override Model method .save class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def save(self, *args, **kwargs): self.first_name = self.first_name.capitalize() self.last_name = self.last_name.capitalize() super().save(self, *args, **args) But, in this case update_or_create always creates a new object as it first checks for lower case fields and never finds it. I also found that one can overwrite .clean method class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def clean(self): self.first_name = self.first_name.capitalize() self.last_name = self.last_name.capitalize() In this caseI understand I need to call .clean method manually. But … -
Handling a JSON API with Django and putting the data in a model
I have a basic JSON API with some data, I need to dynamically get this data in python and put it in a model, more basically, Let's say the API is for cars, each car has a name and model, how to get the data from the JSON API for cars and put in a model called "Car" in models.py? I searched but I couldn't find a way to do that. -
how to post images from client side to Next.js API endpoint and then to Django REST Framework API
I attempted to create a feature that allows users to upload product images to an ecommerce website. My plan initially was to receive the form submission from the client side in Next.js, and then pass it to the built-in Next.js API endpoint. I wanted to add an authorization token to the header and post it to the Django REST framework API, where I save the image and connect it to the user model using a foreign key. Although posting the image directly from the client side to the Django server worked well, I needed to add an authorization token to the header to retrieve the user in the backend. As I used the HTTP-only method, so I had to post it to the Next.js API endpoint. The problem is I keep running in to is when I post it to the api end point I couldn’t get the image directly to repost it to a djano api end point. Any help would be appreciated. Nextjs client side code. import React,{useState} from 'react' import { useSelector} from 'react-redux'; import { Oval } from 'react-loader-spinner'; function ProductUpload() { const loading = useSelector(state => state.auth.loading) const [formData, setFormData] = useState({ name: '', alt: … -
Django not getting static files in Docker
im not getting any static files in my django app when running docker with nginx. Can someone please look at my config and point out where the issue is? Let's start with Dockerfile for the app from python:3.11-slim-buster ENV PYTHONUNBUFFERED=1 ENV PYTHONWRITEBYTECODE 1 WORKDIR /usr/src/app COPY requirements.txt requirements.txt RUN pip install --no-cache-dir -r requirements.txt COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] COPY . . In entrypoint.sh we can find python manage.py collectstatic --no-input gunicorn core.wsgi:application --bind 0.0.0.0:8000 --reload docker-compose for the app version: "3.11" services: app_django: build: . volumes: - .:/usr/src/app/ - staticfiles:/usr/src/app/staticfiles ports: - 8000:8000 env_file: - .env image: app_django:django container_name: meant_container nginx: build: context: ./nginx/ ports: - 80:80 volumes: - ./nginx/conf.d/:/etc/nginx/conf.d/ - staticfiles:/home/app/staticfiles container_name: nginx_container volumes: staticfiles: here is docerfile for nginx FROM nginx:1.24-alpine RUN mkdir -p /home/app/staticfiles and Nginx cofig upstream dserver { server app_django:8000; } server { listen 80; location / { proxy_pass http://dserver; } location /static/ { alias home/app/staticfiles/; } } here is folder location django settings STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / "staticfiles" -
How to add extra columns for a model if in particular category in Django + Postgres
I need to add extra columns if product is in a particular category. I thought of using JSON or allowing null columns, but is there any better way of handling this situation. I'm using Postgresql database. Here are my model structure. class Product(Base): def __str__(self): return self.name name = models.CharField(max_length=255, unique=True, validators=[validate_alphanumeric]) is_safari = models.BooleanField(default=True) Product table has mapped to agents like this class Agent(Base): def __str__(self): return self.agent_user.username agent_user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.RESTRICT, ) country = CountryField() city = models.CharField(max_length=255) AgentProduct model class AgentProduct(Base): agent = models.ForeignKey( Agent, on_delete=models.RESTRICT, ) product = models.ForeignKey( Product, on_delete=models.RESTRICT, ) a_rate = models.IntegerField() c_rate = models.IntegerField() I would like to add some extra information if is_safari is true to the AgentProduct model like per_v_charge = models.IntegerField() extra_p_charge = models.IntegerField() # something like this -
'TemporaryUploadedFile' object has no attribute 'get'
I'm getting this error every time I'm trying to upload video file, and I think the problem is come from the moviepy library that I'm using to cut every video that are higher than 10 minute. the error: AttributeError at /CreateVideo 'TemporaryUploadedFile' object has no attribute 'get' views: from moviepy.video.io.VideoFileClip import VideoFileClip from django.core.exceptions import ValidationError def create_video(request): if request.method == 'POST': title = request.POST['title'] video = request.FILES['video'] banner = request.FILES['banner'] video_file = video video_clip = VideoFileClip(video_file.temporary_file_path()) duration = video_clip.duration video_clip.close() if duration > 600: # 10 minute in seconds raise ValidationError('the video cannot be longer than 10 minute') return video_file new_video = Video.objects.create( user=request.user, title=title, video=video, banner=banner ) new_video.save() return redirect('Video') return render(request, 'video/create_video.html') models: class Video(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=70) video = models.FileField(upload_to='videos') created_on = models.DateTimeField(auto_now_add=True) banner = models.ImageField(upload_to='banner') slug = models.SlugField(max_length=100, unique=True) -
How to organize Django REST Framework urls
so I am working on some dummy e-commerce application in Django (DRF) and I am a bit confused how to write good REST API's. Models class Category(models.Model): name = models.Char... class Product(models.Model): category = models.ForeignKey(...) name = models.Char... Views class ProductListView(APIView): def get(self, request, category_slug=None): products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) serializer = ProductSerializer(products, many=True) return Response(serializer.data, status=status.HTTP_200_OK) First Question So my question is if I should put logic for filtering with capture value (categori_slug) in this view or would it be more clear if I create two endpoints? Second Question In DRF is bottom code good practice to send multiple data trough result/endpoint? return Response({data: serializer.data, other_data: serializer_other.data}, status=st...) So as I am learning all the time only one serializer.data is passed trough one Response API but what if I want that client can also access some other data. Is better to split it in multiple views and than let client make multiple requests? PS: This is my first Stackoverflow question so I would appreciate some feedback on this as well. -
How to use 'auth_user' table of remote database in django?
I want to access 'auth_user' table from another Django project and use it in my current Django project. I am using database routers:- DATABASE_ROUTERS = ['to.your.router.CurrentRouter'] DATABASES = { 'default': eval(os.environ.get('DATABASE_REMOTE', str(DEFAULT_DATABASE))), 'database_current': eval(os.environ.get('DATABASE_CURRENT', str(DEFAULT_DATABASE))) } class CurrentRouter: route_app_labels = { 'admin', 'contenttypes', 'sessions', 'tracking', 'data_collect' } def __str__(self): super().__str__() def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'database_current' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'database_current' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'database_current' return None How can i use 'auth_user' table from DATABASE_REMOTE for logging into django admin panel and delete object from DATABASE_CURRENT. And how to set permission deleting objects in current database using User of remote database? For logging into admin panel using remote database user I have used custom authentication. https://docs.djangoproject.com/en/4.2/topics/auth/customizing/ class CustomAuthenticationBackend(BaseBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = User.objects.get(email=username) except ObjectDoesNotExist: return None if user.check_password(password): return user else: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except ObjectDoesNotExist: return None But when deleting an object from DATABASE_CURRENT using the DATABASE_REMOTE 'User' … -
Django - Filter queryset by latest ForeignKey
I have following models: class Version(models.Model): version_date = models.DateField() # Other fields class Document(models.Model): version = models.ForeignKey(Version, related_name="documents") title = models.CharField(max_length=128) And I have following objects based on the models: # Version objects version_1 = Version.objects.create(version_date="2020-02-2") version_2 = Version.objects.create(version_date="2021-02-2") version_3 = Version.objects.create(version_date="2022-02-2") # Documents doc_1 = Document.objects.create(version=version_1, title="the title of doc") doc_2 = Document.objects.create(version=version_2, title="the title of doc") doc_3 = Document.objects.create(version=version_3, title="the title of doc") My problem is to filter documents only the documents that are in the latest version. If I use Document.objects.filter(title="the title of doc"), I want to only get doc_3 that is under the latest version. Is there any ways to do that by django ORM? Thanks. -
Llama_index index.query returns proper response when .py file is run via CLI but return "None" when used with (Django)api call
I am trying to het a response from openai. This works fine when I run the file form the CLI.(see code below) Because it prints the response to the command line. from django.views.decorators.csrf import csrf_exempt from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader import os os.environ["OPENAI_API_KEY"] = "<MY_OPENAI_API_KEY>" @csrf_exempt def ask_ai( prompt ): print( prompt ) documents = SimpleDirectoryReader("data").load_data() index = GPTSimpleVectorIndex.from_documents( documents ) response = index.query( prompt ) print( response ) ask_ai("<my prompt>") However, when I use Django to call the mostly the same but slightly modified file(see below) the response is always printed as "None" and returned as null. from django.views.decorators.csrf import csrf_exempt from llama_index import GPTSimpleVectorIndex, SimpleDirectoryReader import os os.environ["OPENAI_API_KEY"] = "<MY_OPENAI_API_KEY>" @csrf_exempt def ask_ai( prompt ): print( prompt ) documents = SimpleDirectoryReader("data").load_data() index = GPTSimpleVectorIndex.from_documents( documents ) response = index.query( prompt ) print( response ) return response.response What can I do to make it print/return the response for the API call in the same way that it does for the CLI? I have tried: async/await. This returns an error. TypeError: Object of type coroutine is not JSON serializable adding a second function with async await applied that returns the query response to ask_ai which then returns it to the … -
Django and Telegram Bot - Save functions fires but doesn't saves changes
I've got one function which can be called from WEB and inside telegram bot (with await) #views.py from .models import SomeModel def save_function(id): record = SomeModel.objects.get(pk=id) bot = telebot.TeleBot("123:abcdef") message = bot.send_message(1234,'message') print(message.message_id) ## runs ok record.message_id = message.message_id record.save() ## no changes in async call from bot from asgiref.sync import sync_to_async @sync_to_async def save_function_async(id,context): from .views import save_function save_function(id=id) ### message_handler_function async def entered_text(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int: await save_function_async(123,context) If i run save_function from any Web-Views - it runs hot it should be But, run save_function from telegram bot - there is any error, the message from bot sends sucessfully, but model's data doesn't changes. How it can be fixed? -
Why can't I output the full values using get_foo_display?
There is a Django form. When I send a GET-request, I output a new empty form, when I click "Submit", I display on the page what the user entered in the questionnaire. The problem is that I want some data to be output not as an internal representation, but as an full one (idk how it called correctly). I'm a beginner in Django and may not understand many nuances. I tried to add data to the dictionary individually, but it didn't lead to anything. pool.html: <p><b>Ваше имя:</b> {{ form_data.name }}</p> <p><b>Ваш пол:</b> {{ form_data.get_sex_display }}</p> forms.py: class FeedbackForm(forms.Form): SEX_OPTIONS = ( ('m', 'Мужской'), ('f', 'Женский'), ('none', 'Паркетный') ... sex = forms.ChoiceField( widget=forms.RadioSelect, choices=SEX_OPTIONS, label='Ваш пол:' ) views.py: def pool(request): assert isinstance(request, HttpRequest) context['title'] = 'Обратная связь' if request.method == 'GET': form = FeedbackForm() else: form = FeedbackForm(request.POST) if form.is_valid(): form_data = request.POST.dict() context['form_data'] = form_data context['form'] = form return render(request, 'app/pool.html', context=context) -
Django changes the MEDIA URL if I pass request from views to serializer
I am working on a Social Media project. I successfully implemented image upload and now working on Like model which allows users to like a post. At present state, if a user clicks on Like button, it turns red. All I want is if the page reloads or the same user logins again, the specific post's like button must remain red. In order to achieve so, I am trying to add extra field in serializer(below): liked_by_current_user with which I can filter out as to when the like color must be red. (The REST APIs are working correctly) models.py: class Comment(models.Model): text = models.TextField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(default=timezone.now) post = models.ForeignKey(Post, on_delete=models.CASCADE) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=100, blank=True) profile_image = models.ImageField(upload_to='user_image', null=True, blank=True) class Like(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) selected views.py def feed(request): context = { 'MEDIA_URL': settings.MEDIA_URL, # pass MEDIA_URL to the template } return render(request, 'post_list_temp.html', context) class PostListView(APIView): def get(self, request, *args, **kwargs): posts = Post.objects.filter(deleted=False).order_by('-created_on') context = { 'post_list' : posts, } paginator = defPagination() result = paginator.paginate_queryset(posts, request, view=self) serializer = feedSerializer(result, context={"request":request}, many=True) return paginator.get_paginated_response(serializer.data) def post(self, request, *args, **kwargs): if request.user.is_authenticated: print(request) serializer … -
TimescaleDB: Image does not recognize created hypertables
I am running a django app with timescaledb as local DB image. It was working until recently (maybe 2 days ago). Now I get the following error: ERROR: function create_hypertable(unknown, unknown, chunk_time_interval => interval) does not exist at character 8 HINT: No function matches the given name and argument types. You might need to add explicit type casts. Answers to other questions (e.g: TimescaleDB: Is it possible to call 'create_hypertable' from Python?) regarding this topic suggest to install the timescaledb extension. But I am running the timescaledb-ha image which comes with the extension included (https://hub.docker.com/r/timescaledev/timescaledb-ha). I also tried to create the hypertables with if_not_exists => TRUE as suggested here: https://github.com/timescale/timescaledb/issues/189. I assume there is a bug in the image since it was updated 2 days ago and before it was working. Parts of my dockerfile: postgres: container_name: postgres_postgis image: timescale/timescaledb-ha:pg14 volumes: - local_postgres_data:/var/lib/postgresql/data - local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres Can somebody help? Would be highly appreciated. Thanks in advance -
Converting multiple left join SQL into a django ORM query
I am having trouble creating a corresponding django ORM query for the following SQL Join: select su.user_id from slack_slackuser as su left join auth_user as au on su.user_id = au.id left join core_profile as cp on au.id = cp.user_id where cp.org_id = 8; Here slack_slackuser maps to SlackUser django model, auth_user maps to the django's AUTH_USER_MODEL and core_profile maps to Profile model. This is what I was trying to do, but this fails.: SlackUser.objects.filter(user_id__core_profile__org_id=org.id).values_list('user_id', flat=True) -
Taking three records from the products in the table according to their categories
I have two tables named categories and products. How can I get three records from each category on the homepage? Thanks in advance class Category(models.Model): name = ... class Produc(models.Model): name = ... category = models.ForeignKey(Category, ... class Home_Cls(TemplateView): ... def homepro(self): cats = Category.objects.all() for cat in cats : que= Products.objects.filter( category_id=cat[..] ).order_by('?')[:3] return que I tried a little. :( Waiting for your help. -
Nginx doesn't see or use subdomain config
Problem: nginx doesn't apply configuration for subdomain if there are domain and subdomain config at the same time. Disclaimer: I'm new to nginx and server deployment. Question: What I do wrong with nginx configuration? Additional info: Nginx 1.18.0 Ubuntu 20.04 Details: I have main domain (it's my portfolio) (let's say example.com) and subdomain (todo-tracker.example.com). Both are django projects started with gunicorn (main on 127.0.0.1:8000, todo-tracker on 127.0.0.1:8001). I have two sites-available config files: default - for main domain server { server_name example.com; location / { proxy_pass http://127.0.0.1:8000/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /static { autoindex on; alias /home/portfolio/portfolio/staticfiles; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; listen [::]:80 ipv6only=on; server_name example.com; return 404; # managed by Certbot } todo-tracker - for subdomain server { server_name todo-tracker.example.com; location / { proxy_pass http://127.0.0.1:8001/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header … -
Database error "Access denied for user 'admin'@'localhost' (using password: YES)")
While working on my first Django project, I am trying to connect my application to MySQL database and it keeps giving me this error. I have installed mysqlclient. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'minesupdb', 'USER': 'admin', 'PASSWORD': 'my_password', 'HOST': 'localhost', -
DJango allauth Microsoft Graph
I have a DJango program called 'p_verison1'. Then I have a second application to manage users called "users". There I have implemented login and it works fine. I have added that you can login with Microsoft using "allauth". The problem is that after pressing the "sign in with microsoft" button, instead of taking you directly to the page to choose the microsoft account, it first takes you to a second page where you have to click on the continue button. I want to remove that second page, I want it to always take as the user clicks the button and continue and directly take you to the Microsoft page. I've been trying different ways but I can't remove the second page. My "login.html": <div class="form-group"> <div class="socialaccount_providers" style="margin=0px"> {% include "socialaccount/snippets/provider_list.html" with providers="microsoft" process="login" %} </div> </div> My "provider_list.html" {% load socialaccount %} {% load static %} {% get_providers as socialaccount_providers %} {% for provider in socialaccount_providers %} {% if provider.id == "openid" %} {% for brand in provider.get_brands %} <div> <a title="{{brand.name}}" class="socialaccount_provider {{provider.id}} {{brand.id}}" href="{% provider_login_url provider.id openid=brand.openid_url process=process %}" >{{brand.name}}</a> </div> {% endfor %} {% endif %} <div class="my-2"> <a title="{{provider.name}}" class="socialaccount_provider {{provider.id}}" href="{% provider_login_url provider.id process=process …