Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - returning raw bytes image from view
I have a view that returns an image (I'm aware that it might be a bad practice. But it's necessary in my case). Using normal Django HttpResponse I just return: # img is bytes response = HttpResponse(img, content_type="image/jpeg") response['Access-Control-Allow-Origin'] = '*' return response I want to use DRF since most of my views use it as well. I tried to just replace HttpResponse with Response but it crashed with 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Is there another way to do that? Should I even use DRF for returning this kind of data or should I stick to raw Django HttpResponse? One last thing, I have the same problem with other buffer types. E.g HttpResponse(content_type='text/csv') and response = HttpResponse(content=excel, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'inline; filename=filename.xlsx' return response Is there some general solution for these cases? -
Reverse for 'surveyanalysis' with arguments '('',)' not found. 1 pattern(s) tried: ['surveyanalysis/(?P<Survey_Question_No>[0-9]+)/$']
my html template looks like this: <a href="{% url 'SurveyAnalysis:surveyanalysis' Survey_Question_No %}">ANALYZE RESULTS</a><i class="fa fa-long-arrow-right" aria-hidden="true"></i> views.py look like this def surveyanalysis(request,Survey_Question_No): surveyresponse = get_object_or_404(SurveyResponseDetails, id=Survey_Question_No) # start working for Chart labels = [] #empty labels for storing labels data = [] #empty data for storing data default_data=[] #empty default_data for storing default_data default_labels=[] #empty default_labels for storing default_labels #filtering total Radio type Question Responses queryset = SurveyResponseDetails.objects.order_by('Survey_Question_Desc').values('Survey_Question_Answer').filter(Survey_Question_No=Survey_Question_No).annotate(Survey_Question_Desc_count=Count('Survey_Question_Desc')) for response in queryset: data = list(queryset.values_list('Survey_Question_Desc_count', flat=True)) labels = list(queryset.values_list('Survey_Question_Answer', flat=True)) return render(request, 'survey-analysis/surveyanalysis.html', { 'surveyresponse':surveyresponse 'labels': labels, 'data': data, }) my urls look like this from django.urls import path from django.conf.urls import url from django.contrib import admin from . import views from django.views import View app_name='SurveyAnalysis' from django.contrib.auth import views as auth_views urlpatterns = [ path('surveyanalysis/<int:Survey_Question_No>/', views.surveyanalysis, name='surveyanalysis'), path('question', views.surveyanalysis, name='question'), ] Usually I could easily read where the error is coming from and deal with it but in this case I can't spot the cause of the error hence I'm unable to progress with my study. Any help will be greatly appreciated. -
How to get username in a variable forms.py Django
So i am trying to fill in a model variable in from by default. I need the current logged in username in master_id = #here# i am not able to use request. Please help. from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from django.db import transaction from django.contrib.auth import get_user_model from .models import User, Shop class ShopRegister(UserCreationForm): first_name = forms.CharField(required = True) last_name = forms.CharField(required = True) firm = forms.CharField(required = True) email = forms.CharField(required = True) contact = forms.CharField(required = True) details = forms.CharField(required = True) lid = forms.CharField(required = True) master_id = #need my username here############## class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.employee = True user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.firm = self.cleaned_data.get('firm') user.email = self.cleaned_data.get('email') user.contact = self.cleaned_data.get('contact') user.details = self.cleaned_data.get('details') user.lid = self.cleaned_data.get('lid') user.save() shop = Shop.objects.create(user=user) shop.master_id=self.cleaned_data.get('master_id') shop.save() return user -
TypeError at /api/v1/usuarios
I'm new to python and Django. But I already have prior knowledge. I am making an application as a backend using django rest. But there was an error that I am unable to resolve. Just below I show the error. And the code is below too. If you can help me I would appreciate it. Thank you. urls.py path('usuarios', UserAPIView.as_view(), name='usuarios'), views.py class UserAPIView(APIView): """ API de usuario """ def get(self, request): usuarios = User.objects.all() serializer = UserSerializer(usuarios, many=True) return Response(serializer.data) serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['url', 'username', 'email'] -
My s3 images will not display on my django site
My web application is using django and s3. When I attempted to access my s3 images on AWS via the public bucket. Everything else works except for the simple secure storage (s3) bucket. I have this error: <Error> <style class="darkreader darkreader--safari-fallback">...</style> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>DAD37CB20E79C307</RequestId> <HostId> tuZqmK2Ei6dvMify2V2LoGmJxJ33UemNknXnH2DM4YzfqS3MNuvmLJJVq5SmUTr5976TkWpeHpc= </HostId> </Error> https://framann-quilting-place.s3.us-east-2.amazonaws.com/media/products/carousel/SewingKit.jpg -
Should I add my API NGINX sites-available config to the same file as my Django NGINX sites-available that will be used for production?
I made an API using postgREST, it's based off of my postgres database schema, and it connects to my database via a PRIVATE network. I only want the API to be used internally, only my servers should be able to access the API and present it to the client, I don't want to outside world to access it. Here is my NGINX file for my domain: /etc/nginx/sites-enabled/default server { listen 80; server_name SERVER_PUBLIC_IP_ADDRES; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /directory/to/django_webapp; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Below is an example of how postgREST advices users in their documentation to using NGINX. http { # ... # upstream configuration upstream postgrest { server localhost:3000; } # ... server { # ... # expose to the outside world location /api/ { default_type application/json; proxy_hide_header Content-Location; add_header Content-Location /api/$upstream_http_content_location; proxy_set_header Connection ""; proxy_http_version 1.1; proxy_pass http://postgrest/; } # ... } } As you can see in the code comment, it says expose to the outside world, Which I don't want to do. So then again, do I really need to add this portion of the code to my Django nginx? The API … -
How can i make customer chat option in a ecommerce website by django?
want backend end frontend html code Like this customer chat option https://i.stack.imgur.com/gaLEd.png -
Set default start page in Paginator Django
I have a list of projects. When I enter into details of one of them then I would like check others using next page. The problem I have is that it doesnt matter which one I click on I always start from the first page (first project) The documentation of Paginator class I found in django docs is very small and I would like to find the way to indicate which page display, ex. if I click on object with id=3 I should see <Page 3 of 8>. def project_detail(request, id): projects = Project.objects.all() paginator = Paginator(projects, 1) page = request.GET.get('page') project = paginator.get_page(page) return render(request, 'portfolio/projects/detail.html', 'project': project}) I woud like to implement this part of code inside: paginator.page(id) if it`s posible, but sincerly dont know how. -
django model forms how to use PK within the forms (forms.py)?
I want to do the following validation in a django model form: class BookUpdateModelForm(forms.modelForm): #[... a lot of stuff ...] def clean_title(self): title = self.cleaned_data.get("title") objectId = self.cleaned_data.get("id") if title in Book.objects.values_list('title', flat=True): book = Book.objects.get(title=title) if book.id != objectId: raise forms.ValidationError( "Este título ya esta tomado. Si requiere utilizarlo pongase en contacto con el administrador del sitio." ) return title Originally i was using this to try avoid repeated titles: class BookUpdateModelForm(forms.modelForm): def clean_title(self): title = self.cleaned_data.get("title") if title in Book.objects.values_list('title', flat=True): raise forms.ValidationError( "Este título ya esta tomado. Si requiere utilizarlo pongase en contacto con el administrador del sitio." ) return title But as you can guess the validation error poped up when i was trying to update the book model. Then i opted to Make 2 separated ModelForms, one to update and one to create. The first piece of code is from the update and is where i am finding my self in trouble. I can not access the id of the Object i am updating within the form. My template have the following lines: <!--auto select the current user to foreignkey in model--> <input type="hidden" name="user" value="{{user.id}}" id="my-id-user"> <!--auto select the current object to validate in … -
Postman and django rest framework (rest-auth)
postman drf I am reaching same url with drf and postman but fields are different.I don't understand why. (screenshots are under links postman and drf) -
can we write ORM queries without data?
from django.contrib.auth.models import User from django.db import models class CUser(User): score = models.IntegerField() The custom user has an additional field (“score”), we want to do the following operations using ORM queries only. Every answer must have a single query: Calculate the mean score of all users. Find the user with the highest score. Find if there is any user with score less than 2 (return True/False) Find all the users which have score exactly equal to the mean score. Change the score value of all users in a single query to 100 (one hundred) Find all the users which don't have score 10 or 20 Print a list of all the score values from all users excluding the first 10 users. Answers: 1. 2. 3. 4. 5. 6. 7. -
Cannot fix django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I run the following line of code on a dcker container: RUN python3 manage.py sitetree_resync_apps --settings=sites.production.settings and I get the following error: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/xxx/xxx/invoicing/apps.py", line 10, in <module> from xxx.site.signals import resource_event, notify_by_email File "/xxx/xxx/site/signals.py", line 12, in <module> from xxx.backend.email import send_email File "/xxx/xxx/backend/email.py", line 11, in <module> from post_office import mail File "/usr/local/lib/python3.6/site-packages/post_office/mail.py", line 13, in <module> from .models import Email, EmailTemplate, Log, PRIORITY, STATUS File "/usr/local/lib/python3.6/site-packages/post_office/models.py", line 27, in <module> class Email(models.Model): File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 136, in check_apps_ready … -
Django def_get logic in models.py not finding object
I am trying to save a field profit to the model ItemSold. I need to get purchase_price from the previous Item model in order to save profit in the def get_profit function in the ItemSold model (OneToOne with Item). The def_get_profit is in models.py because I am only using the Django admin dashboard at the moment to view / edit records. I am getting the DoesNotExist error which is obviously being caused by purchase_price = Item.objects.get(id=self.id).purchase_price as when I remove it, the function works. I'd be grateful if someone could help me understand why id=self.id isn't recognising the Item.object in question. models.py class Item(models.Model): name = models.CharField(max_length=200, null=True) purchase_price = models.FloatField(null=True) def __str__(self): return f'{self.name}' class ItemSold(models.Model): sold_price = models.FloatField(null=True) profit = models.FloatField(null=True, blank=True) item = models.OneToOneField(Item, on_delete=models.CASCADE) @property def get_profit(self): purchase_price = Item.objects.get(id=self.id).purchase_price sold_price = float(self.sold_price) fees = float((sold_price * 0.09) + (0.9)) profit = float(sold_price - purchase_price - fees) return profit def save(self, *args, **kwargs): self.profit = self.get_profit super(ItemSold, self).save(*args, **kwargs) def __float__(self): return self.profit def __str__(self): return f'{self.profit}' -
Como obtener la row de la tabla en hbase shell
Quiero obtener la row de cada uno de los datos que estan ingresados tiene la estructura que se muestra a continuacion ROW COLUMN+CELL 1 column=datos_personales:documento, timestamp=1604669916960, value=16646015 Hize este codigo que me trae la row pero solo me trae la 1, y necesita que dependiendo de cada uno me traiga sea la 1 o 2 o 3 no se que haya mal en la consulta, muchas gracias def obteneridAuth(request): table = database.connection.table('users') exist_user = table.scan(filter="SingleColumnValueFilter ('datos_personales','cedula',=,'regexstring:^"+request.user.username+"$')") id_user=next(exist_user)[0] return id_user -
ERROR: Command errored out with exit status 1: Python When Installing pyautogui and any other programs
WEll I Get and Error Like this ERROR: Command errored out with exit status 1: command: 'C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Pranzal\AppData\Local\Temp\pip-install-p6rubgaj\pyautogui\setup.py'"'"'; file='"'"'C:\Users\Pranzal\AppData\Local\Temp\pip-install-p6rubgaj\pyautogui\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Pranzal\AppData\Local\Temp\pip-pip-egg-info-s1_syjvk' cwd: C:\Users\Pranzal\AppData\Local\Temp\pip-install-p6rubgaj\pyautogui Complete output (28 lines): Traceback (most recent call last): File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\pkg_resources_init_.py", line 2848, in get_entry_map ep_map = self.ep_map File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\pkg_resources_init.py", line 2810, in getattr raise AttributeError(attr) AttributeError: _ep_map During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\Pranzal\AppData\Local\Temp\pip-install-p6rubgaj\pyautogui\setup.py", line 18, in <module> setup( File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\setuptools\__init__.py", line 152, in setup _install_setup_requires(attrs) File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\setuptools\__init__.py", line 142, in _install_setup_requires dist = MinimalDistribution(attrs) File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\setuptools\__init__.py", line 134, in __init__ distutils.core.Distribution.__init__(self, filtered) File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\setuptools\dist.py", line 421, in __init__ for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'): File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\pkg_resources\__init__.py", line 640, in <genexpr> for entry in dist.get_entry_map(group).values() File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\pkg_resources\__init__.py", line 2850, in get_entry_map ep_map = self._ep_map = EntryPoint.parse_map( File "C:\Users\Pranzal\AppData\Local\Programs\Python\Python39\lib\site-packages\pkg_resources\__init__.py", line 2535, in parse_map raise ValueError("Entry points must be listed in groups") ValueError: Entry points must be listed in groups ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Losing user authentication after logging from a different app in the same django project
In my django project, I have two applications, coachingapp and account. My purpose is to be able to login from the admin application successfully and be directed to the index page under the coachingapp as authenticated. I am using Django 3.1.3 My views.py in the admin app: from django.shortcuts import render, redirect from .forms import LoginForm from django.contrib.auth import login, logout from django.http import HttpResponseRedirect from django.contrib import messages from .models import User user = None def login_site(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): data = form.cleaned_data global user user = authenticate_user(data['your_email'], data['your_password']) if user is not None: login(request, user) result = {'form': form} return HttpResponseRedirect("/", result) else: result = {'form': form} messages.error(request, 'incorrect email or password') else: result = {'form': form} messages.error(request, 'Your input seems invalid!') else: form = LoginForm() result = {'form': form} return render(request, "account/login.html", result) def authenticate_user(email, password): try: user = User.objects.get(email=email) except User.DoesNotExist: return None else: if user.check_password(password): return user return None Here is my views.py in the coachingapp: from __future__ import unicode_literals from django.http import JsonResponse from django.shortcuts import render from django.http import HttpResponseRedirect def index(request): if request.user.is_authenticated: return render(request, "coachingapp/index.html", {}) else: return HttpResponseRedirect("account/login_site") I am successfully authenticating in the … -
How to add an input integer to update the model field through form?
I have a model that holds an inventory value. I want to be able to add any integer value to that model field. It doesn't throw any errors but I get unexpected results when I post. For some reason I do not understand, the code is multiplying the number entered in the form by 2 and setting the result as the new inventory number. I have tried using both forms.Form and ModelForm for my form. The form I am using is also used to update the Panel description, so the text area for the description is pre-populated with the current Panel description. For example, if I have an inventory of 80 and I enter 3 in the input field and POST, the new inventory will be 6. That is obviously not what I expect to happen, I would like it to POST and make the new inventory 83. Models.py class Panel(models.Model): name = models.CharField('Name', max_length=50, default='') slug = models.SlugField(unique=True) description = models.TextField('Description', null=True, blank=True) date_created = models.DateTimeField('Date Created', auto_now_add=True, null=True) display = models.BooleanField(default=True) image = models.ImageField('Panel Image', null=True, blank=True) inventory = models.IntegerField('Inventory', null=True, default=0) def get_absolute_url(self): return reverse("model_detail", kwargs={"pk": self.pk}) def __str__(self): return f'{self.name}' def save(self, *args, **kwargs): if not … -
alpine.js pagination limit the pages
i have an array of numbers (from search results) and then the code for pagination. I want only the first 3 pages to be visible, but if i click on the 3 page, i want that the next page is visible and so on .... <template x-for="(page,index) in pages()" :key="index"> <button class="px-3 py-2 rounded focus:outline-none" :class="{ 'text-primary-500 border border-primary-500 text-white font-bold' : index === pageNumber, 'hidden' : index > visiblePages }" type="button" x-on:click="viewPage(index)"> <span x-text="index+1"></span> </button> </template> it is working, with the next button, i can go to page 4,6,7 etc. but in the pagination there is only standing 1,2,3. For me it's clear, because i set the class to hidden if the index is greater then 3. But i don't know how to change that if i click on next button AND the index is greater then 3 that there is standing 4, then 5, then 6 and so on. I hope you understand what i mean :) I took the code from: Alpine Toolbox but with this code the problem is, that if i have for example 100 Pages, there will be 1,2,3....100 pagination numbers and i don't want this. thanks for helping Greets Martin -
Access API key in javascript from django settings.py
I am trying to pass an API key for google places from my settings.py file to a JS script. Should I expect to be able to access the variable in the JS script this way, or is there a better approach? # settings.py api_key = 123456HYTYTY # views.py args['api_key'] = settings.api_key return render(request, 'template_example.html', args) # template.html {% block js %} <script src="https://maps.googleapis.com/maps/api/js?key={{ api_key }}&libraries=places" defer></script> {% endblock js %} -
Tip for optimization in signal processing
I have two task models and activities, what I am doing is that every time the user puts the process in the activities model in true, a count is made, what I want to do, it does it in the correct way and it is as I expect, but I feel that the solution I have is not the most optimal, I would like to know if there is any way to do what I have in a more optimal way. This my model: class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) type_task = models.ForeignKey(TypeTask, on_delete=models.CASCADE) task = models.CharField(max_length=50) description = models.TextField() state = models.BooleanField(default=False) porcentage = models.IntegerField(default=0) slug = models.SlugField(max_length=60, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.task class Activities(models.Model): name = models.CharField(max_length=50) process = models.BooleanField(default=False) task = models.ForeignKey(Task, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name This is my signal: @receiver(post_save, sender=Activities) def calculate_porcentage(sender, instance, *args, **kwargs): tasks = Task.objects.all() for task in tasks: activities = Activities.objects.filter(task=task).count() completed = Activities.objects.filter( task=task).filter(process=True).count() porcentage = (completed * 100) // activities instance.porcentage = porcentage -
Django django.core.files.File(file-like object) returns File('None')
I have a io.BytesIO object that I want to convert to a valid Django File object. My code is simple: ret_file = File(file_object) (Pdb) ret_file <File: None> (Pdb) file_object <_io.BytesIO object at 0x7ab3fa1d51d0> I can't figure out how to get this object as a valid File. Any help would be much appreciated. Thank you in advance -
Using Django-MPTT in Django-Filters to get children on filtering parent node
I have an MPTT model class, and want to use it in Django-Filter. My MPTT model is; class ProdCategory(MPTTModel): name = models.CharField(max_length=200, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') slug = AutoSlugField(populate_from='name',slugify=slugify) class MPTTMeta: order_insertion_by = ['name'] def __str__(self): return self.name The class is used as a foreign key in another "deal" model class as 'productCategory' My filter class in filters.py is: class DealFilter(django_filters.FilterSet): class Meta: model = deal fields = ['store', 'productCategory'] Finally, my view is: def filterdeals(request): deals = deal.objects.all() myFilter = DealFilter(request.GET, queryset = deals) deals = myFilter.qs args = { "deals": deals, "myFilter":myFilter,} return render(request, 'deals/filter.html', args) Now, since in MPTT, I want all the children selected on filtering the parent, I want to include this code for the same: deal.objects.filter(productCategory__in=ProdCategory.objects.get(pk=2).get_descendants(include_self=True)) But I don't know where to include this code- so that when the parent category ID is passed, I get all the children under it. TIA for your help -
Serving gzip content from Django TemapleView
I am using TemplateView to render my pages. Recently I started using webpack to compress my js files into a gzip format. I now want to modify my Template view to render the gzip file. Currently I'm setting the TemplateView's component field to <my_component>.js and I want to change it to <my_component>.js.gz. For that I need to set up the content-encoding header param of the response to 'gzip'. Is there a way to do it somehow in the TemplateView class? I dont want to change the class because I dont really want to deal with the HttpResponse builerplate. -
Configure batabase for production/project managment
My ultimate goal is to create a Django based (so with Python) web application to handle production activities (at work). In other word, something similar to project managment app, with different task for each project etc. But, before thinking about Django "world", I was thinking about how to define the underlying database. First of all let me explain what I mean. Let's assume that I have to produce object OBJ1. To do that I have to complete a certain number of tasks, say TSK1, TSK2,TSK3. The same for OBJ2, OBJ3 and so on... So, each "Object" has its own (different from object to object) sequence of tasks, with their own duration. Now I may have to produce 5 pieces for OBJ1, 40 for OBJ2, and so on, and every "instance" of OBJx could have different delivery date (tasks have different duration, from 1 hour to 7 days for example, it depends). I'd like to be able (at the end of the project) to add every OBJs to a page where I can update the tasks status, to control the progress and check for delay and so on. At the end... I'd like to be able to "handle": different project (obj) … -
Django Crispy Forms - Display List of Dictionaries
Take the following list of dictionaries as an example: {"host": "test-01", "service": "tomcat"}, {"host": "test-02", "service": "tomcat"}, {"host": "test-03", "service": "tomcat"}, {"host": "test-04", "service": "tomcat"}, {"host": "test-05", "service": "postgres"}, {"host": "test-06", "service": "tomcat"}, {"host": "test-07", "service": "tomcat"}] I essentially want to create a HTML message for each dictionary saying what service is going to be restarted on what server. However, I'm not sure what the best way of going about this is. I've tried the below to no avail: views.py def restart_es_services_confirm(request): systems = [{"host": "test-01", "service": "tomcat"}, {"host": "test-02", "service": "tomcat"}] form = ServicesConfirm(request=request) if request.method == 'POST': return HttpResponseRedirect('restart_services.html') else: form = ServicesConfirm(request=request) return render(request, 'restart_services_confirm.html', {'form': form}, {'systems': systems}) restart_services.py class ServicesConfirm(forms.Form): reconfirm = forms.BooleanField(required=True, label='I confirm these services can safely be restarted.',widget=forms.CheckboxInput(attrs={})) def __init__(self, *args, **kwargs): request = kwargs.pop("request") super().__init__(*args, **kwargs) systems = request.session['systems'] for system in systems: host = system['host'] service = system['service'] message = ("Restart " + service + " on " + host) self.helper = FormHelper() self.helper.add_input(Button('cancel', 'Cancel', css_class='button button--wide button--black', formvalidate='formnovalidate', onclick="window.location.href = '{}';".format(reverse('home')))) self.helper.add_input(Submit('deploy', 'Deploy', css_class='button button--wide button--white')) self.helper.form_method='POST' self.helper.layout = Layout( Fieldset( 'Confirmation', Row( Column('reconfirm', css_class='form-group col-md-14 mb-0') ) ) ) restart_services_confirm.html: <!doctype html> <html lang="en"> {% load static %} …