Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
displaying and processing a django form
I am newbie. I have some kind of online store. I need that after clicking on the buy button, which is located on the product page, the user is redirected to a page with a checkout form that contains the fields: phone number, mail and the product itself. URLS.PY from django.urls import path from first.views import productsHTML, productHTML, products_category, product_buy urlpatterns = [ path("productsHTML/<str:uuid>/buy", product_buy, name = "product_buy"), path("products_category/<str:id_category>", products_category, name = "products_category"), path("productsHTML/<str:uuid>", productHTML, name = "productHTML"), path("productsHTML/", productsHTML, name = "productsHTML"), ] FORMS.PY class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['email', 'phone_number'] widgets = { 'email': forms.EmailInput(), 'phone_number': forms.TextInput(), } VIEWS.PY def product_buy(request, uuid): if request.method == 'GET': product = Product.objects.get(id=uuid) form = OrderForm() return render(request, 'product_buy.html', {'product': product, 'form': form}) if request.method == 'POST': try: if form.is_valid(): product = Product.objects.get(id=uuid) email = form.cleaned_data['email'] phone_number = form.cleaned_data['phone_number'] order = Order.objects.create(email=email, product=product,phone_number=phone_number) return redirect('productsHTML') except: return render(request, 'productHTML.html', uuid = uuid) I use a construction try except so that in case of creating an order, the user is redirected to the page with all the products, and in case of failure: to the page of the product that he wanted to buy. PRODUCT_BUY.HTML {% extends 'products.html' %} … -
Can I used python programming for searchin rooms instead of javascripts
I am developing an Hotel booking website using django frameword how will created the search page can i used html value and pass to my view, or I will have to used javascript.(but I am not so good in js:|) I am expecting to used python and pass the html value in view.py files -
"TemplateDoesNotExist at /" django react webpack project
I have a Django React app integrated using WebPack. File structure as follows: |--CSP |--api /*django side*/ |--CSP |--Settings.py |--urls.py |--frontend /*react side*/ |--dist /*The template*/ |--index.html |--bundle.js |--src |--components |--App.js |--index.js |--styles.css |--tailwind.config.js |--postcss.config.js |--urls.py |--views.py |--webpack.config.js Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig', 'rest_framework', 'frontend.apps.FrontendConfig' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] Views.py (frontend) from django.shortcuts import render # Create your views here. def index(request, *args, **kwargs): return render(request, '/csp/frontend/dist/index.html') urls.py (frontend) from django.urls import path from . import views urlpatterns = [ path('', views.index) ] webpack.config.js const path = require('path') var webpack = require('webpack'); module.exports = { mode: 'development', entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, devServer: { static: { directory: path.resolve(__dirname, 'dist'), }, port: 3000, open: true, hot: true, compress: true, historyApiFallback: true, }, module: { rules: [ { test: /\.css$/i, include: path.resolve(__dirname, 'src'), use: ['style-loader', 'css-loader', 'postcss-loader'], }, { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, ], }, optimization: { minimize: true, }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV' : JSON.stringify('development') }) ], } Both react and django work perfectly … -
Django: Can I make a ForeignKey relation between one model and several others in Django?
I am new to Django, and not very advanced at this point. My goal is to make one "Comment" model that works for different "Post" models. My structure is as follows: class TunedCarPost(models.Model): ..... ..... class ConceptCarPost(models.Model): ..... ..... class ArticlePost(models.Model): ..... ..... class Comment(models.Model): post = models.ForeignKey( [TunedCarPost, ConceptCarPost, ArticlePost], related_name="comments", on_delete=models.CASCADE, ) ..... ..... I can't do such thing as: class Comment(models.Model): post = models.ForeignKey( [TunedCarPost, ConceptCarPost, ArticlePost], related_name="comments", on_delete=models.CASCADE, ) I tried to use an abstract model, so "Comment" only links to the abstract model: class Post(models.Model): ..... ..... class TunedCarPost(Post): ..... ..... class ConceptCarPost(Post): ..... ..... class ArticlePost(Post): ..... ..... class Comment(models.Model): post = models.ForeignKey( Post, related_name="comments", on_delete=models.CASCADE, ) ..... ..... But Django throws an exception that ForeignKey can't link to an abstract model. Is there any easy solutions for my case or my structure is total mess? -
runtime error on vercel for django project : No module named 'firebase_admin'
I am new to django and try to develop a web app which is based on firebase firestore .The app work fine in debug mode , however when i tried to deploy the app on web hosting site vercel it build successfully when i navigated my website it threw following exception : ERROR] ModuleNotFoundError: No module named 'firebase_admin' Traceback (most recent call last): File "/var/task/vc__handler__python.py", line 159, in vc_handler response = Response.from_app(__vc_module.app, environ) File "/var/task/werkzeug/wrappers/base_response.py", line 287, in from_app return cls(*_run_wsgi_app(app, environ, buffered)) File "/var/task/werkzeug/wrappers/base_response.py", line 26, in _run_wsgi_app return _run_wsgi_app(*args) File "/var/task/werkzeug/test.py", line 1096, in run_wsgi_app app_rv = app(environ, start_response) File "/var/task/django/core/handlers/wsgi.py", line 131, in __call__ response = self.get_response(request) File "/var/task/django/core/handlers/base.py", line 140, in get_response response = self._middleware_chain(request) File "/var/task/django/core/handlers/exception.py", line 58, in inner response = response_for_exception(request, exc) File "/var/task/django/core/handlers/exception.py", line 141, in response_for_exception response = handle_uncaught_exception( File "/var/task/django/core/handlers/exception.py", line 185, in handle_uncaught_exception callback = resolver.resolve_error_handler(500) File "/var/task/django/urls/resolvers.py", line 729, in resolve_error_handler callback = getattr(self.urlconf_module, "handler%s" % view_type, None) File "/var/task/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/var/task/django/urls/resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) File "/var/lang/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line … -
Django app works in Firefox but not chrome or edge
I've noticed that testing a django app I'm working on in anything but firefox causes issues with navigation, giving 404 errors for anything except the index page. Having looked around I can see that the problem is to do with trailing slashes in the urlpatterns, but even the default admin app uses a trailing slash which causes issues in different browsers. For some reason, in firefox I can navigate to a url like 'admin/' or 'admin' and it points to the correct page no problem, yet in chrome and edge, I can only navigate to the page if the url pattern matches exactly, including trailing slashes or not. I was under the assumption based on documentation the append_slashes was true by default and that chrome also has this behaviour built in. -
google login fails in django
I have created a Django project with both Google login and normal email login. When I try to login with my email, it works fine. However, if I have the same email associated with a Google login, the Google login redirects me to a different sign-in URL. I want to be able to create different accounts for Google login and email login, or connect the two if they have the same email. Can you please assist me with this issue? Thank you. -
I get this error - "ValueError: The 'photo' attribute has no file associated with it."
I've a registration page that does 2 things: Creates a new user; Creates a profile for this user; However it doesn't work properly. It doesn't matter if I upload a photo or not. Every time I've the same error. It creates a user however the problem is with it's profile. Here is my models.py code: from django.db import models from django.contrib.auth.models import UserManager, AbstractUser from PIL import Image class CustomUserManager(UserManager): def create_user(self, username, email=None, password=None, **extra_fields): user = self.model( email=self.normalize_email(email), username=username, password=password, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email=None, password=None, **extra_fields): user = self.model( email=self.normalize_email(email), username=username, password=password ) user.set_password(password) user.is_admin = True user.save(using=self._db) return user class CustomUser(AbstractUser): email = models.EmailField(max_length=254, unique=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) username = models.CharField(max_length=30) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) birthdate = models.DateField(blank=True, null=True) photo = models.ImageField(default='default.png', upload_to='profile_pics', blank=True ) def __str__(self): return f"{self.user.username} Profile" def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.photo.path) output_size = (300, 300) img = img.resize(output_size) img.save(self.photo.path) signup.html : {% block title … -
Getting JavaScript variable in Django
I'm rendering a dynamic calendar's values using JavaScript. I'm displaying the selected date in an element. How can I get the date (value of element generated by JavaScript) in Django? HTML <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/styles.css' %}"/> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200"> <title>Booking</title> </head> <body> <div class="container"> <div class="wrapper2"> <div class="price"> <p>Best price of 60,00 €</p> </div> <form action="" method="POST"> {% csrf_token %} <div class="display-date"> <p>Start date</p> <a id="start-date" name="start"></a> <!-- I need the value of this element in Django --> </div> <div class="display-date"> <p>End date</p> <a id="end-date" name="end"></a> </div> <h4>Enter your full name</h4> <input type="text" name="fullname"> <h4>Enter your e-mail</h4> <input type="text" name="email"> <input class="submit" type="submit" value="Request appointment"> </form> </div> <div class="wrapper"> <div class="outline"></div> <header> <div class="icons"> <span id="prev" class="material-symbols-rounded">chevron_left</span> <p class="current-date"></p> <span id="next" class="material-symbols-rounded">chevron_right</span> </div> </header> <div class="calendar"> <ul class="weeks"> <li>Sun</li> <li>Mon</li> <li>Tue</li> <li>Wed</li> <li>Thu</li> <li>Fri</li> <li>Sat</li> </ul> <ul class="days"></ul> </div> </div> </div> </body> <script src="{% static 'js/script.js' %}"></script> JavaScript const CURRENT_DATE = document.querySelector(".current-date"); days_tag = document.querySelector(".days"); previous_next_icon = document.querySelectorAll(".icons span"); // Getting new date, current year and motnh let date = new Date(), current_year = date.getFullYear() current_month = date.getMonth(); const months = … -
Filters for annotate in Django
How can I use Annotate to count only certain conditions? class User(models.Model) name = models.CharField(max_length=50) class Tweet(models.Model) user = models.ForeignKey("User", related_name="tweet") favorite = models.IntegerField(default=0) # I only want to count tweets with 100 or more favorites. users = User.objects.annotate(tweet_count=Count("tweet")) -
I can not send Email(Gmail) with Django on AWS
I upload a Web app created by Django(with Apache2) to AWS. I can send Emails from a Form on Ubuntu, but I can not on AWS EC2 and Server Error(500) occurs even if I use the same codes. If I send Email with python manage.py shell_plus, I can send Email. [ec2-user@]$ python manage.py shell_plus >>> from django.core.mail import send_mail >>> send_mail(mail_subject, mail_message, mail_from, mail_to, fail_silently=False,) But I cannot from the Django Web app. What should I do to send Email as Gmail? Or should I use Amazon SES instead? Thanks. settings.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_HOST_USER = os.environ.get("GMAIL_HOST_USER") EMAIL_HOST_PASSWORD = os.environ.get("GMAIL_HOST_PASSWORD") EMAIL_FROM_EMAIL = os.environ.get("GMAIL_HOST_EMAIL") EMAIL_USE_TLS = True I added Inbound Rule(EC2) port:587 IPv4:0.0.0.0 Django 4.1.7 Python 3.8.16 Apache 2.4.56 mod_wsgi 4.9.4 -
Save QuerySet result to json file and then unpack data from file
I need to save some rows from mysql table to json file (all values from this rows). I try to write this one: qs = SomeModel.objects.filter(type='some_type') qs_json = serializers.serialize('json', qs) with open('output.json', 'w', encoding='utf-8') as f: json.dump(qs_json, f, ensure_ascii=False, indent=4) I got file like this one: "[{\"model\": \"some_app.some_model\", \"pk\": 1, \"fields\": {\"description\": \"\", \"content_type\": 26, \"source_from_id\": 1, \"source_to_id\": 2, \"target\": \"main\", \"is_default\": true, \"parameters\": \"{\\\"window\\\": 43200}\", \"test_app\": 13, \"added_at\": \"2018-09-28\"}}, {\"model\": \"some_app.some_model\", \"pk\": 2, \"fields\": {\"description\": \"\", \"content_type\": 26, \"source_from_id\": 3, \"source_to_id\": 4, \"target\": \"main\", \"is_default\": true, \"parameters\": \"{\\\"_window\\\": 43200}\", \"test_app\": 13, \"added_at\": \"2018-09-28\"}}]" SomeModel have fields: description, content_type, source_from_id, source_to_id, target, is_default, parameters, test_app, added_at. I expect to get json file, because later I need to parse this file and load all this data back to database to another table. The structure should be like: [{"model": "some_app.some_model", "pk": 1, "fields": { 'description': "", 'content_type': 26, 'source_from_id': 1, 'source_to_id': 2, 'target': 'main', 'is_default': true, 'parameters': {}, 'test_app': 13, 'added_at': '2018-09-28' } }, {"model": "some_app.some_model", "pk": 1, "fields": { 'description': "", 'content_type': 26, 'source_from_id': 1, 'source_to_id': 2, 'target': 'main', 'is_default': true, 'parameters': {}, 'test_app': 13, 'added_at': '2018-09-28' } }] Then I have tried: with open('output.json', 'r') as f: json_file = f.read() … -
Quasar CLI with Vite + Django | Quasar SPA - Django
How to integrate Quasar SPA app with Django? Using: Quasar CLI with Vite Django Expected to have Django serving 'Index.html' and other static files build by 'quasar build' command. Which resides in "application/dist" and "application/dist/assets" directories. -
Too many db connections (django 4.x / ASGI)
I have deployed a django app (on ASGI using uvicorn) and getting a lot of OperationalError FATAL: sorry, too many clients already It seems that this is a known issue #33497 for django 4.x and ASGI, but I cant find anything on it (other than acknowledging it) so far Is there some way around this, or should I switch to WSGI (or downgrade to 3.2)? It seems to me that this is a blocking issue for using to ASGI altogether. Shouldn't it be better documented? (unless I missed it) -
Get a more Accurate search bar In Django
I currently have a working search bar for my Django website, but because of my database getting bigger the results get less accurate, for Example if I type in Her, the first object that shows up is The Marshall MatHERs LP2, but I want the Object that is literally named "her" to come first to make it more accurate, how to do this? Code: def search_album(request): if request.method == 'POST': searched = request.POST.get('searched') album = Album.objects.filter(title__contains=searched) return render(request, 'home/search_album.html', {'searched':searched, 'album':album}) else: return render(request, 'home/search_album.html') -
Django Channels wesbsocket fails on Heroku
I have an app which is deployed to Heroku and uses django channels 3.0.4. It's been running perfectly for the past 18 months but now gives the following error: WebSocket connection to 'wss://my-app.myurl/ws/quiztest/mc/' failed: I have not changed any of the code from when it was working previously. I also have a test version of the app running on Heroku using exactly the same codebase and it works fine, which would suggest the error may be to do with my Heroku config, although I've compared the settings of this app with the test app and they seem OK. Everything else in my app works fine, just the django channels websocket issue. I have spun up a simple test to recreate the issue. Here is the JS that tries to connect: <script> var loc = window.location; var wsStart = 'ws://'; if (loc.protocol == 'https:'){ wsStart = 'wss://'; } var endpoint = wsStart + loc.host + '/ws/quiztest/'; var username = 'mc'; var socket = new WebSocket(endpoint + username + '/'); console.log(socket); console.log(endpoint + username + '/'); socket.onopen = function(e) { console.log('Open Host Socket') }; socket.onmessage = function(event) { // Handle incoming messages from the server here console.log('Received message:', event.data); } socket.onclose = … -
Django admin site fails to load using static CSS
I have Django project for which the built-in admin client has stopped working. It looks like Python is failing to handle a list object when it is expecting a string(?) while loading a CSS file using Django's "static" methods. I've gone over my settings.py and admin.py and checked all "static" config settings against the Django documentation. When I run different Django projects, the admin site works fine. Here are the errors and settings from the project. I'm running Django 4.1.5 and Python 3.10.6 on the Django dev web server. Any pointers and advice are greatly appreciated. web page returns: AttributeError at /admin/login/ 'list' object has no attribute 'rsplit' Request Method: GET Request URL: http://localhost:8000/admin/login/?next=/admin/ Django Version: 4.1.5 Exception Type: AttributeError Exception Value: 'list' object has no attribute 'rsplit' Exception Location: /usr/local/lib/python3.10/dist-packages/django/utils/module_loading.py, line 25, in import_string Raised during: django.contrib.admin.sites.login Python Executable: /usr/bin/python Python Version: 3.10.6 Python Path: ['/home/ed/PycharmProjects/wikidataDiscovery', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/ed/.local/lib/python3.10/site-packages', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Sun, 26 Mar 2023 05:44:51 -0700 and pick of template error Here's all "static" info in settings.py: STATIC_URL = 'static/' # STATIC_ROOT = '' STATICFILES_STORAGE = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] -
How to get Django and ReactJS to work together in 2023?
I am new to both technologies but i have used WebPack and babel with Django rest framework. I had a lot of issues in my experience. I am also interested in using Vite but honestly i got lost in the installation guide. I'm looking to create a simple Django api backend and react frontend(fetching data with Axios. What's the best way to How can i integrate React and Django in 2023? -
What's wrong with my Django app deployed with Heroku? Server error 500
I made a blog using Django. I deployed it with Heroku, but when I load the page, it said Server Error 500. It is not loading my templates. What could went wrong? Maybe my settings.py is not sat up correctly. I'm new in Django and Heroku, so if anyone can help me, I would be thankful. Here is my file tree: Here is my settings.py: Here is a Heroku log: » Warning: heroku update available from 7.53.0 to 8.0.2. 2023-03-25T21:45:52.759511+00:00 app[web.1]: [2023-03-25 21:45:52 +0000] [2] [INFO] Starting gunicorn 20.1.0 2023-03-25T21:45:52.759842+00:00 app[web.1]: [2023-03-25 21:45:52 +0000] [2] [INFO] Listening at: http://0.0.0.0:32581 (2) 2023-03-25T21:45:52.759886+00:00 app[web.1]: [2023-03-25 21:45:52 +0000] [2] [INFO] Using worker: sync 2023-03-25T21:45:52.762814+00:00 app[web.1]: [2023-03-25 21:45:52 +0000] [7] [INFO] Booting worker with pid: 7 2023-03-25T21:45:52.816818+00:00 app[web.1]: [2023-03-25 21:45:52 +0000] [8] [INFO] Booting worker with pid: 8 2023-03-25T21:45:53.000000+00:00 app[api]: Build succeeded 2023-03-25T21:45:53.195760+00:00 heroku[web.1]: State changed from starting to up 2023-03-25T21:46:07.408261+00:00 app[web.1]: 2023-03-25 21:46:07 [8] [ERROR] pathname=/app/.heroku/python/lib/python3.11/site-packages/django/utils/log.py lineno=224 funcname=log_response Internal Server Error: /accounts/login/ 2023-03-25T21:46:07.408275+00:00 app[web.1]: Traceback (most recent call last): 2023-03-25T21:46:07.408276+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.11/site-packages/django/core/handlers/exception.py", line 47, in inner 2023-03-25T21:46:07.408276+00:00 app[web.1]: response = get_response(request) 2023-03-25T21:46:07.408276+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^^^ 2023-03-25T21:46:07.408277+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.11/site-packages/django/core/handlers/base.py", line 181, in _get_response 2023-03-25T21:46:07.408278+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2023-03-25T21:46:07.408278+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … -
Some files "rollback magically" to previous versions, probably related to DST - Daytime saving light (Also could be Django-related issue)
I'll try to give as much details as possible, as this problem is very strange to me (I've never seen this in +10 years of production servers maintenance), and I couldn't fully understand what happened, and how to prevent this to happen in the future. I'd love to hear your feedbacks. Chapter 1: The context and the problem I've got this one Django server production (running with Gunicorn), where a few instances of Django run (3, to be exact). For your information, this server runs on CentOS 7.5.1804. This morning, one of my Django instance (the most important one) was out of service (classic HTTP 502). First clue, I've got the message warning mydjangoinstance.service changed on disk. run 'systemctl daemon-reload' to reload units when I attempt to restart the service (my Django instances run with systemctl daemon). I don't really pay attention - know I should have tho - since we didn't make any recent changes to the .service file... After a small investigation, I notice that some critical files of my Django installation of this instance has changed, for no apparent reasons, they "rollback" to a far previous version. If you're familiar with Django architecture, it concerns files such … -
Nested forloop counter in django template
I created one django template, there i have nested 3 for loop there. i need to make forloop counter: {% for i in myloop1 %} {% for j in i.loop2 %} {% for k in j.func %} {{forloop.parentloop.counter}}_{{ forloop.counter }} {% endfor %} {% endfor %} {% endfor %} -
How to fix nested DRF serializer API response value is being inside list?
I have a problem with nested serializer. I'm using class absed validators, and raise custom Validation error that returns dictionary with key value paris that looks like this { "details": "Some error details", "summary": f"Field has error" } but when I'm raising error from nested serializer it has dufferent format, where value is an list instead of string "tags": [ { "details": [ "'My field' should not contain spaces" ], "summary": [ "Field Tag 'One more filed' should not contain spaces" ] } ] expected response "tags": [ { "details": "'My field' should not contain spaces", "summary": "Field Tag 'One more filed' should not contain spaces" } ] serializers.py class PostSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField(slug_field="name", read_only=True) title = serializers.CharField(required=True, validators=[TitleValidator()]) content = serializers.CharField(required=True) tags = TagSerializer(many=True, required=False) tag serializer module class TagSerializer(serializers.ModelSerializer): tag = serializers.CharField(min_length=3) class Meta: model = Tags fields = ["tag"] validators=[TagValidator()] class TagValidator: def __call__(self, tags: OrderedDict): tag = list(tags.values())[0] errors = [] if " " in tag: errors.append(f"'{tag}' should not contain spaces") if len(errors) > 0: raise PostException.validation_error( errors, "Tag", ) return tags erros.py file class PostException(Exception): @staticmethod def validation_error(error, field, **kwargs) -> ValidationError: data = { "details": error, "summary": f"Field {field} {error[0]}" } return ValidationError(data) When … -
EC2 Django instance ERR_ADDRESS_UNREACHABLE from outside
I have an EC2 instance working with NGinx and Gunicorn. Nginx is running fine. Gunicorn is running fine. Django app is running fine. When i curl -v 127.0.0.1:80 on the machine, i receive the home page. OK. But when i curl -v public_ip_address:80 or curl -v public_dns_address:80 i got unreachable error. So i simplify my nginx configuration with server { listen 80; server_name my_public_dns my_public_ip; return 200; } to reduce errors to the minimum. It's still the same error. My iptable : sudo iptables -vnL Chain INPUT (policy ACCEPT 0 packets, 0 bytes) pkts bytes target prot opt in out source destination 6 340 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:80 flags:0x17/0x02 ctstate NEW 2 120 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:8080 flags:0x17/0x02 ctstate NEW 80 port is obviously open in EC2 instance's security group. Firewall is ok. sudo ufw status verbose Status: inactive So it doesn't seem to be some of firewall, port, nginx, gunicorn error. I'm stuggling on it for few days ago. -
inner loop in button group django
I have two loops one iterates over the users and one to delete the users. Problem is the code is showing users next to each other and the button with svg icon next to each other, how can I append the user buttons with their svg icons? my Template: <div class="btn-group me-2 mb-2"> {% for user in usecase_assigned %} <button type="button" class="btn btn-outline-danger">{{user|join:', '}}</button> {% endfor %} {% for unassign in user_assigned %} <form action="{% url 'unassign_emp' eid=unassign.0 ucid=result.usecase_id %}" method="POST"> {% csrf_token %} <button type="submit" class="btn btn-danger" name="unassign_emp"> <svg xmlns=http://www.w3.org/2000/svg width="16" height="16" fill="currentColor" class="bi bi-file-x-fill" viewBox="0 0 16 16"> <path d="M12 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2zM6.854 6.146 8 7.293l1.146-1.147a.5.5 0 1 1 .708.708L8.707 8l1.147 1.146a.5.5 0 0 1-.708.708L8 8.707 6.854 9.854a.5.5 0 0 1-.708-.708L7.293 8 6.146 6.854a.5.5 0 1 1 .708-.708z"></path> </svg> </button> </form> {% endfor %} </div> what I'm getting: -
How to step forward queryset items to their foreignkey item in another model
class User(AbstractUser): id = models.BigAutoField(primary_key=True) class Follow(models.Model): id = models.IntegerField(primary_key=True) userPointer = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower") userTarget = models.ForeignKey(User, on_delete=models.CASCADE, related_name="followed", null=True) A users id passes to views, I want return followers queryset. I have tried:↓ test = User.objects.get(pk=request.user.id).follower.all() Now a qureryset of Follow model is generated. But I need each item be translate to it's appropriated userTarget foreignkey. test = User.objects.get(pk=request.user.id).follower.all().userTarget This not work!