Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No module named 'paramiko' in docker python:3.12.0-alpine even after installing it (logs say it was installed)
paramiko is inside requirements.txt and is installed via RUN pip3 install -r requirements.txt --prefer-binary in my Dockerfile. I also tried installing it with apk py3-paramiko. docker-compose logs tell me that paramiko is installed. Successfully installed Django-4.1.3 PyNaCl-1.5.0 asgiref-3.7.2 bcrypt-4.0.1 beautifulsoup4-4.12.2 certifi-2023.7.22 cffi-1.16.0 charset-normalizer-3.2.0 cryptography-41.0.4 django-auth-ldap-4.5.0 django-bootstrap-v5-1.0.11 djangoajax-3.3 dnspython-2.4.2 gunicorn-21.2.0 idna-3.4 multiping-1.1.2 mysql-connector-python-8.0.29 packaging-23.1 ***paramiko-3.3.1*** protobuf-4.24.3 pyasn1-0.5.0 pyasn1-modules-0.3.0 pycparser-2.21 python-ldap-3.4.3 requests-2.31.0 soupsieve-2.5 sqlparse-0.4.4 urllib3-2.0.5 ... web_1 | File "/usr/local/lib/python3.9/site-packages/django/urls/conf.py", line 38, in include web_1 | urlconf_module = import_module(urlconf_module) web_1 | File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module web_1 | return _bootstrap._gcd_import(name[level:], package, level) web_1 | File "<frozen importlib._bootstrap>", line 1030, in _gcd_import web_1 | File "<frozen importlib._bootstrap>", line 1007, in _find_and_load web_1 | File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked web_1 | File "<frozen importlib._bootstrap>", line 680, in _load_unlocked web_1 | File "<frozen importlib._bootstrap_external>", line 850, in exec_module web_1 | File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed web_1 | File "/usr/src/app/emailflow/urls.py", line 2, in <module> web_1 | from . import views web_1 | File "/usr/src/app/emailflow/views.py", line 3, in <module> web_1 | from . import main web_1 | File "/usr/src/app/emailflow/main.py", line 7, in <module> web_1 | import paramiko web_1 | ModuleNotFoundError: No module named 'paramiko' Any help would be greatly appreciated. -
S3 – Images sometimes showing up with wrong rotations
I run a web service where users are allowed to upload images. I've noticed that sometimes, the uploaded image on S3 shows up rotated – as I came to learn due to exif metadata. Taking a sample of some of the images, and opening them in GIMP, it yields a prompt where I have to decide whether to keep or strip the exif metadata. I noticed, however, that sometimes the "properly" rotated image includes the exif metadata, and, other times, to "properly" rotate the image I need to tell GIMP to ignore the exif data. I thought I could resolve this issue simply by getting rid of the exif metadata, but this will not work under the above observation. So, in summary: how can I guarantee image uploading to S3 with the correct image rotation? P.S.: I am using Python via boto3 to upload images. Thanks! -
whats the best way to format Django Templates in VSCODE?
enter image description here VSCode prettier formatter makes this template format in weird way and i get error in django. I have tried multiple Django Extensions , Prettier ,etc. can anyone share best vscode extensions and settings for django . -
Django auto submit form when user done typing?
I have a form with a text field and i want to receive user input and after user done typing (about 2s). Is there a way to achieve this in django(i only know how to do this in pure js) My model and form: class ProductName(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class ProductNameForm(ModelForm): class Meta: model = ProductName fields = ('name',) My template: <div id="searchbar" class="d-flex flex-row"> <form action="search_result" method=POST class="input-group flex-nowrap bg-light mx-0 mx-lg-auto rounded p-1"> {% csrf_token %} {{ place.place }} {% render_field form.name placeholder="Search product..." class+="form-control"%} {% comment %} <input type="text" id="search" placeholder="Search product" name="search-input" class="form-control rounded"> {% endcomment %} <button type="submit" class="btn btn-secondary"><i class="fa fa-search"></i></button> </form></div> My view: def search(request): if request.method == 'POST': form = ProductNameForm(request.POST) place = ProductPlaceForm(request.POST) if form.is_valid() and place.is_valid(): form.save() place.save() form = ProductNameForm() place = ProductPlaceForm() return HttpResponseRedirect('/search_result') form = ProductNameForm() place = ProductPlaceForm() return render(request, 'search_form.html', {'form':form, 'place':place}) -
Django embedded custom template tag
I'm trying to create a custom template tag for Django. However, it is not generating any output; nor receiving any from the parser. The following is the code for the templatetag itself: class MediaQueryNode(Node): def __init__(self, xsmall, small, medium, large, xlarge, wrap=None): self.xsmall = xsmall self.small = small self.medium = medium self.large = large self.xlarge = xlarge self.wrap = wrap def render(self, context): xsmall = None small = None medium = None large = None xlarge = None context = context.flatten() if self.xsmall: xsmall = self.xsmall.render(context) if self.small: small = self.small.render(context) if self.medium: medium = self.medium.render(context) if self.large: large = self.large.render(context) if self.xlarge: xlarge = self.xlarge.render(context) template = loader.get_template("templatetags/mediaquery.html") context.update({ "mediaquery_xsmall": xsmall, "mediaquery_small": small, "mediaquery_medium": medium, "mediaquery_large": large, "mediaquery_xlarge": xlarge, "wrap": self.wrap.resolve(context) if self.wrap else False, }) return template.render(context) @register.tag("mediaquery") def do_media_query(parser, token): subtags = ["xsmall", "small", "medium", "large", "xlarge"] tag_content = {tag: None for tag in subtags} processed_tags = [] end_tag = 'endmediaquery' # Skip any content between {% mediaquery %} and the first subtag parser.parse(subtags + [end_tag]) while parser.tokens: token = parser.next_token() if token.token_type == TokenType.BLOCK: token_name = token.contents if token_name in processed_tags: raise TemplateSyntaxError(f"Duplicate {token_name} tag") if token_name not in subtags and token_name != end_tag: raise TemplateSyntaxError(f"Unknown … -
Django ModelForm - Bootstrap DateTimePicker
I'm having some problems for processing DjangoModelForm and bootstrap-datepicker to select a specific month First of all I get this error when I access the form The specified value "01/04/2023" does not conform to the required format. The format is "yyyy-MM" where yyyy is year in four or more digits, and MM is 01-12 And after selecting manually the month I get periodo: Enter a valid date. limite_retroactividad: Enter a valid date. I tried to handle it with a javascript script but it's working just for the initial dates but not for saving the data. This is what I have: forms.py class RegistroGestionForm(ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super().__init__(*args, **kwargs) def clean(self): cleaned_data = super().clean() periodo = cleaned_data.get('periodo') limite_retroactividad = cleaned_data.get('limite_retroactividad') if periodo and limite_retroactividad: if periodo < limite_retroactividad: # Add validation error self.add_error('limite_retroactividad', 'El periodo no puede ser menor al límite de retroactividad') return cleaned_data class Meta: model = RegistroGestion fields = ['periodo', 'estado', 'limite_retroactividad'] widgets = { 'limite_retroactividad': DateInput( attrs={ 'type': "month", 'class': "form-select mb-3" } ), 'periodo': DateInput( attrs={ 'type': "month", 'class': "form-select mb-3" } ), } views.py class RegistroGestionUpdateView(UpdateView): model = RegistroGestion form_class = RegistroGestionForm context_object_name = 'registro_gestion' template_name = 'esquema_liquidacion/registro_gestion_form.html' def get_context_data(self, … -
manage.py server running twice internally
why while executing the command manage.py runserver in my project server runs twice.How to fix the issue.but while using --noreload this issue not arises but during api testing server doesnot respond.Shwoing file path not found. command:-py manage.py runserver output:- manage.py is being executed. Hello manage.py is being executed. Hello Watching for file changes with StatReloader Performing system checks... command:-py manage.py runserver output:- manage.py is being executed. Hello manage.py is being executed. Hello Watching for file changes with StatReloader Performing system checks... -
Page not found не работает if settings.DEBUG: [closed]
Начал изучение библиотеки Django и столкнулся с проблемой при создании интернет-магазина, что мою страницу не может найти при использовании следующей команды: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) son/urls from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('koil.urls')) ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in son.urls, Django tried these URL patterns, in this order: При запуске сервера пишет вот это: admin/ ^static/(?P.)$ ^media/(?P.)$ The empty path didn’t match any of these. В чём может быть проблема? P.S. Заранее извиняюсь, если вопрос задан некорректно, при необходимости могу дополнить. К сожалению не имею ни малейшего понятия, как решить данную проблему( -
Django How to use proxy models instead of parent
My code: from django.db import models class Animal(models.Model): type = models.CharField(max_length=100) class Dog(Animal): class Meta: proxy = True class Cat(Animal): class Meta: proxy = True I want to do: animals = Animal.objects.all() but in animals, I should have only Dogs and Cats instances. I need to cast an Animal object to a specific proxy model somehow. How do I do that? in the init method? -
ModuleNotFoundError: No module named 'real_estate' - uwsgi & django
I've been trying to run my django website using uwsgi, but I keep getting this error. I tried so many solutions from stackoverflow and others but It just doesn't get fixed. I'm using this article to do so: https://medium.com/@panzelva/deploying-django-website-to-vps-with-uwsgi-and-nginx-on-ubuntu-18-04-db9b387ad19d Here are some of the solutions I tried: Having the same version of python in venv and global env(both 3.10.12). Moving wsgi.py file from real_estate directory to the main folder. Changing line 12 of wsgi.py file from "os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'real_estate.settings')" to "os.environ.setdefault['DJANGO_SETTINGS_MODULE']= 'real_estate.settings'" or "os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')" I tried running my website like this: "vim uwsgi/sites/real_estate.ini" and then opened my browser tab to this <my_vps_ip_address>:8000, but I get This: "Internal Server Error" and this in my error log: *** Operational MODE: single process *** Traceback (most recent call last): File "/home/allen/project/real_estate/real_estate/wsgi.py", line 17, in <module> application = get_wsgi_application() File "/home/allen/project/env/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/allen/project/env/lib/python3.10/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/allen/project/env/lib/python3.10/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/home/allen/project/env/lib/python3.10/site-packages/django/conf/__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "/home/allen/project/env/lib/python3.10/site-packages/django/conf/__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File … -
Which is a better alternative to the Django make_random_password Deprecated function?
This aswer suggests the use of the make_random_password, but it is deprecated since Django 4.2. I assume there is a good reason for eliminating this fuction, so what should I use instead? I searched for alternatives, but could not find any native to Django. I can create my own solution using hashlib, but should I? -
Django : MixIn or One-to-One for User
I have a Django project containing among others, 2 models : Contact and User. I want a contact to have the ability to be transformed into a user. I am hesitating between 2 choices : Using MixIn to make my User inherit from Contact Using One-to-One but in the reverse way from the documentation Here is option 1: #models.py from django.db import models from django.contrib.auth.models import AbstractUser class OwningCompany(models.Model): name = models.CharField(max_length=255) class Entreprise(models.Model): owning_company = models.ForeignKey(OwningCompany, on_delete=models.CASCADE) name = models.CharField(max_length=255) class Contact(models.Model): owning_company = models.ForeignKey(OwningCompany, on_delete=models.CASCADE) name = models.CharField(max_length=255) lastname = models.CharField(max_length=255) email = models.EmailField(max_length=255) class User(Contact, AbstracUser): pass And here is option 2 : #models.py from django.db import models from django.contrib.auth.models import AbstractUser class OwningCompany(models.Model): name = models.CharField(max_length=255) class Entreprise(models.Model): owning_company = models.ForeignKey(OwningCompany, on_delete=models.CASCADE) name = models.CharField(max_length=255) class Contact(models.Model): owning_company = models.ForeignKey(OwningCompany, on_delete=models.CASCADE) name = models.CharField(max_length=255) lastname = models.CharField(max_length=255) email = models.EmailField(max_length=255) class User(AbstractUser): contact = models.OneToOneField(Contact, on_delete=models.CASCADE) Might be of interest to know that I will always query for a single OwningCompany. What is the best way of doing this ? -
Running django app as a service and it failing to load the base templates
I have created this django appraisal app and I am running it on my company premises server and did not want to have to run in with cmd for obvious reasons. So I created this simple service that runs it on the a certain port. The problem is that all css fails to load and the base templates cannot be found when I run it. It is worth noting that when I run it from cmd everything loads perfectly but when I start the service, the base templates cannot be found. Here is the service I am using: <service> <id>appraisal</id> <name>Appraisal</name> <description>This service runs Pergamon Appraisal tool</description> <executable>C:\Users\Administrator\AppData\Local\Programs\Python\Python312\python.exe</executable> <arguments>C:\perg_appraisal\pergamon_appraisal\pergamon\manage.py runserver 0.0.0.0:9190</arguments> <logpath>C:\perg_appraisal\pergamon_appraisal\service_logs</logpath> <log mode="roll"></log> </service> Here is my BASE_DIR path in settings: BASE_DIR = Path(__file__).resolve().parent.parent Here is my templates: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR,'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] and here is my static files urls: STATIC_URL = 'static/' STATICFILES_DIRS = [BASE_DIR / 'static'] What could be making my base templates not visible when running it as a service? -
Django Model Error : Code is not getting renderd
So, I having a database in which there is html code which i wanna render i show you the model first model.py class Badge(models.Model): name = models.CharField(max_length=255) code = models.CharField(max_length=700, default='<h5><span class="badge bg-primary ms-2">New</span></h5>') code_price = models.CharField(max_length=700, default='<s>{{product.price | safe}}</s><strong class="ms-2 text-danger">{{product.get_price_with_discount() | safe}}</strong>') # product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='badges') def __str__(self): return self.name class Product(models.Model): """A product.""" name = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='static/img/' , default='/static/img/404.png') category = models.ForeignKey(Category, on_delete=models.CASCADE) type = models.ForeignKey(Badge, on_delete=models.CASCADE, related_name= "products") def get_price_with_discount(self): discount = (self.price) * (10 / 100) return self.price - discount now in Django it cant find the product.price since product is defined later or u can say it renders it but as a string i send the html page code now services.html <section> <div class="text-center container py-5"> <h4 class="mt-4 mb-5"><strong>Bestsellers</strong></h4> <div class="row"> {% for product in products %} <div class="col-lg-4 col-md-12 mb-4"> <div class="card"> <div class="bg-image hover-zoom ripple ripple-surface ripple-surface-light" data-mdb-ripple-color="light"> <img src="{{product.image.url}}" class="w-100" style="height: 500px;" /> <a href="#!"> <div class="mask"> <div class="d-flex justify-content-start align-items-end h-100"> {% comment %} <h5><span class="badge bg-primary ms-2">New</span></h5> {%endcomment %} {{product.type.code|safe}} </div> </div> <div class="hover-overlay"> <div class="mask" style="background-color: rgba(251, 251, 251, 0.15);"></div> </div> </a> </div> <div class="card-body"> <a href="" class="text-reset"> <h5 class="card-title … -
Django summernote text editor when edit the bullet point or number it's not showing on Django template?
SummerNote editor bullet point and number not showing on Django Template here my config setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'web.apps.WebConfig', 'django_summernote', ] X_FRAME_OPTIONS = 'SAMEORIGIN' MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / 'media/' here url.py settings path('summernote/', include('django_summernote.urls')), admin.py settings from django.contrib import admin from .models import Navmenu, NavSubmenu, WebPage, WebUrl, Seo,NewLatter, Project from django_summernote.admin import SummernoteModelAdmin class ProjectAdmin(SummernoteModelAdmin): list_display = ('name','sort_title','slug','create_by','create_at','update_at','status') summernote_fields = ('desc') admin.site.register(Project, ProjectAdmin) view.py settings def Projects_Details(request,slug): tags = Seo.objects.filter(pages_title__name = "Project-Details").first() pro_de = Project.objects.filter(slug = slug).first() context = { 'tags':tags, 'pro_de':pro_de, } return render(request,'web/project_detail.html', context) templates {{pro_de.desc | safe}} here editor pic. and here template output pic. -
PyCharm: The app module <module 'Photometry' (namespace)> has multiple filesystem locations
The backend of my django project works perfectly well in my terminal but i ll like to run it on PyCharm in debug mode. When I try, i get the following error: django.core.exceptions.ImproperlyConfigured: The app module <module 'Photometry' (namespace)> has multiple filesystem locations (['/usr/src/app/Photometry', '/opt/project/etc/Photometry']); you must configure this app with an AppConfig subclass with a 'path' class attribute. First part of the error Second Part of the error I precise the the project is in a docker container It is supposed to do something like this: What happens in my terminal Oh and in the very beginning of the error I have this: The very beginning I've been stuck there for more than a week now. PLEASE HELP Thank youuu. -
[Vue warn]: Failed to mount app: mount target selector "#app" returned null
Please help me figure this out. Been for a while trying to figure this out but can't make it work. Where should I put my <script src="{% static 'js/custom-vue.js' %}"></script> to be able to resolve the error shown in the image below? Thank you. master.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Profile</title> {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} <script src="{% static 'js/vue.global.js' %}"></script> <script src="{% static 'js/custom-vue.js' %}"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css"> </head> <body> <div class="container"> {% block content %} {% endblock %} </div> </body> profile.html {% extends 'users/master.html' %} {% block title %} Profile Page {% endblock %} {% block content %} <h2>Profile</h2> <p>ID: {{ user.id }}</p> <p>Username: {{ user.username }}</p> <p>Email: {{ user.email }}</p> <p>First name: {{ user.first_name }}</p> <p>Last name: {{ user.last_name }}</p> <p><a href="{% url 'logout' %}">Logout</a></p> <div class="container-fluid"> <div id="app"> <button @click="showModal" class="btn btn-primary"><i class="bi bi-calendar-event"></i> New Event</button>&nbsp; <button @click="showCalModal" class="btn btn-primary"><i class="bi bi-calendar-check"></i> Calendar Category</button>&nbsp; <button @click="showDivModal" class="btn btn-primary"><i class="bi bi-person-square"></i> Division</button>&nbsp; <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Add event</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form> <p><input type="text" name="event_title" class="form-control" … -
WebSocket connection to 'wss://www.aniconnect.org/ws/chat/AUdZzo8slKKwKvzmUrnmLRfnVkuAYfJj/' failed:
I have been working on a django chatting application that uses websockets to implement its chatting functionality. The site was working fine when it was being accessed through an IP address but when I tried to get an SSL certificate using letsencrypt, it broke. I was following the guide at letsencrypt: https://certbot.eff.org/instructions?ws=nginx&os=ubuntufocal Everything was going fine until I had to enter the "sudo certbot --nginx" command in the terminal which prompted me to enter a domain name, which I hadn't bought. So before I bought a domain name, I tested the site and then it broke. The chatting functionality was no longer working but I thought that it was just part of getting an SSL certificate so I proceeded to buy a domain name. I managed to get the domain name set up properly but that error was not resolved. I even managed to get an SSL certificate for that domain name using the "sudo certbot --nginx" command. The websockey connection is unable to be established for some reason. The following is the nginx config file: server { listen 80; server_name www.aniconnect.org; return 301 https://$host$request_uri; } server { listen 443 ssl; server_name www.aniconnect.org; ssl_certificate /etc/letsencrypt/live/www.aniconnect.org/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/www.aniconnect.org/privkey.pem; location = /favicon.ico … -
Getting Intermittent 403 error while making a fetch request from JS
I am trying to call a POST API via fetch await in JS which sometimes gives 201 and sometimes it gives 403. const apiCalls = number_arr.map(async (event) => { const response = await fetch(`{% url 'base_check_url' %}?number=${event.attrs.value}`, { method: "POST", credentials: 'include', headers: {'Content-Type': 'text/plain'}, }); APIs are written using django framework Attaching screenshot of error response logged in console: This is an intermittent issue, if I hit the API via JS 10 times, 70% of the time I would get 403. Also, do let me know if any other info is required to debug this issue. Thanks in advance. -
Django can't find existing html file in template folder
I'm trying to get the login page working on a seperate Django app. My register.html works just fine but i can't do the same with login html. The Error: TemplateDoesNotExist at /members/login/ registration/login.html Request Method: GET Request URL: http://127.0.0.1:8000/members/login/ Django Version: 4.2.4 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Exception Location: C:\Users\Furkan\AppData\Roaming\Python\Python311\site-packages\django\template\loader.py, line 47, in select_template Raised during: django.contrib.auth.views.LoginView Python Executable: C:\Program Files\Python311\python.exe Python Version: 3.11.5 Python Path: ['C:\\Users\\Furkan\\desktop\\dcrm\\dcrm', 'C:\\Program Files\\Python311\\python311.zip', 'C:\\Program Files\\Python311\\DLLs', 'C:\\Program Files\\Python311\\Lib', 'C:\\Program Files\\Python311', 'C:\\Users\\Furkan\\AppData\\Roaming\\Python\\Python311\\site-packages', 'C:\\Program Files\\Python311\\Lib\\site-packages'] Server time: Fri, 06 Oct 2023 13:59:43 +0000 views.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('website.urls')), path('members/', include('django.contrib.auth.urls')), path('members/', include('members.urls')), ] members/views.py: from django.shortcuts import render from django.views import generic from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy class UserRegister(generic.CreateView): form_class = UserCreationForm template_name = 'registiration/register.html' success_url = reverse_lazy('login') members/templates/registiration/login.html: {% extends 'base.html' %} {% block title %} Login {% endblock %} {% block content %} <div class="col-md-7 offset-md-3"> <h1 class="heading-one">Login</h1> <br> <br> <div class="form-group"> <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-success">Login</button> </form> </div> </div> {% endblock%} website/templates/navbar.html: <nav class="navbar navbar-expand-lg navbar-dark nav-color fixed-top"> <a class="navbar-brand" href="{% url 'home' %}" ><b>Furkan Çelik</b></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" … -
Classification ai model is integrated in Django app. I have configured using nginx for production purpose but i am facing an issue. "Trusted origin"
when i run project using local host on port 8000 then my project runs and displays the result but when i run it on port 81 project runs but doesn't display result. Error: Forbidden (Origin checking failed - http://textapp.local:81 does not match any trusted origins.): I have done "inginx" config. -
How to include Flask routes inside the Django
I wanted to use the Plotly Dash inside the Django. I don't want to use the django-plotly-dash python library because it have compatibility issues and all. Is there any way to include the Flask routes other than that Suggest a way to include the flask routes -
update the object in the database to indicate that a payment has been successfully processed
` @csrf_exempt def stripe_webhook(request): stripe.api_key = settings.STRIPE_SECRET_KEY time.sleep(30) payload = request.body signature_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, signature_header, settings.STRIPE_WEBHOOK_SECRET) except ValueError as e: logging.error(f"ValueError: {e}") return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: logging.error(f"SignatureVerificationError: {e}") return HttpResponse(status=400) if event['type'] == 'checkout.session.completed': session = event['data']['object'] session_id = session.get('id', None) if session_id: try: user_payment = UserPayment.objects.get(stripe_checkout_id=session_id) user_payment.payment_bool = True user_payment.save() logging.info(f"Updated payment_bool for session_id: {session_id}") except UserPayment.DoesNotExist: logging.error(f"UserPayment not found for session_id: {session_id}") else: logging.error("session_id is missing in the event data.") return HttpResponse(status=200)` I have been trying to update the 'UserPayment' object in the database to indicate that a payment has been successfully processed, but it doesn't work, even though the payment is successful in sripe -
I recently deployed my website and while submitting the forms or logging in on admin, I get this error
I get this problem almost every time I tried to do login admin and submit forms. After logging in admin and sending form same error is occuringg. I have left the default admin panel of django for site updates and used crispy forms for form in my website. -
My static files are not coming in my Django API project after deploying it in AWS EC2
I have created a simple API with django but after deploying it on AWS EC2 the admin panel is not showing any CSS or design. Please Help. Like This: enter image description here nginx file: server { listen 80; server_name 0.0.0.0; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/sweetraga_django/static/; } location / { proxy_pass http://0.0.0.0:8000; } } settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static')