Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
403 error everytime I login to my site, but csrftoken is in my form. DJANGO
I am experiencing 403 error when I uploaded my site on pythonanywhere.com, but it works fine in localhost. It keeps on saying 403 forbidden when I try to login an account, even I input a wrong password. I tried to look at the request cookies in my browser, it does not detect the csrftoken, but when I check the checkbox that shows filtered out request cookies, I can see the csrftoken and its value and other things. I have {% csrf_token %} in my login form and I am using the default login view of django. here's my settings.py: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["jeremiramos.pythonanywhere.com"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #my apps 'accounts.apps.AccountsConfig', #installed apps 'corsheaders', 'crispy_forms', 'rest_framework', 'main', 'cms', 'ckeditor', 'students', ] AUTH_USER_MODEL = 'accounts.User' AUTHENTICATION_BACKENDS = ( # 'django.contrib.auth.backends.RemoteUserBackend', 'django.contrib.auth.backends.ModelBackend', ) MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', … -
Extend Filter functionality to use only if variable have value
I am using the django framework for make an blog app. my django version is Django version 4.0.4 i am supposed to do filter the data as per Title And category that blog does have my code is as follow searchTitle = request.GET.get('searchTitle') searchCat = request.GET.get('searchCat', '') if searchTitle or searchCat: blogs = Blog.objects.filter(blog_title__icontains=searchTitle).order_by('-blog_id') if searchCat: blogs = Blog.objects.filter(blog_title__icontains=searchTitle,blog_category=searchCat).order_by('-blog_id') else: blogs = Blog.objects.all().order_by('-blog_id') This is working perfect but this doesn't make sense since it does not follow DRY principle Here i've written Blog.object.filter code twice for search. so i want to minimize that and that problem in one line if possible. so could you guys guide over me -
Django + React , Google Login Button doesn't shown
I use frontend as React and backend as Django. I want to add Google social login, but button doesn't shown. I copy and paste this link, https://developers.google.com/identity/gsi/web/guides/display-button Here is my code. react - index.html <script src="https://accounts.google.com/gsi/client" async defer></script> <div id="g_id_onload" data-client_id="1234567890-myclientid.apps.googleusercontent.com" data-login_uri="http://127.0.0.1:8000/accounts/google/login/" data-auto_prompt="false"> </div> <div class="g_id_signin" data-type="standard" data-size="large" data-theme="outline" data-text="sign_in_with" data-shape="rectangular" data-logo_alignment="left"> </div> django - urls.py ... path('accounts/', include('allauth.urls'),), ... error occured. '/accounts' page works very well. [GSI_LOGGER]: Error parsing configuration from HTML: Unsecured login_uri provided. -
No idea why I am getting 'An existing connection was forcibly closed by the remote host' error message
I have been building a practice website for over a year and have never encountered this problem. I have not knowingly made any adjustments to my firewalls and internet settings. Today I tried to run a few different versions of my website (from between a few days and few months old) and I encountered the same issue on all of them. So I was able to rule out a rogue piece of code in a recent version causing the problem. I restarted my PC, cleared my cache on Google Chrome and also tested the issue on Firefox. Does anyone have any suggestions? I am scratching my head to what triggered this problem. -
Unauthorized response to POST request after JWT token refresh in Django
Goal: I am trying to get access to specific user data using JWT. Specifically, I aim to get the user id from the JWT token using request.user.id. Problem: I am able to run the api and refresh the tokens. Once the tokens expire, I am able to refresh them. However, after that happens, I don't seem to be able to access to my API However, once the tokens are refreshed, I get an error when I try to load the data again: "Unauthorized: /api/load/". Is there something that is clearly wrong here? Django view for api/load/ class LoadDataSet(APIView): serializer_class = LoadDataSerializer queryset = UserPantry.objects.all() permission_classes = [IsAuthenticated] authentication_classes = [JWTAuthentication] def post(self, request, format=None): user = request.user.id print(user) return Response(status=status.HTTP_204_NO_CONTENT) The api call in react native: const res = await request({ url:'/api/load/', method: 'POST', data: {'user_id': String(user_id)} }) Django JWT settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ ], 'DATETETIME_INPUT_FORMATS': ['%Y-%m-%d %H:%M'], 'DATIME_FORMAT': '%Y-%m-%d %H:%M', 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=3), 'REFRESH_TOKEN_LIFETIME': timedelta(days=60), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'AUTH_HEADER_TYPES': ('JWT', 'Bearer'), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', … -
Django - Adding HTML Pages
I am having trouble adding a new html page. I added everything to the views.py and urls.py file, and even the base.html but I keep getting an error message (see on last line in terminal screenshot) enter image description hereenter image description hereenter image description here -
Create Django model where the default value is not shown in my form
Im trying to create a Django model with a default value, something like this: class ExampleModel(models.Model): image = models.URLField(max_length=200, default='https://example.com') And a form for this model: classExampleForm(forms.ModelForm): class Meta: model = ExampleModel fields = ('image') The thing is that by doing this when I display the form in an HTML template, the image field comes prepopulated with https://example.com, I want the filed to be empty and if the user doesn't input any value it takes the default one but that this is not shown in the form. -
calling a synchronous function asynchronously in django-graphene mutation
My mutation contains a function which calls an API to send SMS. Since this function's execution may take some time, and its result doesn't have anything to do with what the mutation returns (It does not have to be send back to the client); I prefer to run it asynchronously. So that the mutation gets executed as fast as possible. Here's my code: class MyMutation(graphene.Mutation): class Arguments: phone = graphene.String(required=True) success = graphene.Boolean() @classmethod def mutate(cls, root, info, phone): ... ... myfunction() #The client should not wait for this function's execution. return MyMutation(success=True) I couldn't find a proper way to do this in django-graphene's docs. -
Django docker-compose: how to handle migrations and collect static
I have a django app that I have been trying to "Dockerize" . I am pretty close but I am facing a small issue. Essentially, I am trying to understand how should I handle the fact that everytime I run docker-compose up I should run python manage.py migrate. Any suggestions? Below my dockerfile and my dockercompose. If they are totally wrong, please le me know as well. # pull official base image FROM python:3.10-alpine # set work directory WORKDIR /app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV DEBUG 0 # install psycopg2 RUN apk update \ && apk add --virtual build-essential libffi-dev gcc python3-dev musl-dev \ && apk add postgresql-dev \ && pip install psycopg2 # install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt # copy project COPY . . # add and run as non-root user RUN adduser -D miliu USER miliu # run gunicorn # CMD gunicorn mywebsite.wsgi:application --bind 0.0.0.0:$PORT CMD python ./manage.py collectstatic --noinput version: "3.8" services: web: build: . volumes: - .:/django ports: - 8000:8000 env_file: .env image: miliu container_name: miliu_container command: > sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" depends_on: - db db: image: postgres volumes: … -
how do i save a variable in html file in order to send it to a database through Django?
So I've made a counter on Django using HTML and JS, HTML/JS then used this as a template on django Views.py, now i want to save the counter number to a MySQL database, how would i do this tho? Is it possible with just using a template? Im new to Django so I'm sorry in advanced. Counter -
Django change textfield
Currently am using this textfield for my model #model class NoLoginPsuedoAppointment(models.Model): ... comments = models.TextField(blank=True) #form class NoLoginPsuedoAppointmentForm(forms.ModelForm): comments = forms.Textarea() class Meta: model = NoLoginPsuedoAppointment fields = [ "comments", ] Which comes out looking like this Is there a way to change where the textarea begins so that comments is on top of the textarea or on its top left instead of being on its bottom left? Can this be changed through the django forms? or do I need to change it through css? -
Daphne ModuleNotFoundError: No module named 'app_name'
When I run daphne -b 0.0.0.0 -p 8000 --access-log=daphne.log config.asgi:application I get Daphne ModuleNotFoundError: No module named 'app_name' But when I run python3 manage.py runserver it works normally? When I remove app_1 from INSTALLED_APPS it will show me ModuleNotFoundError: No module named 'app_2' This is my folder structure: project_name │ manage.py │ └───config │ │ __init__.py │ │ asgi.py │ │ celery.py │ │ urls.py │ │ wsgi.py │ │ │ └───settings │ │ │ │ __init__.py │ │ base.py │ │ dev.py │ │ prod.py │ │ └───project_name │ │ __init__.py │ │ │ └───app_1 │ └───app_2 │ └───app_3 │ └───media │ └───static asgi.py: from django.core.asgi import get_asgi_application django_asgi_app = get_asgi_application() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from chat import routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.dev') application = ProtocolTypeRouter({ 'http': django_asgi_app, 'websocket': AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ), }) -
Is there a Pythonic way to type a function parameter to a specific django model object?
Let's say I have a model like this: class Foo(): name = models.CharField() And a function like this: def update_foo_name(foo_object): foo_object.name = "New Name" Is there a way to enforce typing on update_foo_name(), so that only a valid object of Foo can be passed here? Ie something like update_foo_name(foo_object: Foo.objects). Apologies if this has already been asked, and thank you in advance for any responses! -
Replit: Why am I getting PR_END_OF_FILE_ERROR for my Django project?
I run a Django repl within Replit. However, I often cannot access the browser preview of my project because of a "PR_END_OF_FILE_ERROR" in Firefox. I also tried using Brave and Chromium, but no luck with them either: they showed an "ERR_CONNECTION_CLOSED" error. When I reached out to Replit Support, they said, "This looks like a problem that someone in our community can help with." Can any of you help? -
Ignore certain fields on update depending on condition
Description: The goal is to update all Spotlight fields on PUT/PATCH (update/partial update) if its status is YELLOW. If status is RED || GREEN, it should update only its status and ignore any other fields. The workaround presented here is kind of smelly and it produces misleading responses when using PUT. Is there any Django way to achieve this better than the presented workaround? Workaround: if instance.state == instance.STATE_YELLOW: custom_data = request.data else: custom_data = {'state': request.data['state']} Full code: from stoplight.filters import StoplightFilter from stoplight.models import Stoplight from stoplight.permissions import ( IsSuperuserOrReadOnly ) from stoplight.serializers import StoplightSerializer from rest_framework import status from rest_framework.mixins import CreateModelMixin, ListModelMixin, RetrieveModelMixin from rest_framework.response import Response from rest_framework.viewsets import GenericViewSet class StoplightViewSet(GenericViewSet, CreateModelMixin, ListModelMixin, RetrieveModelMixin): """ API endpoint for Stoplights """ queryset = Stoplight.objects.all() serializer_class = StoplightSerializer filter_class = StoplightFilter search_fields = ('name',) permission_classes = (IsSuperuserOrReadOnly,) def update(self, request, *args, **kwargs): """ Updates Stoplight state """ partial = kwargs.pop('partial', False) instance = self.get_object() if instance.state == instance.STATE_YELLOW: custom_data = request.data else: custom_data = {'state': request.data['state']} serializer = self.get_serializer(instance, data=custom_data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) if getattr(instance, '_prefetched_objects_cache', None): # If 'prefetch_related' has been applied to a queryset, we need to # forcibly invalidate the prefetch cache on … -
"column does not exist" and "cursor does not exist" for postgres migration (where column clearly exists)
I'm running into some migration problems. I've tried deleting my last migration file, going into psql and dropping all the new tables and deleting the specific migration row in django_migrations. But I'm still getting the following errors for the following model: # my model class Excerpt(models.Model): id = models.UUIDField( default=generate_ulid_as_uuid, primary_key=True, editable=False ) body = models.JSONField(default=None) slug = ArrayField( models.SlugField(max_length=50), unique=True, null=True, blank=True ) Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column app_excerpt.slug does not exist LINE 1: ..."app_excerpt"."chapter_id", "app_excerpt"."body", "app_excer... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: column app_excerpt.slug does not exist LINE 1: ..."app_excerpt"."chapter_id", "app_excerpt"."body", "app_excer... ^ During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/code/manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line … -
Exception inside application: 'user' user=self.scope['user'] KeyError: 'user'
I'm trying to set up a custom middleware for my django channels since AuthMiddleWare returns anonymousUser while trying to use self.scope['user] in consumers.py and i'm using token based authentification,but after setting up the custom middleware django keeps throwing this exception: Exception inside application: 'user' Traceback (most recent call last): File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\security\websocket.py", line 37, in __call__ return await self.application(scope, receive, send) File "C:\Users\user\Easylance\chat\token_auth.py", line 29, in __call__ return await super().__call__(scope, receive, send) File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\routing.py", line 150, in __call__ return await application( File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\consumer.py", line 94, in app return await consumer(scope, receive, send) File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\consumer.py", line 58, in __call__ await await_many_dispatch( File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\utils.py", line 51, in await_many_dispatch await dispatch(result) File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\consumer.py", line 73, in dispatch await handler(message) File "C:\Users\user\Easylance\chat\consumers.py", line 13, in websocket_connect user=self.scope['user'] KeyError: 'user' definitely the error means that there's no key for the dict scope named 'user',but in my token_auth.py file where the custom middle ware is situated,i actually assigned a key 'user' the custom middle ware code is below: class TokenAuthMiddleware(BaseMiddleware): def __init__(self, inner): super().__init__(inner) … -
requirement.txt error in virtual environment
I am running pip freeze > requirements.txt instead of making requirements.txt my virtual environment is making only requirements file which is empty. Any advice? -
Making price range filter in django
Hi guys I have built an ecommerce site using Django. I want to filter the price ranges and I have found the perfect javascript and html tempelate for that. Problem is I don't have javascript knowledge to put that to my advantage. Here are the codes. Javascript var slider = document.getElementById('price-slider'); if (slider) { noUiSlider.create(slider, { start: [1, 999], connect: true, tooltips: [true, true], format: { to: function(value) { return value.toFixed(2) + '$'; }, from: function(value) { return value } }, range: { 'min': 1, 'max': 999 } }); } html code <div class="aside"> <h3 class="aside-title">Filter by Price</h3> <div id="price-slider"></div> </div> Views def category_products(request,id,slug): products = Product.objects.filter(category_id=id) minmaxPrice = products.aggregate(Min('price'), Max('price')) context={'products': products, 'minmaxPrice':minmaxPrice,} return render(request,'category_products.html',context) Now it shows ranges from 1 to 999 as fixed in the javascript code, but I want it to be dynamic based on the range "minmaxPrice" in views, like this "minmaxPrice.price__min" and "minmaxPrice.price__max". Thank you in advance!!! -
The genre system in django
I'm making a genre system on django based on the videos. I came across a problem that when I select a certain genre and click on the find button, I am thrown a link of the type '/filter/?genre=2', but the problem is that the found books are not displayed, I know for sure that they are, the problem is specifically in the template.The genres themselves also disappear from the sidebar, but the header tag and some others remain. I can't figure out what the problem is. views.py class GenreView: def get_genres(self): return Genre.objects.all() class AllBookView(View): def get(self, request): allbook = BookModel.objects.all() view_genres = GenreView.get_genres(self) return render(request, 'bookapp/bookmodel_list.html', context={ 'allbook': allbook, 'viewgenre': view_genres, }) models.py class Genre(models.Model): name = models.CharField('Имя', max_length=100) def __str__(self): return self.name class Meta: verbose_name = "Жанр" verbose_name_plural = "Жанры" class BookModel(models.Model): title = models.CharField(max_length=100, verbose_name='Название') creator = models.CharField(max_length=100, verbose_name='creator', null=True) author = models.CharField(max_length=100, verbose_name='автор') contentbook = models.TextField(verbose_name='Содержание') picture = models.ImageField(upload_to='images/', verbose_name='Обложка') price = models.IntegerField(null=True, verbose_name='Цена') price_rent = models.IntegerField(null=True, verbose_name='Аренда') likes = models.ManyToManyField(User, related_name='book_post', verbose_name='лайкнули') genres = models.ManyToManyField(Genre, verbose_name='жанры') html <header></header> <div></div> (Внутренности этих тегов надеюсь не так важны, но они выводятся) <form action="{% url 'filter' %}" method="get"> <div class="left-side my-4"> <h3 class="sear-head editContent">Жанры</h3> <ul class="w3layouts-box-list" style="list-style-type: none; … -
Django API unittest JWT authentication always 403 Forbidden
I am trying to write unit tests for my Django API that has JWT authentication. But every test gets status code 403 - Forbidden. I did try with force_authenticate too, but it doesn't work. When I work with Postman, everything is fine. Here is the code below, and one of the tests. Thanks for the help if there is any. test_view.py: from rest_framework.test import APIClient, APITestCase from django.urls import reverse from users.models import User class TestViews(APITestCase): def setUp(self): self.client = APIClient() self.register_url = reverse('register') self.login_url = reverse('login') self.user_url = reverse('user') self.logout_url = reverse('logout') self.user1 = User.objects.create( email = "petar@stripe.com", first_name = "Petar", last_name = "Petrovic", password = "petar123" ) self.user1 = User.objects.get(email="petar@stripe.com") self.client.force_authenticate(user=self.user1) self.data_login = { "email": "petar@stripe.com", "password": "petar123" } def test_login_POST(self): response = self.client.post(self.login_url, data=self.data_login, format="json") self.assertEquals(response.status_code, 200) # AssertionError: 403 != 200 self.assertTrue("jwt" in response.data) # AssertionError: False is not true models.py: from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) password = models.CharField(max_length=255) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] views.py: from rest_framework.views import APIView from RecipesAPI.constants import HUNTER_API_KEY, CLEARBIT_API_KEY, JWT_KEY import requests from rest_framework.response import Response from … -
Validate parent model foreign key by child class in Django
Let's say I have the following parent models in my Django application: class Location(models.Model): name = models.CharField(max_length=100) class Exit(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name="exits") closed = models.BooleanField() And two pairs of corresponding child models: class Submarine(Location): size = models.FloatField() class Hatch(Exit): diameter = models.FloatField() class House(Location): height = models.FloatField() class Door(Exit): width = models.FloatField() height = models.FloatField() In this setup it is possible for a House to have a Hatch as one of its Exits, as well as for a Submarine to have a Door. Is there a way to explicitly prevent this from happening? Ideally, I would like an exception to be thrown on attempt to set an invalid foreign key. Moving the location field from Exit to Hatch and Door is not an option, because I want to be able to use constructions like the following: open_locations = Location.objects.filter(exits__closed=False) and avoid duplication (i.e. writing separate functions for Houses and Submarines). Maybe the limit_choices_to constraint could be helpful, but I didn't manage to figure out how to apply it here. -
CSRF verification fails after having deployed Django on nginx and waitress
I have used the build-in CSRF module in Django, which worked on localhost. After deploying on nginx and waitress on windows server, it gives me the following error: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: Origin checking failed - https://95.18.243.298 does not match any trusted origins. Have tried these setting in settings.py: CSRF_TRUSTED_ORIGINS = ['95.18.243.298'] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') USE_X_FORWARDED_HOST = True USE_X_FORWARDED_PORT = True CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True Figured it maybe have something to do with having implemented HTTPS. The nginx config looks like this: server { listen 80; server_name DJANGO-WEB; # substitute your machine's IP address or FQDN return 301 https://$host$request_uri; } server { listen 443 ssl; server_name DJANGO-WEB; charset utf-8; ssl_certificate C:/Users/Administrator/Desktop/certifikat.pem; ssl_certificate_key C:/Users/Administrator/Desktop/privateKey.key; # max upload size client_max_body_size 75M; location /static { alias C:/Users/Administrator/itavis-web/static; } location / { proxy_pass http://localhost:8080; # See output from runserver.py proxy_set_header X-Forwarded-Port $server_port; proxy_set_header X-Forwarded-Host $host; } } Hope someone can help. -
Add multiple checkout buttons for multiple events on same page Eventbrite
How to add multiple checkout buttons for multiple events on the same page? <script src="https://www.eventbrite.com/static/widgets/eb_widgets.js"></script> <script type="text/javascript"> var exampleCallback = function () { console.log('Order complete!'); }; var getEventID = function(){ var value = document.getElementById('eventID').value; return value; }; window.EBWidgets.createWidget({ widgetType: 'checkout', eventId: getEventID, modal: true, modalTriggerElementId: 'checkout_btn', onOrderComplete: exampleCallback, }); </script> HTML Here {% for event in data.events %} <form id="form_id"> {% csrf_token%} <div class="center"> <div class="w3-card-4" style="width:100%;"> <header class="w3-container w3-blue" > <h1>{{event.name.text}}</h1> </header> <div class="w3-container" style="background-color: #ddd;"> <p>{{event.description.text}}</p> Event ID: <input type="hidden" id="eventID" name="eventID" value="{{event.id}}"><br> Capcity: {{event.capacity}} <button id="checkout_btn" class="button" type="button">Buy Tickets!</button> </div> </div> </form> {% endfor %} I am showing multiple events in Django and trying to fetch the event id in script code. It works for one event when I provide a hardcoded value. Any help will be appreciated! -
Django | the role of the environment vatiable?
I'm learning Django and I come across something. We use environment variables to keep secrets safe from others or to hide them from other developers who work on the same project. We can export the variables on the server. import os SECRET = os.environ.get("") But then any developer can print this secret and see it. What is the point of using environment variables?