Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django static files on AWS S3 Bucket
There are a bunch of questions similar to this one, but after going through some of them, I still can't get it right. I have a Django app and I want to serve static and media files using an AWS S3 Bucket. I can run python manage.py collectstatic and the files are added to the bucket. However, I am getting a 404 not found error for static files on the browser. There was a point in time that my configurations worked because I was able to see the files coming from s3 by inspecting the page, but I can't find what was changed for it not to work now. Here's my settings.py: USES_S3 = os.getenv('USES_S3') == 'True' if USES_S3: AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=31536000'} AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'core.storage_backends.StaticStorage' PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'core.storage_backends.MediaStorage' else: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles') MEDIA_URL = '/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') STATICFILES_DIRS = ( os.path.join(CORE_DIR, 'core/static'), ) storages_backend.py: from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' default_acl = 'public-read' file_overwrite = False class StaticStorage(S3Boto3Storage): location … -
Adding data to DB via Django Admin panel
I have a new Django project using Python 3.7 and Django 1.8 I’ve made a model, migration, superuser account. But admin panel won’t work when I’m trying to add anything in it. Why this error occurs and how to fix it? Error screenshot -
Django Retrieving data as 5 members groups
when retrieving objects in Django I want it to be divided into a group like for example get all products and the result should be 4 groups each group have 5 objects I don't mean to group by property just random groups each group have five members for example when retrieving products = Product.objects.all() i want the result to be product = [ [ {id:1, price:3}, {id:2, price:3}, {id:5, price:3}], {id:6, price:3}, {id:10, price:3}, {id:1, price:3}], {id:19, price:3}, {id:1, price:3}, {id:1, price:3}] ], so i want to like to get the query a number for example 3 so that it gives me group with 3 members in each -
Django + Bootstrap + Ajax form POSTing a ForeignKey?
I am having trouble with a bootstrap popup modal, and associating a ForeignKey to a POST request. I have a simple Add Note Button, and empty modal which is where the form data will be rendered. In the modal, I have an empty input field which grabs a database object, which will be the ForeignKey in my django view. <div class="container-fluid main-container"> <div class="text-center"> <button type="button" class="btn btn-danger js-create">Add Note</button> </div> </div> <div class="modal fade" id="modal-event"> <input type="hidden" id="eventID" name="event_id" value="{{ event_id }}"> <div class="modal-dialog"> <div class="modal-content"> </div> </div> and the form is as follows... <form method="post" action="{% url 'add_note' %}"> {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title">Add Note</h4> </div> <div class="modal-body"> {% for field in form %} <div class="form-group{% if field.errors %} has-error{% endif %}"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {% render_field field class="form-control" %} {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> {% endfor %} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save</button> </div> </form> This is the JS function that opens up the modal... $(function () { $(".js-create").click(function () { let event_id = $("input[name='event_id']").val(); console.log(event_id); // Logs the … -
Assign color to text in website based on ID in database
In my forums website, I want to assign a certain color to each role. For example the admin color is blue, so the username of this admin is always blue. In my database, I'm using MySQL, I have a role table that assigns an ID for each role and a users table linked to the role table. How can I assign the color I want to the role ID that I want? Note: I'm using Django for my back-end work Thank you. -
502 Bad Gateway on My Django Site when I click on A link to send message to all users
When clicked on the send sponsored message the site keeps on loading and after some time shows an error - 502 Bad Gateway. I have tried running the site on my localhost but the error does not come I think because my localhost does not contain a big database like the server. The view function called on click - #Send sponsored messages via Commondove user @login_required @user_passes_test(is_staff) @permission_required('send_sponsored_message') def sendSponsoredMessage(request): dictV = {} fromUser = get_object_or_404(UserModel, authUser = request.user) dictV['users'] = UserModel.objects.all().order_by('name') dictV['colleges'] = College.objects.all().order_by('collegeName') dictV['organizations'] = SocialOrganization.objects.all().order_by('organizationName') if request.method == 'POST': allDevices = [] allUserModelObjects = [] heading = request.POST.get('heading') text = request.POST.get('message') userPks = request.POST.getlist('users') image = request.FILES.get('image') if not text and not image: dictV['error'] = 'Message and Image both cannot be empty' else: #Call sendSponsoredMessageHelper with devices of all users sendSponsoredMessageHelper(text, image, userPks, fromUser) dictV['success'] = True return render(request, 'sendSponsoredMessage.html',dictV) sendSponsoredMessageHelper function mentioned above - #Send a sponsored message from dashboard def sendSponsoredMessageHelper(text, image, userPks, fromUser): userModelObjects = UserModel.objects.filter(pk__in = userPks) for user in userModelObjects: Message.objects.create(fromUser = fromUser, toUser = user, message = text, image = image, sponsored = True) #Send notification heading = fromUser.name authUserPks = [ x.authUser.pk for x in userModelObjects ] allDevices = GCMDevice.objects.filter(user__pk__in … -
Connecting to Postgres running on Windows from django running on WSL
I primarily develop on windows but I'm testing my app using WSL since I will push it to a linux server. My current issue is connecting the django app, running on WSL to postgres, running on windows. Many articles explain how to connect to postgres running on WSL but not the other way round. -
How to solve the translation/localisation of JavaScript external files since Django does not allow built-it tags in other files?
I was looking in other questions. I know that Django allows to use built-in tags in the internal JavaScript code on HTML page, but it is a bad practice that a professional developer would not do; I know that Django does not allow to use built-in tags in the external JavaScript files. Differently of it, Go Hugo allows. I considered the question Django translations in Javascript files, but I do not know if it is a bad practice to generate the JavaScript with the same name but with with different language abbreviation, as table-en.js, table-fr.js, table-pt-br.js, table-pt-pt.js, etc. The small code, for example: var preTtitle = 'List of colours and icon in'; const styles = [ { name: 'adwaita-plus', title: ' ' + preTtitle + 'Adwaita++' }, { name: 'suru-plus', title: ' ' + preTtitle + 'Suru++' }, { name: 'suru-plus-ubuntu', title: ' ' + preTtitle + 'Ubuntu++' }, { name: 'yaru-plus', title: ' ' + preTtitle + 'Yaru++' } ]; I also need to translate the table columns: firstHeader.textContent = 'Name of colour'; secondHeader.textContent = 'Preview of icons'; trHeader.appendChild(firstHeader); trHeader.appendChild(secondHeader); thead.appendChild(trHeader); I want to translate 'List of colours and icon in', 'Name of colour' and 'Preview of icons'. As … -
503 Service Temporarily Unavailable using Kubernetes
I am having some issue with creating ingress for a nginx service that I deployed in a kubernetes cluster. I am able to open the web page using port forwarding, so I think the service should work.The issue might be with configuring the ingress.I checked for selector, different ports, but still could not find where goes wrong. Anyone could help ? Thank you in advance. # Source: django/templates/configmap.yaml apiVersion: v1 kind: ConfigMap metadata: name: vehement-horse-django-config labels: app.kubernetes.io/name: django helm.sh/chart: django-0.0.1 app.kubernetes.io/instance: vehement-horse app.kubernetes.io/managed-by: Tiller enter code here data: --- # Source: django/templates/service.yaml apiVersion: v1 kind: Service metadata: name: vehement-horse-django labels: app.kubernetes.io/name: django helm.sh/chart: django-0.0.1 app.kubernetes.io/instance: vehement-horse app.kubernetes.io/managed-by: Tiller spec: type: ClusterIP ports: - port: 80 targetPort: 8080 protocol: TCP name: selector: app.kubernetes.io/name: django app.kubernetes.io/instance: vehement-horse --- # Source: django/templates/deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: vehement-horse-django labels: app.kubernetes.io/name: django helm.sh/chart: django-0.0.1 app.kubernetes.io/instance: vehement-horse app.kubernetes.io/managed-by: Tiller spec: replicas: selector: matchLabels: app.kubernetes.io/name: django app.kubernetes.io/instance: vehement-horse template: metadata: labels: app.kubernetes.io/name: django app.kubernetes.io/instance: vehement-horse spec: containers: - name: django image: "website:72cf09525f2da01706cdb4c6131e8bf1802ea6a3" imagePullPolicy: Always envFrom: - configMapRef: name: vehement-horse-django-config ports: - name: http containerPort: 8080 protocol: TCP resources: limits: cpu: 1 memory: 1Gi requests: cpu: 1 memory: 512Mi imagePullSecrets: - name: some-secret --- # Source: … -
"django.db.utils.OperationalError: no such table" when adding in new app
I recently added the mycase app to my larger django project but since then I have been getting all kinds of database errors. If any more information would be helpful just reply with a comment, I don't know exactly what would be helpful in this case. Thanks! Traceback: File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/opt/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/opt/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 368, in execute self.check() File "/opt/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/opt/anaconda3/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/opt/anaconda3/lib/python3.8/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/opt/anaconda3/lib/python3.8/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/opt/anaconda3/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/opt/anaconda3/lib/python3.8/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/opt/anaconda3/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/opt/anaconda3/lib/python3.8/site-packages/django/urls/resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "/opt/anaconda3/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, … -
The empty path didn’t match any of these. Django
I'm a total beginer at Django. Please help me to solve it, I've been trying to do so for 2 days. Essentially I created a model, defined a class there but when I open the page I get the error Using the URLconf defined in reports_proj.urls, Django tried these URL patterns, in this order: admin/ ^static/(?P<path>.*)$ ^media/(?P<path>.*)$ The empty path didn’t match any of these. urls.py 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), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) admin.py from django.contrib import admin from .models import Profile admin.site.register(Profile) settigs.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #our apps 'customers', 'products', 'profiles', 'reports', 'sales', #3rd party 'crispy_forms' ] When I put path('login/', admin.site.urls), it works but shows me Please enter the correct username and password for a staff account. whenever I try to log in as admin. It seems like I should write some methods in views.py, because it has only from django.shortcuts import render line. If it's true, which ones? -
how to create Django preferences (Site dashboard)
Hi I have ready Django project and I want to create a control panel for it, for example I want to add a field with the name of the site, a field with a description of the site, and a field with the logo of the site, and I call them in the templates instead of changing them manually through the editor every time. I upload the website logo to the static file and want to add an option to change it from the control panel instead of manually replacing it from the server. I have attached an illustration of what I want to reach. Thank you -
DJANGO - Admin Action
I'd like to create a website with for car dealer with admin and allow dealers to add, edit, delete car. My problem is that on Django Admin, when I login with any account I see all the cars and I'd like to show only cars attched to connected dealer. I create a model from django.db import models from django.contrib.auth.models import User import datetime from brand.models import Brands from django.urls import reverse class Car(models.Model): dealer = models.ForeignKey(User, on_delete=models.DO_NOTHING) brand = models.ForeignKey(Brands, on_delete=models.DO_NOTHING) carname = models.CharField(max_length=100) def __str__(self): return '%s %s' % (self.brand, self.carname) Also, when I create a car the dealer's list show all dealers in database, but me I'd like to display only connected account name. Thanks for your help -
Campo de endereços com opções dentro do FORMS usando Django?
Does anyone know how I can put an address field with options inside FORMS using Django ?? similar to the one in the image, only that there would be neighborhoods as well. I'm trying to work with Geoip, but if you can give me options or tell me how to do it, I appreciate it. illustrative picture: https://scontent.fsdu25-1.fna.fbcdn.net/v/t1.6435-9/183553513_4055413947881958_3475192236908351315_n.jpg?_nc_cat=105&ccb=1-3&_nc_sid=825194&_nc_eui2=AeFgw7TrSMCgZIbSrqxk-PjUYUpfRPtoIc5hSl9E-2ghzjE7o86qkRcdtvD4nUt8R-qpnaMPg0aZvKibC_GYvbvV&_nc_ohc=tUx8l-Ik2SUAX-ngCCN&_nc_ht=scontent.fsdu25-1.fna&oh=2f5067c53372bc5503360b8e367dcd06&oe=60C1AB96 -
Ajax send GET, instead of PUT and DELETE with Django backend
I have two custom form in HTML: -first needs to UPDATE first model -second needs to UPDATE or DELETE second model Page screenshot with forms Page loads via link.../personal/<staff_id>/' I have following code for buttons in second form: url for buttons: var updateUrl = '../personal/change/{{ profile.user.id }}/' Blue button with name Изменить and id="change": $("#change").on("click", function (event) { var form = $('#form-profile'); $.ajax({ ... }); }); Red button with name Удалить and id="delete: $("#delete").on("click", function (event) { var form = $('#form-profile'); $.ajax({ ... }); }); When pressing to buttons, page reloads with all form data in url personal/<staff_id>?csrfmiddlewaretoken=C5UPpOHIg2LJLbAIJpZHJosBK6Zma7BZjWC9s5TaLRZdlGOCJGsUMq T13MbO0wI2&profile_pic=&first_name=Name+3&last_name=Surname+3&email=&phone=&website=&role=методист&description=&delete= Ajax should have been sent PUT or DELETE request, instead it sends GET request with all parameters. I tested on postman, Django perfoms as needed. If DELETE was sent marks User as deleted and returns User. If PUT just updates User and returns updated User What am I doing wrong? <!DOCTYPE html> <html lang="ru"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js" integrity="sha512-LGXaggshOkD/at6PFNcp2V2unf9LzFq6LE+sChH7ceMTDP0g2kn6Vxwgg7wkPP7AAtX+lmPqPdxB47A0Nz0cMQ==" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <link type="text/css" rel="stylesheet" href="/static/bootstrap/css/bootstrap.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" /> <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js" integrity="sha384-tzzSw1/Vo+0N5UhStP3bvwWPq+uvzCMfrN1fEFe+xBmv1C/AtVX5K0uZtmcHitFZ" crossorigin="anonymous"></script> <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY" crossorigin="anonymous"></script> <link type="text/css" rel="stylesheet" href="/static/css/main.css"> <link type="text/x-scss" … -
More than one template render from one view in Django
I have a view that has some raw queries and I need to use these queries on more than one html page (template). How can I render the context of the view to two templates? -- I know it is better to use generic view to this view but it's not important now. -- views.py def results(request,user_name_id): # VEZETŐI TESZT vezetoi_hatekonysag = Vezetoi.objects.raw(...) vezetoi_iranyito = Vezetoi.objects.raw(...) vezetoi_motivalo = Vezetoi.objects.raw(...) vezetoi_tamogato = Vezetoi.objects.raw(...) vezetoi_delegalo = Vezetoi.objects.raw(...) # VISELKEDÉSTÍPUS TESZT viselkedes_iranyito = Vezetoi.objects.raw(...) viselkedes_inspiralo = Vezetoi.objects.raw(...) viselkedes_tamogato = Vezetoi.objects.raw('...) viselkedes_elemzo = Vezetoi.objects.raw(...) context = { # VEZETŐIKOMPETENCIA ÉS HATÉKNYSÁG 'vezetoi_hatekonysag': vezetoi_hatekonysag, 'vezetoi_iranyito': vezetoi_iranyito, 'vezetoi_motivalo': vezetoi_motivalo, 'vezetoi_tamogato': vezetoi_tamogato, 'vezetoi_delegalo': vezetoi_delegalo, # VISELKEDÉSTÍPUS 'viselkedes_iranyito': viselkedes_iranyito, 'viselkedes_inspiralo': viselkedes_inspiralo, 'viselkedes_tamogato': viselkedes_tamogato, 'viselkedes_elemzo': viselkedes_elemzo, } return render(request, 'stressz/all_user.html', context) -
Django + Ajax grabbing/posting ForeignKey data
I'm pretty new when it comes to working with Ajax, and having some difficulty bringing a ForeignKey into a POST request to send some form data. To start off I have an Add Note button, followed by an empty modal which will hold the form data, and also an empty input field which holds the ForeignKey ID I need to grab. <div class="container-fluid main-container"> <div class="text-center"> <button type="button" class="btn btn-danger js-create">Add Note</button> </div> </div> <div class="modal fade" id="modal-event"> <input type="hidden" id="eventID" name="event_id" value="{{ event_id }}"> <div class="modal-dialog"> <div class="modal-content"> </div> </div> The Add Note button calls a JS function here that opens the modal with the form... $(".js-create").click(function () { let event_id = $("input[name='event_id']").val(); // Prints out the correct event ID that I need console.log(event_id); $.ajax({ url: '/event/add-note/', type: 'get', data: {'event_id': event_id}, dataType: 'json', beforeSend: function () { $("#modal-event").modal("show"); }, success: function (data) { $("#modal-event .modal-content").html(data.html_form); } }); }); }); And then the on submit functionality to post the form data. $("#modal-event").on("submit", ".js-create", function () { let event_id = $("input[name='event_id']").val(); let form = $(this); $.ajax({ url: form.attr("action"), data: {'event_id': event_id}, type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { alert("Note created!"); } else { $("#modal-event .modal-content").html(data.html_form); } … -
Django - update database item if exists or insert if not exists
I want to update item quantity in a database or add to inventory if the UPC doesn't already exist. I am not sure how to write the logic. Here's what I have so far: My view: from django.contrib.auth.decorators import login_required from .forms import AuditItemForm from .models import AuditItem import datetime @login_required def audit_inventory(request): form = AuditItemForm(request.POST or None) if form.is_valid(): form.save(commit=False) form_upc = form.cleaned_data.get('upc') qty = form.cleaned_data.get('qty') for instance in AuditItem.objects.all(): if instance.upc == form_upc: instance.qty += qty instance.user = str(request.user) instance.last_updated = datetime.datetime.now() instance.save() elif instance.upc != form_upc: form.save(commit=True) return redirect('/audit') context = { "form": form, "title": "Audit Inventory", } return render(request, "audit.html", context) What's wrong with my logic? It updates an item correctly but it doesn't allow me to add a new item that doesn't already exist. -
Pass django model query as json response
I'm working on a social network. I want to load the comments of each post so I make an API call to the server to fetch all the comments of the required posts. The code will make everything clear: urls.py path("comments/<int:post_id>", views.load_comments) models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') commented_by = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.CharField(max_length=128) views.py def load_comments(request, post_id): """Returns the comments to index.js""" try: # Filter comments returned based on post id post = Post.objects.get(pk=post_id) comments = list(Comment.objects.filter(post=post).values()) return JsonResponse({"comments": comments}) except: return JsonResponse({"error": "Post not found", "status": 404}) index.js fetch(`/comments/${post_id}`) .then(res => res.json()) .then(res => { // Appoints the number of comments in the Modal title document.querySelector("#exampleModalLongTitle").textContent = `${res.comments.length} Comments`; res.comments.forEach(comment => { modal_body = document.querySelector(".modal-body") b = document.createElement("b"); span = document.createElement("span"); br = document.createElement("br"); span.classList.add("gray") b.textContent = comment.commented_by_id + " "; span.textContent = comment.comment; modal_body.appendChild(b); modal_body.appendChild(span); modal_body.appendChild(br); }) I can get the comment value using comment.comment in js. However, the problem arises when I convert the comments objects to list.values so now I lose the ability to get the user who posted the comment (commented_by) Any help to get the comment and commented_by values is appreciated. I also tried in views.py: def load_comments(request, post_id): """Returns … -
Django - IIS deployment - scriptProcessor could not be found
I have been trying to deploy django application using IIS but after following all the steps i am getting below error <handler> scriptProcessor could not be found in <fastCGI> application configuration I understand this error is due to incorrect path of scriptprocessor value, but value mentioned is correct. Please see below screenshot Screenshot of wfastcgi-enable Applied configuration changes to section "system.webServer/fastCgi" for "MACHINE/WEBROOT/APPHOST" at configuration commit path "MACHINE/WEBROOT/APPHOST" ""c:\program files\python39\python.exe"|"c:\program files\python39\lib\site-packages\wfastcgi.py"" can now be used as a FastCGI script processor Below is the value set in web.config file in wwwroot folder <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\program files\python39\python.exe|c:\program files\python39\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> Can somebody help why i am facing this error. -
Designing Postgresql table with multiple foreign key candidates
When designing a table with 2 or more possible candidates for reference/foreignkey how should this be achieved? Say we have the following: Table Trigger { ... - condition1 [FK: BookSales or BookPrice] - operation1 [enum: and, or, not..] - condition2 [FK: BookSales or BookPrice] - operation2 [enum: and, or, not..] - condition3 [FK: BookSales or BookPrice] } Now the the tables BookSalesand BookPricedon't have exactly the same fields and should be reusable for different triggers. One idea would be to create a table such as: Table BookPriceOrSale { ... - cType [enum: Price, Sales] <fields for BookPrice> <fields for BookSales> } And simply evaluating it based on cType with it as FK: condition1 [FK: BookPriceOrSale]. Another option is of course creating an intermediary table that has the foreignkey for one and null for the other -- this however adds another table compared to the one above which eliminated one, but added additional columns. Table TriggerCondition { ... priceCondition [FK: BookPrice] SalesCondition [FK: SalesPrice] } Here we instead reference it as condition1 [FK: TriggerCondition] A third option I can imagine is using inheritance, but I am not too sure about this.. My immediate thoughts would suggest using option 2 for correctness, … -
Deleting Table Entry In Django
So I have a table that looks like this: And I'm trying to make it so that the delete button deletes the entry from the form (and from the database as a whole). Attached below are my models and views. Model: from django.db import models from django.contrib.auth import get_user_model from django.contrib.auth.models import User class Plant(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="plant", null = True) name = models.CharField(max_length = 20) wateringInterval = models.PositiveSmallIntegerField() Views: from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Plant from .forms import AddNewPlant, RegisterForm def home(response): if response.method == "POST": form = AddNewPlant(response.POST) if form.is_valid(): tempName = form.cleaned_data["name"] waterInt = form.cleaned_data["wateringInterval"] p = Plant(name = tempName,wateringInterval = waterInt) p.save() response.user.plant.add(p) else: form = AddNewPlant() return render(response, "main/home.html", {"form":form,}) Also, the template: {% load crispy_forms_tags %} <div class = "main"> <table class="table table-striped"> <thead> <tr> <th scope="col">#</th> <th scope="col">Plant Name</th> <th scope="col">Water How Often?</th> <th scope="col">Next Watering</th> <th scope="col">Water</th> <th scope="col">Delete</th> </tr> </thead> <tbody> {% for plant in user.plant.all %} <tr> <th scope="row">{{forloop.counter}}</th> <td>{{plant.name}}</td> <td>{{plant.wateringInterval}}</td> <td>/</td> <td><input class="btn btn-primary" type="submit" value="Water"/></td> <td><button type="submit" name="delete" value="{{plant}}" class="btn btn-danger">Delete</button></td> </tr> {% endfor %} </tbody> </table> As seen in the template, I know it needs to be a … -
django fetching wrong datetime from database (inconsistent time on DateTimeField)
In the admin panel showing my correct date and time, but when I'm fetching that data there is getting the wrong time, but the date is correct. Please see this screenshot you will get my problem. [1]: https://i.imgur.com/I5DFV.jpg "screenshot" -
django Pass Search word from post field to URL
Good day, I need to send a string from an input field to a URL. my search engine is in Employees.views and it looks something like this. def search_in_employees(request, search): print(search) return render(request, "employees/employee_list.html") it's pretty simple. my URL looks like this. from django.urls import path, re_path from .import views app_name = 'employees' urlpatterns = [ path('create/', views.EmployeesCreateView.as_view(), name='create'), path('list/', views.EmployeesListView.as_view(), name='list'), path('update/<pk>/', views.EmployeesUpdateView.as_view(), name='update'), path('delete/<pk>/', views.EmployeesDeleteView.as_view(), name='delete'), path('update_db', views.UpdateDataBase.as_view(), name='update_db'), path('search/<search>', views.search_in_employees, name='search'), ] and the form in the template looks like this. <form action="{% url 'employees:search' %}" method="post"> {% csrf_token %} <div class="input-group"> <input type="text" class="form-control" name="search" placeholder="Search..." aria-label="Search"> <div class="input-group-append"> <input class="btn btn-primary btn-sm" type="submit" id="button-addon2"> </div> </div> </form> there is something wrong with the code but I just can find what is it. the error message it's this. thank you in advance for any help. best -
How to use pagination with modal view in django
I am diplaying a ListView with pagination in a modal view in django but when I click the link to the next page it closes the modal. I want to display the next result page inside that modal. Or close that modal and open a new one inside a new modal view How can I use pagination (show the next result page) inside that modal This is the modal <div class="modal-dialog modal-dialog-centered modal-lg" > <div class="modal-content"> <div class="wrapper wrapper-content {% block entry %} animated fadeInRight {% endblock entry %}"> <div class="row"> <div class="col-lg-12"> <h3>Trabajadores: {{ list_title }}</h3> <div class="col-12"> <div class=""> </div> </div> <div class="table-responsive"> <table class="table table-bordered table-hover" id="mydatatable"> <thead> <tr> <th class="text-navy" >Nombre</th> <th class="text-navy">Primer apellido</th> <th class="text-navy">Cédula</th> <th class="text-navy">Email</th> </tr> </thead> <tbody> {% for worker in workers %} <tr class="clickable" onclick="window.location='{% url 'riesgo:worker_detail' worker.id %}'"> <td> {{ worker.name }} </td> <td > {{ worker.last_name1 }} </td> <td > {{ worker.identification }} </td> <td > {{ worker.email }} </td> </tr> </tbody> {% empty %} <span style="color: red">{{ list_message }}</span> {% endfor %} </table> </div> <div class="pull-right"> <nav> <ul class="pagination"> {% if 'name' in request.get_full_path %} {% if has_previous_pages %} <li class="page-item"> <a class="page-link" href="{{ request.get_full_path }}&page={{ 1 }}" …