Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Do null foreign keys slow things down?
I'm implementing file attachments for certain objects in the project I am working on. There are six or so object classes which might reasonably have attached files (which would be revealed in their Detail views and managed via a link from there). The model would be like class JobFile( models.Model): job = models.ForeignKey( 'jobs.Job', models.SET_NULL, null=True, blank=True, related_name='attachments', ) quote = models.ForeignKey( 'quotation.Quote', models.SET_NULL, null=True, blank=True, related_name='attachments', ) #etc document = models.FileField( ... ) # the attachment One advantage of this rather than a Generic ForeignKey is that an upload can be attached to more than one sort of object at once. Another is the simplicity of referring to obj.attachments.all() in the obj detail views. I'm not looking for a large set of object classes to which these files might be attached. However, for any one file attachment most of its ForeignKeys will be null. I have seen various references to null ForeignKeys causing slow Django ORM queries. Is this anything I need to be concerned about? If it makes any difference, these objects will be almost exclusively accessed via the attachments reverse ForeignKey manager on the related object. The only time I can see a need for explicit filtering … -
Here is another question on No module named 'rest_framework_jwtmusicapp' musicapp being the name of the app i'm worrking on
I have installed the djangorestframework-simplejwt but i still get this red zig-zag underline on this import statement from rest_framework_jwt.settings import api_settings this is from veiws.py and here is the error code from my terminal (venv) C:\Users\Administrator\Desktop\Zuri Assignment\Week 5\songcrud>python manage.p y runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\Administrator\Desktop\Zuri Assignment\Week 5\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) import_module(entry) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\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 "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework_jwtmusicapp' (venv) C:\Users\Administrator\Desktop\Zuri Assignment\Week 5\songcrud>python -m pip install djangorestframework Requirement already satisfied: djangorestframework in c:\users\administrator\desktop\zuri assignment\week 5\venv\lib\site-packages (3.10.0) (venv) C:\Users\Administrator\Desktop\Zuri Assignment\Week 5\songcrud>python -m pip install djangorestframework-simplejwt Requirement already satisfied: djangorestframework-simplejwt in c:\users\administrator\desktop\zuri assignment\week 5\venv\lib\site-packages (5.2.2) Requirement already satisfied: pyjwt<3,>=1.7.1 in c:\users\administrator\desktop\zuri assignment\week 5\venv\lib\site-packages (from djangorestframework-simplejwt) (2.6.0) Requirement already satisfied: djangorestframework in c:\users\administrator\desktop\zuri assignment\week 5\venv\lib\site-packages (from djangorestframework-simplejwt) (3.10.0) Requirement already satisfied: django in c:\users\administrator\desktop\zuri assignment\week 5\venv\lib\site-packages (from djangorestframework-simplejwt) (4.1.3) Requirement already satisfied: sqlparse>=0.2.2 in c:\users\administrator\desktop\zuri assignment\week 5\venv\lib\site-packages (from django->djangorestframework-simplejwt) (0.4.3) Requirement … -
Why I got "http://~" as redirect url parameter althoguh I set "https://~" to LOGIN_REDIRECT_URL in mozilla-django-oidc?
I've been trying to integrate Django app with Keycloak using mozilla-django-oidc and fix the problem as refered to in the title. I configured LOGIN_REDIRECT_URL and the configurations that are required in settings.py LOGIN_REDIRECT_URL = "https://~" and prepared Django template. {% if request.user.is_authenticated %} \<p\>Current user: {{ request.user.email }}\</p\> \<form action="{{ url('oidc_logout') }}" method="post"\> {{ csrf_input }} \<input type="submit" value="logout"\> \</form\> {% else %} \<a href="{{ url('oidc_authentication_init') }}"\>Login\</a\> {% endif %} However I clicked the Login link, then I got the error message which says invalid redirect url because redirect url parameter was changed to http://~. I looked through the code of mozilla-django-oidc, and seemed that there's no function changing "https://~" to "http://~" as redirect url parameter and I set "https://~" to LOGIN_REDIRECT_URL so there might be something wrong with reverse proxy which is Istio in my case. I haven't configured anything by myself so far. In case of using Ngnix, this problem can be solved like this. I'd like you to answer what's the cause of problem and how to fix it. I appreciate for your time to read this. -
AlterField shows the error `Duplicate key name`
In my migration file, there is the AlterField like this migrations.AlterField( model_name='historicalglobalparam', name='history_date', field=models.DateTimeField(db_index=True), ), my table historicalglobalparam has history_date column When appling this $python manage.py migrate The error appears django.db.utils.OperationalError: (1061, "Duplicate key name 'shared_models_historicalglobalparam_history_date_26e0c543'") However there comes error like this. I wonder it's AlterField not AddField Why this erorr comes? -
This site can’t be reached domain.de refused to connect
I have a project, Frontend with Flutter and Backend with Django. It was working fine. I wanted to change HTTP to HTTPs. now I am getting the error This site can’t be reached domain.de refused to connect The Nginx file for the Frontend: server { server_name visoon.de; root /home/visoon_frontend/build/web; index index.html; listen 443 ssl; ssl_certificate /etc/letsencrypt/live/visoon.de/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/visoon.de/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; } server { if ($host = visoon.de) { return 301 https://$host$request_uri; } listen 80; server_name visoon.de; return 404; } And Nginx file for the Backend: upstream visoon_app_server { server unix:/home/visoon_backend/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name visoon.de; client_max_body_size 4G; proxy_read_timeout 1200s; access_log /home/visoon_backend/logs/nginx-access.log; error_log /home/visoon_backend/logs/nginx-error.log; location /static/ { alias /home/visoon_backend/visoon_backend/static/; expires -1; } location /media/ { alias /home/visoon_backend/visoon_backend/static/media/; expires -1; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; # proxy_buffering off; if (!-f $request_filename) { proxy_pass http://visoon_app_server; break; } } # Error pages error_page 500 502 503 504 /500.html; location = /500.html { root /home/visoon_backend/visoon_backend/static/; } } Does anyone know why I am getting this error? many thanks for considering my request. -
how to i save data in django after i filter in forms using kwargs.pop?
when a try to filter category to match user it works but I can't save data to the form anymore and it show any error? forms.py: from django import forms from django.forms import ModelForm from .models import Createservice from .models import Category class Serviceform(ModelForm): class Meta: model = Createservice fields = ['user', 'Service_name', 'description', 'your_sertificate', 'category'] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(Serviceform, self).__init__(*args, **kwargs) print(self.user) if self.user is not None: self.fields['category'].queryset = Category.objects.filter( wilaya=self.user.wilaya) views.py: @login_required def createservice(request): if request.method == 'POST': user = request.user services = Serviceform(request.POST,request.FILES, user=user) if services.is_valid(): servicess = services.save(commit=False) servicess.user = user servicess.save() return redirect('index') else: user = request.user services = Serviceform(user=user) context = {"service": services} return render(request, 'services/createservice.html', context) createservice.html: <form action="{% url 'create-service' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-row"> <div class="col form-group"> <label>Service_name</label> {{service.Service_name}} </div> <!-- form-group end.// --> <div class="col form-group"> <label>Description</label> {{service.description}} </div> <!-- form-group end.// --> </div> <!-- form-row end.// --> <div class="form-row"> <div class="form-group col-md-6"> <label>your_sertificate </label> {{service.your_sertificate}} </div> <!-- form-group end.// --> <!-- form-group end.// --> </div> <!-- form-row.// --> <!-- form-row.// --> <div class="form-row"> <div class="form-group col-md-6"> <label>select your category </label> {{service.category}} </div> <!-- form-group end.// --> <!-- form-group end.// --> </div> <!-- … -
Some static files showing some not in django project . Why?
[ As about.jpg runs but doesnt runs building.jpg is written. urlpatterns = [ path('', include('pages.urls')), path('listings/', include('listings.urls')), path('accounts/', include('accounts.urls')), path('contacts/', include('contacts.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Rest API instead of table in Django Proxy unmanaged models
In my Django arch. task I must connect multiple projects. Some can only communicate through REST API and don't have common database access. However, the task is to provide seamless communication on model level. I.e. my model should serve as a wrapper for read requests in such a way, that business layer does not see the difference between local models and models that wrap remote data. Assuming that inherited create-delete-update methods will do nothing. I have read these: Proxy models documentation Unmanaged models documentation Also documentation on creation of custom managers and querysets. However, not a single good example for what I am set to achieve. Perhaps you can provide a solid Django example how to modify manager and query set in this way? -
Invalid block tag on line 95: 'endif', expected 'empty' or 'endfor'. Did you forget to register or load this tag? plz solve this
TemplateSyntaxError at /product/df/ Invalid block tag on line 95: 'endif', expected 'empty' or 'endfor'. Did you forget to register or load this tag? i got this error when i making a ecommerce app ` </div> <!-- col.// --> {% if product.size_variant.count %} <div class="form-group col-md"> <label>Select size</label> <div class="mt-1"> {% for size in product.size_variant.all %} <label class="custom-control custom-radio custom-control-inline"> <input type="radio" onclick="get_correct_price('{{size.size_name}}')" name="select_size" {% if selected_size==size.size_name %} checked {% endif %} class="custom-control-input"> <div class="custom-control-label">{{size.size_name}}</div> </label> {% endfor %} ` please solve this problem -
Django, how to refresh html page not in urls.py only included with tags
I am working on an app that utilizes the {% include %} tags to build pages. Basically I have a layout.html that serves as the base and it has an include tag for the navbar.html and {% block content %} for other pages e.g. home, login, user etc. In the navbar.html there is another {% include %} for my notification.html which contains the badge icon for notifications. I am using django-notifications-hq to handle the notifications. Everything works, but to get new notifications, I have to refresh the page. I want the badge (or notifications.html) to update periodically. Here are the html pages, the layout.html, navbar.html and notification.html; they are not in the urls.py file, simply called via tags. layout.html {% load static %} <!DOCTYPE html> <html> <head> <title>Application</title> <link rel="stylesheet" type="text/css" href="{% static 'bootstrap/css/bootstrap.min.css' %}" /> <link href="{% static 'css/login.css' %}" rel="stylesheet"> <script type="text/javascript" src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> <script type="text/javascript" src="{% static 'javascript/tablesorter.js' %}"></script> <script type="text/javascript" src="{% static 'javascript/refreshpage.js' %}"></script> </head> <body> <div id="notifylist"> {% include 'VegeApp/navbar.html' %} </div> <hr /> {% if messages %} <ul class="alert"> {% for message in messages %} {% if message.tags == 'debug' %} <li class="alert alert-secondary">{{ message }}</li> {% endif %} {% if message.tags … -
Use OpenCellID data local in python to lookup single locations
I'm trying to host the OpenCellID dataset world (https://opencellid.org/downloads.php?token=world) local. Note: I have to run that local, because the machine has no connection to the internet (for the opencellid api) My usage: I am using django as a backend in python. I upload a file there with cellid data, which I want to convert to lat:long and import that set into the database. The opencellid dataset is very huge, so it's expensive to read the file all the time. Input: MCC-MNC-LAC-CellID Output lat:long from the specific line in the opencellid dataset I was reading the csv with pands, but It takes a lot of power and time to read it into a variable. -
Django Channels websocket error while building the tutorial
I'm using django channels tutorial and I did whatever there was in the tutorial , and I'm getting error from my Terminal while I click the send button of my message which is: "GET /ws/chat/lobby/ HTTP/1.1" 404 2232 my routing.py file : from django.urls import re_path from .consumers import ChatConsumer websocket_urlpatterns = \[ re_path('ws/chat/\<room_name\>', ChatConsumer.as_asgi()), \] my consumers.py : import json from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_dict = json.loads(text_data) message = text_data_dict['message'] self.send(text_data=json.dumps({ 'message': message })) views.py : from django.shortcuts import render def index(request): return render(request, "chat/index.html") def room(request, room_name): context = { "room_name": room_name } return render(request, 'chat/room.html', context) urls.py : from django.urls import path from .views import index, room urlpatterns = [ path('', index, name='index'), path('<str:room_name>/', room, name='room') ] asgi.py file : import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import Chat.routing os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( Chat.routing.websocket_urlpatterns ) ), }) and my room.html file : <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Room</title> </head> <body> <textarea id="chat-log" cols="100" rows="20"></textarea><br> <input id="chat-message-input" type="text" size="100"><br> <input id="chat-message-submit" type="button" value="Send"> {{ room_name|json_script:"room-name" }} <script> const roomName = … -
How can I assign different platform ID to multiple candidates before saving it to the database?
I have a formset that takes in 7 candidates and each candidate should have a platform id. When I try to assign a platform to a candidate in a for loop, it only assigns the first platform ID to all candidates. here is my view fuction. def addcandidate(request): party = PartyList.objects.all() partylist_form = PartylistForm() PlatformSet = formset_factory( PlatformForm,extra=7) candidateFormSet = formset_factory(CandidateProfileForm,extra=7) form1 = PlatformSet(prefix='platform') form2 = candidateFormSet(prefix='candidate') if request.method == 'POST': partylist_form = PartylistForm(request.POST) form1 = PlatformSet(request.POST, prefix='platform') form2 = candidateFormSet(request.POST,request.FILES,prefix='candidate') if form1.is_valid() and form2.is_valid() and partylist_form.is_valid(): try: partylist = PartyList.objects.get(partylist_name=request.POST['partylist_name']) except ObjectDoesNotExist: partylist = partylist_form.save() for f1 in form1: p1 = f1.cleaned_data['platform'] p2 = f1.cleaned_data['platform2'] p3 = f1.cleaned_data['platform3'] try: Platform.objects.get(candidate_platform=p1) except ObjectDoesNotExist: platform = Platform(candidate_platform=p1,candidate_platform2=p2,candidate_platform3=p3) platform.save() for count,f2 in enumerate(form2): name = f2.cleaned_data['name'] img = f2.cleaned_data['Candidate_Img'] try: CandidateProfile.objects.get(name=name) except ObjectDoesNotExist: candidate = CandidateProfile(Candidate_Img=img,name=name) candidate.save() candidate.platform = platform candidate.partylist = partylist if count == 0: candidate.position = Position.objects.get(id=1) elif count == 1: candidate.position = Position.objects.get(id=2) elif count == 2: candidate.position = Position.objects.get(id=3) elif count == 3: candidate.position = Position.objects.get(id=4) elif count == 4: candidate.position = Position.objects.get(id=5) elif count == 5: candidate.position = Position.objects.get(id=6) elif count == 6: candidate.position = Position.objects.get(id=7) candidate.save() return redirect(request.META['HTTP_REFERER']) else: print(form1.errors) print(form2.errors) print(form1.non_form_errors) print(form2.non_form_errors) context = … -
Boto3, how to disable ACL when using generate_presigned_url?
I keep getting this error: An error occurred (AccessControlListNotSupported) when calling the PutObject operation: The bucket does not allow ACLs I'm switching to chunked uploads, previously i could do below and this uploaded fine. original = models.FileField(storage=S3Boto3Storage(bucket_name='video-sftp',default_acl=None),upload_to='', blank=False, null=False) Now i'm using generate_presigned_url and the ACL parameter is being ignored. url = client.generate_presigned_url( ClientMethod="put_object", Params={ "Bucket": "video-sftp", "Key": f"{json.loads(request.body)['fileName']}", "ACL": "None" }, ExpiresIn=300, ) How do i solve? -
How to connect to a postgres database in a docker container?
I setup my django and postgres container on my local machine and all working fine. Local server is running, database running but I am not being able to connect to the created postgres db. docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" depends_on: - db db: image: postgres:13.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=my_user - POSTGRES_PASSWORD=my_password - POSTGRES_DB=my_db volumes: postgres_data: I tried this command: docker exec -it container_id psql -U postgres error: psql: error: could not connect to server: FATAL: role "postgres" does not exist I am very new to Docker. -
Dajngo admin: more "view on site" alternatives
I am creating a fairly standard CRUD application with Django. For now I have chosen an approach where the common/complex properties can be edited using custom forms and the more exotic elements of the application must be edited with the django admin - works quite nicely. In the Django admin I really like the "View on site" link which will take me to view an object on the site. Now I would really like to other "call back into the site" functionalities: From the list view in django admin I would like to be able to have a "View on site" which takes me to a "list view" in the application. From the application view in Django admin it would be nice to have a "View on site" which takes me to an "application root" in the application. Are any such things available? -
Django admin is not accesible when DEBUG=False
I'm writing the backend for my app using django and django-rest-framework. The problem I have is that when I set DEBUG=False in my settings, the admin site (along with the browseable rest API) is no longer available, and I got a 500 response. The rest when queried/posted using JSON still works normally. This is my urlspatterns (I also tried including /admin at the top of the list) urlpatterns = [ path("", index, name="index"), path("api/", include(router.urls)), path("admin/", admin.site.urls), path("api-auth/", include("rest_framework.urls", namespace="rest_framework")), ] Since I'm creating my app using react, I'm testing a project structured in a way that all the django apps are contained in the same folder, being the main app: backend. I had to make some minor changes in the apps to accommodate this structure. For instance, this is an excerpt of how the installed apps: INSTALLED_APPS = [ ... "rest_framework", "backend", "backend.projects", "backend.tasks", "backend.subtasks", "backend.comments", ] And this is a capture of the folder tree. I think it must be something that changes in app/template discovery when changing from DEBUG=True to False. Point out that everything else apart from that works correctly: the root of my backend is serving the react app correctly, rest API works correctly as … -
Send data to my views.py: CSRF token missing
I have an html page which allows to send the contents of a csv file. From a javascript file I do different processing on the content. Then I would like to send to my view to add it to my database. When i click on the button i get this error: Forbidden (CSRF token missing.): /app/addDataInDB [11/Nov/2022 14:06:56] "POST /app/addDataInDB HTTP/1.1" 403 2506 .html <form id="myForm" method="POST"> {% csrf_token %} <input type="file" id="csvFile" accept=".csv" /> <br /> <button type="submit">Envoyer</button> </form> ... <script src="{% static 'js/readCSV.js' %}"></script> .js const form = document.getElementById('myForm') form.addEventListener('submit', sendData); function sendData(event){ event.preventDefault(); const res = { 0:{"val1": 1, "val2":2}, 1:{"val1": 3, "val2":4}} $.ajax({ type: "POST", url: 'addDataInDB', data: { "result": res }, dataType: "json", success: function (data) { alert("successfull") }, failure: function () { alert("failure"); } }) } app/urls.py from django.urls import re_path from . import views urlpatterns =[ re_path(r'^addDataInDB$', views.addDataInDB, name='addDataInDB'),] app/views.py def addDataInDB(request): if request.method == "POST": print(request.POST) -
get select option selected on form submit
how to get select option selected on form submit in html, I am creating project in Django, where i am using few bootstrap fields, my problem is that when I submit form bootstrap select options get their default value which I do not want, I want to get selected option selected rather their default value, please let me know if anyone have any idea I have tried few Jquery methods which did not worked for me. -
Why I got "http://~" as redirect url parameter althoguh I set "https://~" to LOGIN_REDIRECT_URL in mozilla-django-oidc?
I've been trying to integrate Django app with Keycloak using mozilla-django-oidc and fix the problem as refered to in the title. I configured LOGIN_REDIRECT_URL in settings.py LOGIN_REDIRECT_URL = "https://~" and prepared Django template. {% if request.user.is_authenticated %} <p>Current user: {{ request.user.email }}</p> <form action="{{ url('oidc_logout') }}" method="post"> {{ csrf_input }} <input type="submit" value="logout"> </form> {% else %} <a href="{{ url('oidc_authentication_init') }}">Login</a> {% endif %} However I clicked the "Login", then I got the error message which is invalid redirect url because redirect url parameter was changed to http://~. I looked through the code of mozilla-django-oidc, and seemed that there's no function changing "https://~" to "http://~" as redirect url parameter and set "https://~" to LOGIN_REDIRECT_URL so there might be something wrong with reverse proxy which is Istio in my case. I haven't configured it to anything by myself so far. In case of using Ngnix, this problem can be solved like this. I'd like you to answer what's the cause of problem and how to fix it. I appreciate for your time to read this. -
AttributeError at /login/ 'NoneType' object has no attribute 'has_header'
Я делаю авторизацию на сайте django, используя этот гайд: https://proproprogs.ru/django/delaem-avtorizaciyu-polzovateley-na-sayte. Я создал views class LoginUser(DataMixin, LoginView): form_class = AuthenticationForm template_name = 'shop/login.html' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) c_def = self.get_user_context(title="Авторизация") return dict(list(context.items()) + list(c_def.items())) потом в urls.py добавил path login urlpatterns = [ path('', index, name='index'), path('add_product', add_product, name='add_product'), path('login/', LoginUser.as_view(), name='login'), ] но при переходе на сайт через http://127.0.0.1:8000/login/ у меня появляется ошибка AttributeError at /login/ 'NoneType' object has no attribute 'has_header' Пытался гуглить но там конкретно такой проблемы как у меня не было, в основном писали про render и HttpRequest, но в моем коде его даже негде написать. Пытался гуглить но там конкретно такой проблемы как у меня не было, в основном писали про render и HttpRequest, но в моем коде его даже негде написать. -
The view products.views.get_product didn't return an HttpResponse object. It returned None instead
ValueError at /product/apple-ipad-air-5th-gen-64-gb-rom-109-inch-with-wi-fi5g-purple/ The view products.views.get_product didn't return an HttpResponse object. It returned None instead. how can i solve this problem please help me ` from django.shortcuts import render,redirect from products.models import Product from accounts.models import * from django.http import HttpResponseRedirect from products.models import * from django.utils.timezone import datetime # Create your views here. def get_product(request, slug): product = Product.objects.get(slug=slug) # comment = Comment.objects.get(slug=slug) if request.method == "POST": star = request.POST.get('star') name = request.user.first_name body = request.POST.get('body') review = Comment(star=star, name=name,body=body,date_added = datetime.today()) review.product = product review.save() return redirect(f'/product/{slug}', slug=product.slug) try: context = {'product': product, } if request.GET.get('size'): size = request.GET.get('size') price = product.get_product_price_by_size(size) context['selected_size'] = size context['updated_price'] = price return render(request, 'product\product.html' , context = context) except Exception as e: print(e) ` i am making a ecommerce website and i add review option then i got this error -
Display messages/notifications in NetBox
I would like some help with messages in NetBox, please. I'm writing a custom validator and I need to display a warning message if for example a device name doesn't fit the company's policy. I can't use the standard fail method in the CustomValidator class - the edit request should be fulfilled, it's just supposed to warn the user as well. I would like to use a box message like this one, just with the warning level. I tried something like this: from extras.validators import CustomValidator from django.contrib import messages class device_validator(CustomValidator): def validate(self, instance): if instance.name is not instance.name.upper(): messages.info(request, "Names of devices should be in all-caps.") return But clearly, my syntax is wrong. I get the "Server Error" window and following message: <class 'NameError'> name 'request' is not defined How do I define the request? Could someone please give me an example how to display a message in this context? Thank you. -
How to create a Django project that allows a User to install plugins from a marketplace Just like WordPress
I would like to create a Django project that allows me to sell services as packages. Here I mean, Users should visit my market place, choose a package they want, then click on Install. Just Like WordPress. This process should automatically do configurations in the background including running the required pip install app commands add the app into installed apps make necessary migrations collect static files I'm confused on how to implement this, and need your help on this. I have been able to create a Django project, and am able to package convert apps into packages. I also understand the consequences of conflicts in migrations and circular dependencies associated with multiple apps. What I want is to allow a user of my system to be able to install a package whenever they need to add it on their options, by just clicking install. -
add a custom attribute to the form using a class based view without use ModelForm class in django
is possible to add a custom attribute (like class="form-control") in all forms of a class based view without define ModelForm?