Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to sanitize very basic MySQL SELECT in Python/Django
This is driving my nuts. I have this very basic query that works without the sanitization statement but breaks with it. Everything I've read says to do it this way. query = "SELECT COL1 FROM A_TABLE %s" queryUserInput = "WHERE COL1 = 'user input value'" cursor.execute(query, (queryUserInput,)) I receive the error: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' WHERE ... Top of the stack: C:..\env\lib\site-packages\mysql\connector\connection_cext.py in cmd_query raw_as_string=raw_as_string) Python 3.7 Django 2.1.3 Any advice is very appreciated. -
How to check if a channel is empty
In Channels 1 I could get the number of pending messages in a channel with: RedisChannelLayer().channel_statistics(channel_name).get("messages_pending") I used this during automatic tests to ensure that the channel is empty before starting the next test to avoid an undesired influence of old channel messages. How can I check if a channel is empty or get the number of pending messages in a channel in Channels 2? -
django.db.utils.operationalerror: <2006, "Access denied for user 'root'@'localhost' <using password: YES>"
i used the command python manage.py migrate and the project settings.py are as follows: DATABASES = { 'default':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'timesheetdb', 'USER': 'root', 'PASSWORD': '123456', 'HOST': 'localhost', 'PORT': '' } I am getting an error of: django.db.utils.Operationalerror:<2006,"access denied for user'root'@'localhost' ". i get the same error with the command python manage.py runserver Can you help? -
django, how remove permission form
DJANGO 1.8 I would remove the complete form "permissions" from auth/group/add auth/group/change because I using a second customize admin interface. I founded only the following code, but it modify only the pemermissions list: from django.contrib.auth.admin import GroupAdmin class MyGroupAdmin(GroupAdmin): def get_form(self, request, obj=None, **kwargs): # Get form from original GroupAdmin. form = super(MyGroupAdmin, self).get_form(request, obj, **kwargs) if 'permissions' in form.base_fields: permissions = form.base_fields['permissions'] permissions.queryset = permissions.queryset.exclude(content_type__app_label__in=['admin', 'auth']) return form Is it possible to do? Thank's -
Docker Django image running but not found on localhost
I am trying to run a Django docker image. The image itself is running in the command line without any errors. However when I go to the URL my image is hosted at, the web page is not found. Below is my docker file I used to build the image FROM python:3.6 MAINTAINER c15523957 RUN apt-get -y update RUN apt-get -y upgrade RUN apt-get -y install libgdal-dev RUN mkdir -p /usr/src/app COPY requirements.txt /usr/src/app/ COPY . /usr/src/app WORKDIR /usr/src/app RUN pip install --upgrade pip RUN pip install --no-cache-dir -r requirements.txt EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] Below is the command used to run the image docker run -it -p8001:8000 c15523957/backendimage7 The console logs the message System check identified no issues (0 silenced). December 11, 2018 - 15:05:03 Django version 2.1.3, using settings 'backendproject.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. However when I go to the browser the web page is not found. Note: When I run the Django application without the Docker image the webpage is seen. This is done with python manage.py runserver -
Django REST Framework - SerializerMethodField is null on serializer.save()
I am using Django and REST Framework. I want to save with serializer by data. I called to serializer.save(). But saved model field is null with animal field in HumanSerializer. I want define animal field by SerializerMethodField and want to save model. How to do it? Serializer: class HumanSerializer(serializers.ModelSerializer): animal = SerializerMethodField() class Meta: model = Human fields = ( 'id', 'animal', # <- animal is ForeignKey of Animal model ) def get_animal(self, lead): # blah blah blah pass A save process: data['animal'] = 1 serializer = HumanSerializer( data=data, context={'request': request}, ) if serializer.is_valid(): human = serializer.save() human.animal # <- animal is null. but delete SerializerMethodField then not null -
I have label with name Lab in template,How to use label value in view
I have label with name Lab in template,How to use label value in view my template: {%for product in products %} <div class="column"> <img src=" {{product.image.url}}" class="w3-bar-item w3-circle " style= {"width:50px";"high:10px;"}> <label name="Lab" id="my">{{product.id}}</label> <p>{{product.name}} {{product.Price}} SR</p> <form action="" method="POST"> {% csrf_token %} {{form.as_p}} < <button type="submit" id="dd">Add to my order</button> </form> my view: if data.is_valid(): table = models.Get() table.count = data.cleaned_data['count'] table.order_id_id = order_id table.product_id_id = request.POST.get['Lab'] table.save() -
Method call error inside received email body
I am sending an automated email through the system and when it arrives in the body of the email all the methods are there, except the str(self.total_mes_pagar) method that appears the following line" I am very new to python and would appreciate all the help and patience with me, because I am almost going crazy with this problem models.py class Veiculo(models.Model): marca = models.ForeignKey(Marca, on_delete=models.CASCADE, blank=False) modelo = models.CharField(max_length=20, blank=False) ano = models.CharField(max_length=7, default="2018") placa = models.CharField(max_length=7) proprietario = models.ForeignKey( Pessoa, on_delete=models.CASCADE, blank=False, ) cor = models.CharField(max_length=15, blank=False) def __str__(self): return str(self.modelo) + ' - ' + str(self.placa) class Mensalista(models.Model): veiculo = models.ForeignKey(Veiculo, on_delete=models.CASCADE, blank=False) inicio = models.DateField(("Início"), default=datetime.date.today) validade = models.DateField(("Validade"), blank=False, ) valor_mes = models.DecimalField( max_digits=6, decimal_places=2, blank=False) pago = models.CharField(max_length=15, choices=PAGO_CHOICES) @property def email(self): return self.pessoa.email def mensal(self): return math.ceil((self.validade - self.inicio).total_seconds() / 86400) def total_mes(self): return math.ceil(self.mensal() // 30) def total_mes_pagar(self): return self.valor_mes * self.total_mes() def __str__(self): return str(self.veiculo) + ' - ' + str(self.inicio) def send_email(self): if self.pago == 'Sim': assunto = 'Comprovante pagamento Estacione Aqui 24 Horas' mensagem = 'Obrigado por utilizar o Estacione Aqui 24 horas. Ativação do estacionamento dia : ' + str(self.inicio) + 'Com validade até o dia ' + str( … -
adding review to a site and then sending mobile vertification and registration in django
I have a simple site, now I want to every person could leave review to the products and then after submitting a review, redirect to another page and getting the phone number and in final steps after receiving the verification code via phone, register name and then the review of site will be put in its place and assign to its user. I just want to design model and views, and the front end is not required. here is my code for the review model: class Review(models.Model): user = models.ForeignKey(User) rate = models.IntegerField( default=1, validators=[MaxValueValidator(100),MinValueValidator(0)]) comment = models.TextField(max_length=200) item = models.ForeignKey('item.Item',on_delete=deletion.CASCADE) my first concern is how to track a users session in order to assign each review to its user. every code or hint is appreciable -
What is the purpose of Celery's "autodiscover_tasks" function?
I'm wondering what is the purpose of Celery's "autodiscover_tasks" function. Im am using Celery 4.1.2 with Django 2.1.4. The Celery documentation refers to imports foo.tasks and bar.tasks being imported But I can't comprehend how this works. All the examples I found on GitHub including this one from the Official Celery repo, rely on manually importing the tasks when in need to use it like this: from demoapp.tasks import add, mul, xsum. I guess this is how Python work, you can't access to classes "globally", like in Ruby, for example. Then once, again, what is this function for ? I'm no expert at Celery and maybe I am missing something. The only thing I see is the name of the discovered tasks when launching the Celery worker, is that all this function is supposed to do? Thanks for your inputs, -
Django - Celery Creating a PeriodicTasK from my model
I have this model class Discoveries (models.Model): creation_date = models.DateTimeField(auto_now=True) last_run = models.DateTimeField(auto_now=True) created_by = models.CharField(default="Admin", blank=False, max_length=250) name = models.CharField(blank=False, default="Default Network Discovery", max_length=250) target = models.CharField(blank=False, max_length=250) ports = models.CharField(max_length=300, blank=True, null=True) options = models.CharField(default="-T4 -sV -A -PS", max_length=350) I have this task @app.task def run_discovery(data): n = discovery.discovery() run = {'target': data['target'], 'options':data['options']} b = n.run_discovery(run) My problem, the "data" to run task is a Discovery model instance, How to Associate a Discoveries Model to a PeriodicTask ? I my frontend I have a Form to create Task and select same params to create the PeriodkTask, then when de user Save a new Disvory I wanna create a new Periodic Task Based on this Parameter. -
What is a alternative to Haystack for Django framework?
Brief description With my team I'm creating a search engine for our project that contains a lot of data (I'm talking about millions). We use Django Framework & ElasticSearch because using a nosql search engine renders the results very fast.We use Haystack because it provides an easy modular search system for Django. Search engine & data deeper explained Our search engine contains two input fields. Both can be used but one is enough. Each item in our data has determined on which location it must be found. So, the user searches an item in one or multiple location and the search engine looks for each item out of a million and searches if that item has that location. Our problem & question However, because we have a lot of data and our search engine will have a ranking method and deep filter system, we are hesitating if Haystack is the right system for us. We cannot add EVERY content of an item inside one .json. Is there a better alternative that can handle more complex search results? If we want to use a nosql search engine, but have complex data structure, how can we do that using elastic search? e.g.: … -
Django: Returning boolean whether a value exist in ManyToManyField or not
I have tow models ModelA and ModelB. class ModelA(models.Model): multivalues = models.CharField(max_length=100) def __str__(self): return self.multivalues Class ModelB(models.Model): name = models.CharField(max_length=100) dogs = models.ManyToManyField(ModelA) I want to check in django view that whether an object 'o' of ModelB already has some value for field2. For example if there is an object 'o' of ModelB whose value for field1 is 'Ankit' and value for field2 is 'Labra' , 'Rottweiler' and 'Pug'. I want to check whether o.dogs has 'Labra' or not. How can i achieve this? Since 'dogs' field is ManyToMany field so when i use ModelB.objects.all().values('dogs') What i get is the following result: <QuerySet [{'dogs': 1}, {'dogs': 2}, {'dogs': 3}]> I do not how to proceed from here. -
Django string model reference for through field keyword argument
This is working for me: class Task(models.Model): many_dateranges = models.ManyToManyField('DateRange') class DateRange(models.Model): start_date = models.DateTimeField() end_date = models.DateTimeField() task_myset = models.ManyToManyField(Task, through=Task.many_dateranges.through) I wanted to have a reverse relation that is explicit in the code for some reasons, and its ok. But in case of circular imports, it fails for string model reference: class DateRange(models.Model): start_date = models.DateTimeField() end_date = models.DateTimeField() task_myset = models.ManyToManyField('myapp.Task', through='myapp.Task.many_dateranges.through', blank=True) class Task(models.Model): many_dateranges = models.ManyToManyField(DateRange) I get this error, even if i specify the app name or not: ValueError: Invalid model reference 'myapp.Task.many_dateranges.through'. String model references must be of the form 'app_label.ModelName'. -
Is their any time advantage of using @property decorator on django models instead of saving the field directly into database
So a field that can be computed like full_name from first and last name, we should use the @property to compute the full_name. But when we required to get a list of all 'n' persons with their full name. the full_name will be computed 'n' times which should require more time than just getting the field from database(if it stored as separate field already!). So is their any processing time / db fetching time advantage /disadvantage of using @property to compute full_name? (Note: I have considered other advantages of @property like reduction of database size, not worrying about change in first or last name without change in full name, setter function to set first and last name etc. I just want to know the processing/ db fetching time advantage/disadvantage over saving full_name into database. -
Using template tag in ModelAdmin.readonly_fields method
I use this pattern: class PersonAdmin(admin.ModelAdmin): readonly_fields = ('address_report',) def address_report(self, instance): return format_html(...) Source: docs about readonly_fields Now I would like to use a custom templatetag in the Python method address_report(). What is the best way to call it? I tried to called my templatetag directly, but this just returns a dictionary, not html. -
Fix AttributeError: 'str' object has no attribute 'HTTP_201_CREATED'
I have implememented the following method on a viewset and I'm having an issue when posting I get AttributeError: 'str' object has no attribute 'HTTP_201_CREATED'. Why am I getting this error message since the data has already been serialized into json format. def create(self, request,*args, **kwargs): # Payload Items paid_to = request.data['paid_to'] paid_from = request.data['paid_from'] amount = request.data['amount'] description = request.data['description'] date = request.data['date'] status = request.data['status'] # System Item auth_= get_auth(request) # Limit currency choices if setup default_currency = DEFAULT_CURRENCY # Get Transaction Type & show cr and dr accounts involved: transaction_type = TransactionType.objects.get(id=request.data['transaction_type']) get_credit_account = transaction_type.credit_account get_debit_account = transaction_type.debit_account # Money To Internal Value amount_to = Money(amount,DEFAULT_CURRENCY) # Auto generate transaction number transaction_number = increment_transaction_number() # Create Transaction objects transaction = Transaction.objects.create( transaction_type=transaction_type, organization=auth_, paid_to=paid_to, paid_from=paid_from, description=description, date=date, amount=amount_to, transaction_number=transaction_number) trans_id = transaction.id # print(trans_id) # Add directions to legs ..note positive direction is DEBIT and negative direction is CREDIT positive_direction = 1 negative_direction = -1 # Add leg objects instances to track debits and credits TODO can add mutiple legs Leg.objects.create(transaction=Transaction.objects.get(id=transaction.id), account=get_credit_account, description=transaction.description, amount=+amount_to * positive_direction) Leg.objects.create(transaction=Transaction.objects.get(id=transaction.id), account=get_debit_account, description=transaction.description, amount=-amount_to * negative_direction) serializer = CreateTransactionSerializer(transaction) from rest_framework.renderers import JSONRenderer data = JSONRenderer().render(serializer.data) return Response(data, status=status.HTTP_201_CREATED, headers=headers) -
modelformset_factory doesnt save instances to database
Im trying to make a formset with instances on my page, but formset dont saving instances at all. Extra fields saving is working well, but i cant get whats wrong with instances. I have a lot of forms on the page, and this is the last one, that not saving: My view: def details(request, username, slug): sm = Social_media.objects.all() profile = get_object_or_404(Profiles, user__username=username) site = get_object_or_404(MySites, slug=slug, user__username=username) ftp = get_object_or_404(FTP, site=site) FtpPathFormSet = forms.modelformset_factory(FtpPath,form=FtpPathForm,extra=1) sjim_ops = SjimOperations.objects.filter(user=request.user).order_by('-date') sjim_det = SjimDetails.objects.all() if request.method == 'POST': // other forms and logic if 'change3' in request.POST: newsite = NewSiteForm(instance=site) newftp = NewFtpForm(instance=ftp) ftppath = FtpPathFormSet(request.POST) if ftppath.is_valid: print('here') i = 0 instances = ftppath.save(commit=False) for instance in instances: print('here2') instance.ftp = ftp instance.recursive = request.POST.get('form-'+str(i)+'-recursive') if instance.recursive == 'on': instance.recursive = True else: instance.recursive = False instance.period = request.POST.get('form-'+str(i)+'-period') try: testconnect = ftplibr(ftp.host) testconnect.login(user=ftp.ftpuser, passwd=ftp.password) testconnect.cwd(instance.path) instance.find = True testconnect.quit() except: instance.find = False ftppath.save() i =+ 1 return redirect('main:details', username=username, slug=site.slug) model: class FtpPath(models.Model): period = ( ('Раз в сутки','Раз в сутки'), ('Раз в неделю','Раз в неделю'), ('Раз в 2 недели','Раз в 2 недели') ) ftp = models.ForeignKey(FTP, on_delete=models.CASCADE) path = models.CharField(max_length=200, blank=True) period = models.CharField(choices=period, max_length=20, null=True, blank=True) find = … -
Reviewboard installation with Apache, shows files instead of site
Installing reviewboard on centos 7. Web server : Apache running on port 8080 After i finished the installation it shows me directory listing when i access it from browser. Below is my apache-wsgi.conf file <VirtualHost *:8080> ServerName reviews.com DocumentRoot "/var/www/html/reviews.com/htdocs" # Error handlers ErrorDocument 500 /errordocs/500.html WSGIPassAuthorization On WSGIScriptAlias "/reviews" "/var/www/html/reviews.com/htdocs/reviewboard.wsgi/reviews" <Directory "/var/www/html/reviews.com/htdocs"> AllowOverride All Options -Indexes +FollowSymLinks Require all granted </Directory> # Prevent the server from processing or allowing the rendering of # certain file types. <Location "/reviews/media/uploaded"> SetHandler None Options None AddType text/plain .html .htm .shtml .php .php3 .php4 .php5 .phps .asp AddType text/plain .pl .py .fcgi .cgi .phtml .phtm .pht .jsp .sh .rb <IfModule mod_php5.c> php_flag engine off </IfModule> # Force all uploaded media files to download. <IfModule mod_headers.c> Header set Content-Disposition "attachment" </IfModule> </Location> # Alias static media requests to filesystem Alias /reviews/media "/var/www/html/reviews.com/htdocs/media" Alias /reviews/static "/var/www/html/reviews.com/htdocs/static" Alias /reviews/errordocs "/var/www/html/reviews.com/htdocs/errordocs" Alias /reviews/favicon.ico "/var/www/html/reviews.com/htdocs/static/rb/images/favicon.png" </VirtualHost> What is the issue and how to fix it. -
How to exclude values in django aggregation?
I have done this: groups = group1.objects.filter(User=request.user, Company=company_details.pk, ledgergroups__Creation_Date__gte=selectdatefield_details.Start_Date, ledgergroups__Creation_Date__lte=selectdatefield_details.End_Date).exclude(group_Name__icontains='Capital A/c') groups_cb = groups.annotate( closing = Coalesce(Sum('ledgergroups__Closing_balance'), 0), opening = Coalesce(Sum('ledgergroups__Balance_opening'), 0), ) I want to perform aggregation in 'closing' and 'opening' by interchanging the negative values of annotation... I mean the negative value which will come through annotation in 'closing', that value should be added with the aggregated value of 'opening'.... For example: if the values of closing are 2500,5000,-8000 The total value will be 7500(aggregated value) and -8000 will be added in the aggregated value of 'opening'. Do anyone have any idea how to solve this? -
UpdateView problem : cleaned data passed in url not in instance
I have a problem with my update view but I can't figure out why it happens. So when I try to update an object with an UpdateView I don't get any error showing it just doesn't work and reload the page instead with the changed data passed into the url : "[11/Dec/2018 11:49:20] "GET /home/update/vacation/421?csrfmiddlewaretoken=Op55u8r2GG2uyDjIvW2rstfedeU646ZkrJsmUOC6824rRO5W5NTT4koNwNCIBmof&poste_travail=poste+testa+modif&taux_marge=35.0 HTTP/1.1" 200 2887" I tried to overwrite form_invalid and fom_valid to understand what is happening but it doesn't print anything Does anyone have an idea why this doesn't work ? views_class.py class VacationUpdate(LoginRequiredMixin, UpdateView): login_url = 'login' redirect_field_name = 'redirect_to' form_class = VacationUpdateForm model = Vacation template_name = 'chiffrage/forms/vacation_update.html' pk_url_kwarg = 'vacation_id' def form_invalid(self, form): print(form.changed_data) def form_valid(self, form): print(form.data) vacation = form.save(commit=False) vacation.updated_by = self.request.user vacation.save() return super().form_valid(form) def get_success_url(self): return HttpResponseRedirect(reverse('marge_prix', args=( self.object.version_contrat.contrat.site.client.slug(), self.object.version_contrat.contrat.site.client.pk, self.object.version_contrat.contrat.site.slug(), self.object.version_contrat.contrat.site.pk, self.object.version_contrat.contrat.slug(), self.object.version_contrat.contrat.id, self.object.version_contrat.slug(), self.object.version_contrat.id))) forms.py class VacationUpdateForm(forms.ModelForm): class Meta: model = Vacation fields = ['poste_travail', 'taux_marge'] urls.py path('update/vacation/<int:vacation_id>', views_class.VacationUpdate.as_view(), name='vacation_class_update'), path('clients/<slug:client_name>,<int:client_id>/<slug:site_name>,<int:site_id>/<slug:contrat_slug>,<int:contrat_id>/<slug:version_slug>,<int:version_id>/prix', views.vacation_add, name='marge_prix'), vacation_update.html {% extends 'base.html' %} {% block title %} {{ request.user }}{% endblock %} {% block ligne-titre %}{{ client }}{% endblock %} {% block sans-div %} <div class="main container-fluid col-8"> <form class="form-group"> {% csrf_token%} <table class="table table-sm table-bordered"> {{ form.as_table }} <tr> <td colspan="2"><input … -
Embedding HTML with Python
Iam trying to get input from the user and convert it into pdf. Iam using python. I want to create a text box for getting the input from the user. This is my code below. from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_xy(0, 0) pdf.set_font('arial', 'B', 13.0) pdf.cell(ln=0, h=5.0, align='L', w=0, txt= "hello world", border=0) pdf.output('test.pdf', 'F') The code works well. The text "hello world" is printed as pdf. But I couldn't add html code here for getting input. How can I embed html with python here. Thanks. -
How to export all the data from multiple models with the same foreign key in Django?
I'm new in django. I tried a lot to export data from multiple models by using ForeignKeyWidget. I'm able to export data only from a single > model.Is it possible to export all the data drom multiple related tables using ForeignKeyWidget? models.py class NewRegistration(models.Model): houseowner_name_en = models.CharField(max_length=30) ward_no = models.ForeignKey(system_settings.models.Wardno) contactno = models.CharField(max_length=30) construction_type = models.ForeignKey(system_settings.models.ConstructionType) taxpayer_id = models.CharField(max_length=30, blank=True, null=True) cen = models.IntegerField() is_forwarded = models.BooleanField(default=False) class Meta: verbose_name = 'दर्ता फाइल' verbose_name_plural = 'दर्ता फाइलहरु' def __unicode__(self): return self.houseowner_name_np class Application(models.Model): registration_date = models.CharField(max_length=15) building_use = models.ForeignKey(to=system_settings.models.BuildingUse) building_category = models.CharField(max_length=30) building_structure_category = models.ForeignKey(to=system_settings.models.BuildingStructureCategory) building_storey = models.IntegerField(blank=True, null=True, default=0) building_area = models.DecimalField(max_digits=6, decimal_places=2) reg = models.ForeignKey(NewRegistration) class Landowner(models.Model): landowner_type = models.CharField(max_length=30) lo_salutation = models.CharField(max_length=30) lo_name_np = models.CharField(max_length=30) lo_citizenship_issue_date = models.CharField(max_length=30) lo_phone_no = models.CharField(max_length=30) lo_email = models.EmailField(null=True, blank=True) reg = models.ForeignKey(NewRegistration) -
Image does not upload using createview from template django
CompanyCreateView is a generic view. The file uploads from django administration but does not upload from template. company_logo is stored in mysql database class CompanyCreateView(CreateView): model = Company fields = ['company_name', 'company_description', 'company_email', 'company_website', 'company_address', 'company_phone', 'company_status', 'company_monthly_payment', 'company_logo'] company_form.html {% extends "super_admin/base.html" %} {% load crispy_forms_tags %} {% block content %} {{ form | crispy}} {% endblock content %} -
problems with sending email using foreign key email
I need to send an email when I pay in the Mensalista table, but with this code I can not get the email that appears through the foreign key in the Veiculo field and even when he was sending before, in the body of the email the code "def total_mes_pagar" appeared like this: models.py class Veiculo(models.Model): marca = models.ForeignKey(Marca, on_delete=models.CASCADE, blank=False) modelo = models.CharField(max_length=20, blank=False) ano = models.CharField(max_length=7, default="2018") placa = models.CharField(max_length=7) proprietario = models.ForeignKey( Pessoa, on_delete=models.CASCADE, blank=False, ) cor = models.CharField(max_length=15, blank=False) def __str__(self): return str(self.modelo) + ' - ' + str(self.placa) class Mensalista(models.Model): veiculo = models.ForeignKey(Veiculo, on_delete=models.CASCADE, blank=False) inicio = models.DateField(("Início"), default=datetime.date.today) validade = models.DateField(("Validade"), blank=False, ) valor_mes = models.DecimalField( max_digits=6, decimal_places=2, blank=False) pago = models.CharField(max_length=15, choices=PAGO_CHOICES) @property def email(self): return self.pessoa.email def mensal(self): return math.ceil((self.validade - self.inicio).total_seconds() / 86400) def total_mes(self): return math.ceil(self.mensal() // 30) def total_mes_pagar(self): return self.valor_mes * self.total_mes() def __str__(self): return str(self.veiculo) + ' - ' + str(self.inicio) def send_email(self): if self.pago == 'Sim': assunto = 'Comprovante pagamento Estacione Aqui 24 Horas' mensagem = 'Obrigado por utilizar o Estacione Aqui 24 horas. Ativação do estacionamento dia : ' + str(self.inicio) + 'Com validade até o dia ' + str( self.validade) + ' Confirmamos o …