Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting the field value of a form in view.py
My django website would like to allow logged in users to post a recipe. The recipe model is linked to the user model and as such requires a valid user instance. I would like the Recipe form to automatically assign the postedby field to the instance of the logged in user. So far I have attempted to pass in a dictionary, storing the user's name, to the form instance. as shown in the view However, the constructor method is not receiving the data and is rendering the form but with a failed attempt to submit. I cannot store the data without postedby field having a valid instance as the model throws the following error: Exception Value:UserProfile matching query does not exist. I have also tried to do the following in views.py; @login_required def add_recipe(request): form = RecipeForm() form.fields['postedby'] = UserProfile.objects.get(user=User.objects.get(username=request.user.__str__())) context_dict = {'form':form} if request.method == 'POST': ... However this overwrites the postedby form view to be rendered and raises and error. views.py @login_required def add_recipe(request): form = RecipeForm({'user':request.user}) context_dict = {} #print(form.fields['postedby'].queryset) if request.method == 'POST': form = RecipeForm(request.POST) if form.is_valid(): form.save(commit=True) return redirect(reverse('spatula:index')) else: print(form.errors) context_dict['form'] = form return render(request, 'spatula/add_recipe.html', context=context_dict) The RecipeForm is as follows: class … -
ModelChoiceField always raises : “Select a valid choice. That choice is not one of the available choices”
In forms I have multiple dependent choice fields. but I am getting same error for all the dependent choice fields i tried but it wont come please help me.I am fresher. forms.py class IssuecreateForm(forms.ModelForm): def __init__(self,*args, **kwargs,): self.projects = kwargs.pop("projects",None) # self.issues = kwargs.pop("issues",None) # self.rootcause = kwargs.pop("rootcause",None) super(IssuecreateForm, self).__init__(*args, **kwargs) self.fields['SUMMARY'].widget.attrs.update({'class' : 'form-control','placeholder': 'Enter Summary'}) self.fields['SUMMARY'].label='Summary' self.fields['DESCRIPTION'].widget.attrs.update({'class' : 'form-control mb-4','placeholder': 'Enter Description'},required=False) self.fields['DESCRIPTION'].label='Description' self.fields['ENVIRONMENT'].widget.attrs.update({'class' : 'form-control mb-4','placeholder': 'Enter Description'},required=False) self.fields['ENVIRONMENT'].label='Environment' self.fields['PROJECT'].queryset = self.projects self.fields['LINKED_ISSUES'].choices = [(x.ID, x.SUMMARY) for x in Issues.objects.all()] LABELS =forms.MultipleChoiceField(widget=forms.Select({'class': 'lable-select', 'name':"lable-select", "multiple":"multiple"}), choices=OPTIONS,required=False) CREATED_DATE_TIME=forms.DateTimeField(initial=datetime.datetime.today(),required=False) PROJECT = MyModelChoiceField(queryset=Project.objects.all(),widget=CustomSelectOption(attrs={'class':'mt-2'})) PRIORITY = MyModelChoiceField(queryset=Priority.objects.none(),widget=CustomSelectOption(attrs={'class':'mt-2','name':'issue-types'})) TYPE = MyModelChoiceField(queryset=IssueType.objects.none(),widget=CustomSelectOption(attrs={'class':'mt-2'})) LINKED_ISSUE_TYPES = ModelChoiceField(queryset=LinkedIssueType.objects.none(), empty_label='----------Select Linked Issue Type---------') # STATUS = ModelChoiceField(queryset=IssueStatus.objects.none(), empty_label='----------Select Status---------') RESOLUTIONS = ModelChoiceField(queryset=Resolution.objects.none(),required=False, empty_label='----------Select Resolution---------') ROOT_CAUSES = ModelChoiceField(queryset=RootCause.objects.none(),required=False, empty_label='----------Select Rootcause---------') PROCESS_AREAS = ModelChoiceField(queryset=ProcessArea.objects.none(),required=False, empty_label='----------Select Process Area---------') FUNCTIONAL_AREAS = ModelChoiceField(queryset=FunctionalArea.objects.none(),required=False, empty_label='----------Select Functional Area---------') # DEFECT_TYPE = ModelChoiceField(queryset=DefectType.objects.none(), empty_label='----------Select Defect Type---------') ASSIGNEE = MyModelChoiceField(queryset= PmUser.objects.none(),widget=CustomSelectOption(attrs={'class':'mt-2'}),required=False) REPORTER = MyModelChoiceField(queryset= PmUser.objects.none(),widget=CustomSelectOption(attrs={'class':'mt-2'}),required=False) SPRINTS = ModelChoiceField(queryset=Sprint.objects.none(),required=False, empty_label='----------Select Sprint---------') LINKED_ISSUES = forms.MultipleChoiceField(widget=forms.Select({"class":"issue-list", "name":"issue-list", "multiple":"multiple"}),choices = [],required=False) # EPIC_LINK = forms.MultipleChoiceField(widget=forms.Select({"class":"issue-list", "name":"issue-list"}),choices = []) DURATION_CHOICES=forms.ChoiceField(widget=forms.RadioSelect(attrs={'placeholder': 'METHOD_TYPE','class':'myclass'}),required=False,choices=DURATION_CHOICES) class Meta: model = Issues fields ='__all__' exclude=['CREATOR','UPDATOR','CREATED_DATE_TIME','UPDATED_DATE_TIME','EPIC_LINK','WATCHER','PARENT','LINKED_ISSUES','ORDER','SERIAL_NUMBER','COLOR','DEFECT_TYPE','STATUS','EPIC_NAME'] widgets = { 'START_DATE': DateInput(), 'DUE_DATE': DateInput(), 'ESTIMATION_TIME': DurationInput(), } -
Django models foreignkey default value
There was no manager in the posts I created before. When I add the manager, I want the default value or I am asked to enter it manually. When I enter 'None' I get an error like this; django.db.utils.IntegrityError: NOT NULL constraint failed: new__Core_post.manager_id I cannot export PostManager as the default value. Is there another way or another solution to give? class User(models.Model): #... posts = models.ManyToManyField('Post', blank=True) class Post(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) #... manager = models.ForeignKey('PostManager', on_delete=models.CASCADE) class PostManager(models.Model): #... Sorry for my bad english. -
Obtain all the columns from my model in django
I want to obtain all the info from one table of my database in django, I'm doing this, from django.shortcuts import render # Create your views here. from Platform_App.models import fleets def list_fleets(request): fleet = fleets.objects.all() return render(request, template_name='fleets.html', context={'Fleet':fleet}) But it shows an error in the line below, concretely in fleets. fleet = fleets.objects.all() It says, class fleets has no objects member My model is the following: class fleets(models.Model): fleet_id = models.IntegerField(primary_key=True) fleet_name = models.CharField(max_length=20) description = models.CharField(max_length=40, blank=True, null=True) If fleet = fleets.objects.all() is not correct, how I have to do it to take all the columns of my table?? Probably a easy question, but I'm newbie. Thank you very much!!!! -
Can't connect to website with LetsEncrypt certificate - nginx
I'd like to add ssl certificate to my django app. I've followed tutorial so the nginx config for domain was changed but now it looks like generated certificate is incorrect. nginx conf before certbot modifications server { listen 80; listen [::]:80; server_name doamin.com www.domain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/poul3r/doamin.com; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } and after certbot action server { server_name doamin.com www.doamin.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/poul3r/doamin.com; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/doamin.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/doamin.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = doamin.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; listen [::]:80; server_name doamin.com www.doamin.com; return 404; # managed by Certbot } What I'm doing wrong or what could went wrong during letsencypt implementation ? -
Importing a JS file on Django
I created a simple file called main.js. In this file, i defined a function: function hello(){ console.log('hello') } Now i'm trying to import the file on a template and call the function from there. Here is what i tried: <script type="text/javascript" charset="{% static 'main.js' %}"> hello() </script> But this is giving me the following error: Uncaught ReferenceError: hello is not defined Why is this happening? Am i not importing the file? This is where main.js is located: static -> main.js And here is how my static directory is defined on Django: STATIC_URL = '/static/' My static directory contains a lot of other files and i'm not having problems with those; can someone help me find what i'm doing wrong with this one? Every advice is appreciated -
How to get only one object from ManyToOne table, instead of queryset?
Table Images: id| image | item_id 15|some/path| 45 16|some/path| 45 17|some/path| 45 First try: recommended_items = Item.objects.all().filter(rating__gte=9) // All my items (`item_id` column) for item in recommended_items : image = Images.objects.get(item=item.id)[:1] It works for first item with id=45 but for the rest it returns error: Images matching query does not exist. Second try: for item in recommended_items : image = Images.objects.filter(item=item)[:1] Now it works for all items, existing or not, but it returns iterate object and I should add for loop for just one object, like this: for i in image: print(i.image) What is the right way to handle this ? I want just one record (the last one if it is possible) -
Why am I getting this error while typing the command- makemigrations
from django.db import models # Create your models here. class Products(models.Model): title = models.TextField() description = models.TextField() price = models.TextField() I don't know why I get this error: Traceback (most recent call last): File "Blank/manage.py", line 21, in main() File "Blank/manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\lenovo\PycharmProjects\Django\venv\lib\site-packages\django\core\management__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\lenovo\PycharmProjects\Django\venv\lib\site-packages\django\core\management__init__.py", line 377, in execute django.setup() File "C:\Users\lenovo\PycharmProjects\Django\venv\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\lenovo\PycharmProjects\Django\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\lenovo\PycharmProjects\Django\venv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\lenovo\AppData\Local\Programs\Python\Python37-32\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'products' -
DRF: how to change the value of the model fields before saving to the database
If I need to change some fields values before saving to database as I think models method clear() is suitable. But I can't call him despite all my efforts. For example fields email I need set to lowercase and fields nda I need set as null models.py class Vendors(models.Model): nda = models.DateField(blank=True, null=True) parent = models.OneToOneField('Vendors', models.DO_NOTHING, blank=True, null=True) def clean(self): if self.nda == "": self.nda = None class VendorContacts(models.Model): .... vendor = models.ForeignKey('Vendors', related_name='contacts', on_delete=models.CASCADE) email = models.CharField(max_length=80, blank=True, null=True, unique=True) def clean(self): if self.email: self.email = self.email.lower() serializer.py class VendorContactSerializer(serializers.ModelSerializer): class Meta: model = VendorContacts fields = ( ... 'email',) class VendorsSerializer(serializers.ModelSerializer): contacts = VendorContactSerializer(many=True) class Meta: model = Vendors fields = (... 'nda', 'contacts', ) def create(self, validated_data): contact_data = validated_data.pop('contacts') vendor = Vendors.objects.create(**validated_data) for data in contact_data: VendorContacts.objects.create(vendor=vendor, **data) return vendor views.py class VendorsCreateView(APIView): """Create new vendor instances from form""" permission_classes = (permissions.AllowAny,) serializer_class = VendorsSerializer def post(self, request, *args, **kwargs): serializer = VendorsSerializer(data=request.data) try: serializer.is_valid(raise_exception=True) serializer.save() except ValidationError: return Response({"errors": (serializer.errors,)}, status=status.HTTP_400_BAD_REQUEST) else: return Response(request.data, status=status.HTTP_200_OK) As I learned from the documentation Django Rest Framework serializers do not call the Model.clean when validating model serializers In dealing with this problem, I found two ways to … -
Django increasing value in database on update
i have table for inventory where is Qty column, i will like to add Qty using form to sum new value with already existed in database my class based view in views.py looks like : class ItemUpdateView(LoginRequiredMixin, UpdateView): model = Stock template_name = 'users/item_update_form.html' fields = ['qty'] right now im getting this output : screenshot from page view i will like to have empty Qty Field to type new value and after pressing Add increase value already existing in database with this new value -
Django Choice Field similar as in Admin (Permissions)
Unfortunately we have some really long drop down lists for our users to choose from and the way the django admin implemented their permissions ui really looks like a good solution for this, but for the life of me I can't find any examples how to implement something similar? Does anyone has any tipps? (I currently use "Select2MultipleWidget" to at least make it somewhat manageable) -
NOT NULL constraint failed: complaint_complaint.resident_id
I am writing an app in which people can submit their complaints related to some issues. After the form is submitted, it is supposed to redirect to the page where the details of the complaint are mentioned like area of the complaint, title, description etc. But after the form is submitted, it throws IntegrityError. I read about it and went through some of the solutions: Someone suggested that I delete some past migrations and run them again. I cleared the migrations, ran them again and made some posts through the admin but it is throwing the same error. Some posts suggest that null=True, blank=True should be added but I do not understand where they should be added in my case. I also don't want to add null=True, blank=True because I don't want any field to be left blank. Below is my models.py: from django.db import models from django.urls import reverse # Create your models here. class Complaint(models.Model): """ Details of the complaint """ resident = models.ForeignKey('auth.User', on_delete=models.CASCADE) AREA = [('PL', 'Plumbing'), ('EL', 'Electricity'), ('CP', 'Carpenter'), ('CO', 'Construction'), ('DS', 'Disputes'), ('OT', 'Other'),] matter = models.CharField(max_length=2, choices=AREA) title = models.CharField(max_length=200) text = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): … -
How to sent images through django sendmail
I'm trying to send images in a letter, but it doesn’t work out for me. I tuned {{ STATIC_URL }} but it did not help... How i can fix this? In settings: STATIC_URL = 'http://10.0.50.42:8103/static/' In HTML: <img src="{{ STATIC_URL }}dc/images/banner2.png"> With this setting, I started to receive a letter, but the images are not displayed there. -
Email sent from Django is not received
I have a website where I would like users to contact us if they need it. Thus, I wrote this views def contact(request): submitted = False if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): mail=request.POST.get('email') subject=request.POST.get('objet') msg=request.POST.get('message') send_mail(subject, msg, settings.EMAIL_HOST_USER,['med.abdillah@massiwatechnology.com'],fail_silently=False) return HttpResponseRedirect('/contact?submitted=True') else: form = ContactForm() if 'submitted' in request.GET: submitted = True return render(request, 'contact.html', {'form': form, 'submitted': submitted}) This views is based on the form bellow: class ContactForm(forms.Form): # nom_complet=forms.CharField(max_length=100, required=True) email=forms.EmailField(required=True) objet=forms.CharField(widget=forms.Textarea( attrs={ "rows":1, "cols":80 } )) message=forms.CharField( widget=forms.Textarea( attrs={ "class":"message two", "rows":5,"cols":80 } ) ) In my settings.py file I did the configurations bellow: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST='mail.massiwatechnology.com' EMAIL_PORT='465' EMAIL_HOST_USER='med.abdillah@massiwatechnology.com' EMAIL_USE_TLS=True # EMAIL_USE_SSL=False EMAIL_HOST_PASSWORD='mypassword' [ But I am no receiving any message in this email: med.abdillah@massiwatechnology.com. Is there any configurations mistakes, please? -
Django LoginView authenticate User
Good day. I'm trying to authenticate a user through a custom LoginView I can't understand how it works, whenever i try to authenticate, all it does is react on GET request. When i send a POST request it does nothing with it. I've overriden def post(self, request, args, kwargs) all i get are some strange errors. It doesn't react to form_valid either.. What can i do here? urls.py path('user/login/', CustomLoginView.as_view(), name='login'), forms.py class LoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(args, kwargs) username = forms.EmailField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Email address', 'type': 'email', 'id': 'inputEmail'} ), label='') password = forms.CharField(widget=forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Password', 'type': 'password', 'id': 'inputPassword'} ), label='') views.py class CustomLoginView(LoginView): authentication_form = LoginForm def get(self, request, *args, **kwargs): if self.request.user.is_authenticated: return super(CustomLoginView, self).redirect_authenticated_user return super(CustomLoginView, self).get(request, *args, **kwargs) def form_valid(self, form): super(CustomLoginView, self).form_valid(form) # data = form.cleaned_data # email = data['username'] # password = data['password'] # authenticate(self.request, username=email, password=password) # def post(self, request, *args, **kwargs): # form = LoginForm(self.request.POST) # self.form_valid(form) # cd = form.clean() # email = request.user.email # email = cd['email'] # password = cd['password'] # user = authenticate(request, email=email, password=password) # if user is not None: # login(request, user) # return redirect(self.get_success_url()) # return super(CustomLoginView, self).form_valid(form) … -
Using include to import all the urls from my django app
I'm learning Django and I think I'm following an old tutorial. What I'm trying to do right now is connect using the urls.py(in main app) all the urls from my other app. First of all, import the library include (and the others that where already). from django.contrib import admin from django.urls import path, include The write the url/path: urlpatterns = [ path('admin/', admin.site.urls), path('Platform_App', include('Platform_App/urls.py', namespace = 'Platform_App', app_name = 'Platform_App')), ] But reading the django information, I tried to do something like this that doesn't work, urlpatterns = [ path('admin/', admin.site.urls), path('Platform_App', include('Platform_App.urls')), ] How I have to do it correctly? Thank very much!!! -
django admin list custom button's click event
admin.py class TestAdmin(admin.ModelAdmin): class Media: js = ( 'js/common.js', ) list_display = ['custom_actions'] def custom_actions(self, obj): return mark_safe( '<a class="button call_alert" href="#" data-msg="A">A</a>&nbsp;' '<a class="button call_alert" href="#" data-msg="B">B</a>' ) custom_actions.short_description = 'Custom Actions' admin.site.register(Test, TestAdmin) js/common.js (function($) { $(".call_alert").on("click", function() { alert($(this).data("msg")); // ★★★ Dose not!!! ★★★ }); })($); error message : Uncaught TypeError: $ is not a function at common.js:2 at common.js:5 How can I get alert message? Is it impossible? Please help.. -
Display Text in Text Area Django
I'm new to Django and looking for a way to display terms and condition paragraphs in the Text area to view them on my home.html. Text for TextArea: To use the Online Services through U.S. Bank, you must: • Be a U.S. Bank customer with an eligible account; • Have and maintain valid log-in credentials (including a personal ID and password) for Online Services, which may be provided and revoked in our sole discretion; • Have and maintain a valid email address; • Agree to electronically accept this Agreement and notices regarding this Agreement; and • Use Online Services in accordance with the terms of this Agreement. Use of certain Online Services may require additional accounts or other eligibility requirements. Any help would be appreciated, Thanks in Advance -
Django Model DateField and input fixture
Model file includes : class Foo(models.Model): bar = models.DateTimeField() Fixture file.json includes: { "model": "app.Foo", "pk": "1", "fields": { "bar": "2018/4/20", } }, when I'm trying to add fixtures with "python manage.py loaddata" result is: django.core.serializers.base.DeserializationError: Problem installing fixture 'C:\Projects\TestProject\app\fixtures\file.json': ['“2018/4/20” value has an invalid format. It must be in Y YYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']: (app.Foo:pk=1) field_value was '2018/4/20' so my question is how can I add date format with "YYYY/MM/DD" to my Model files ? -
django: unexpected file download after redirect when file does not exist
Django==1.11.12 If the file exists, the view function creates StreamingHttpResponse and all is fine. But if the file does not exist, the view function should redirect. The problem is, it does not redirect but instead prompt up to ask to save as a file, which has the content of redirected html. import os from wsgiref.util import FileWrapper import mimetypes from django.http import StreamingHttpResponse from django.shortcuts import render, redirect try: response = StreamingHttpResponse( FileWrapper(open(file_path, 'rb'), chunk_size), content_type=mimetypes.guess_type(file_path)[0]) response['Content-Length'] = os.path.getsize(file_path) response['Content-Disposition'] = "attachment; filename=a_file.xlsx") except FileNotFoundError as e: response = redirect("home") return response -
How to allow to choose a record from a dropdown or create a new one in Django?
I have a form for Trips where the client can select any of the existing flights from a dropdown. How can I allow the creation of a new flight right there, so that the client doesn't need to go the flight creation page if it realizes only when creating the trip that he needs a new flight? I am new to django/python so I don't really know if this is possible. -
Django timezone converting doesn't work on DateTimeField with values_list
I'm trying implement user based timezone to my Django app. I activated user timezone in middleware. In normal queries (like filter(),all()) everything is ok. In response, I can see timezone awarded data like that: {"modified": "2020-03-11T09:59:18.904323+03:00"} In some cases, I need to use values_list() method. Unfortunately response returns without timezone converting like that: {"modified": "2020-03-11T06:59:18.904323Z"} I can convert data inside a loop but I think it is not a good approach.Did anyone meet this problem? My middleware(It is working): class TimezoneMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated: tz_str = request.user.time_zone if tz_str: timezone.activate(pytz.timezone(request.user.time_zone)) else: timezone.activate(pytz.utc) request.user.time_zone = pytz.UTC.__str__() else: timezone.deactivate() response = self.get_response(request) return response -
Problem with many to many fieds in DRF create API
when I want to save an instance of my model, many to many fields did not be saved. I tried with below codes: models: class Attachment(models.Model): test = models.TextField() class PlanComment(models.Model): attachment = models.ManyToManyField('Attachment', blank=True) comment = models.TextField() serializers: class AttachmentSerializer(serializers.ModelSerializer): class Meta: model = Attachment fields = ['test'] class PlanCommentSerializer(serializers.ModelSerializer): attachment = AttachmentSerializer(many=True, read_only=True) class Meta: model = PlanComment fields = [ 'id', 'attachment', ] views: class PlanCommentViewSet(viewsets.ModelViewSet): """ API endpoint that allows plan comment to be viewed or edited. """ queryset = PlanComment.objects.all().order_by('-id') serializer_class = PlanCommentSerializer my params: { "attachment": [1], "comment": "Test" } -
register an admin user in django admin panel with only email id and then email account activation/password link to start using the admin panel
I have taken reference from https://github.com/DjangoGirls/djangogirls to create user model that user email instead of username. But at a super admin level, I want to add an email address and set activation flag and then send an email with a password setting link. Once the admin user clicks on the link and activates his account he should be able to login and start using the admin panel. Any guidance would be highly appreciated... Thanks in advance.. -
Parsing XML and saving Large Data to Django DB
I have a Django function that takes in a Nessus file and then parses the data before saving it to the database, my Nessus file typically have about 30k rows and saving this to the database can take as much as 2 hours, I have tried using bulk_create but this breaks the code, meanwhile I use Django 1.11, is there a way I can speed up these large inserts to the database (postgres) Here is my code: def process_nessus_file(*args, **kwargs): process_obj = kwargs.get('file') context = kwargs.get('context') request = kwargs.get('request') file_obj = process_obj.first() file_path = file_obj.file.path context = etree.iterparse( file_path, events=('end', ), tag="ReportHost" ) total_issues = 0 detected_issues = 0 undetected_issues = 0 already_exist_issue = 0 low_risk_count = 0 medium_risk_count = 0 high_risk_count = 0 critical_risk_count = 0 low_new_issue = 0 medium_new_issue = 0 high_new_issue = 0 critical_new_issue = 0 vul_history = [] for event, elem in context: first_identified = None last_seen = None host = elem.get('name') logger.info('Processing issue for host : {}'.format(host)) for child in elem: if child.tag == "HostProperties": for host_prop_tags in child: if host_prop_tags.attrib['name'] == "HOST_START": first_identified = host_prop_tags.text elif host_prop_tags.attrib['name'] == "HOST_END": last_seen = host_prop_tags.text if child.tag == "ReportItem": main_tags = child.attrib child_tags = dict() for ch_tags …