Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django pass value of TabularInline field when Buttonclick
I have a Course model and pupils model. Pupils are a tabularInline in the Course admin Panel. I implemented in tabular.html a Button for every Line in front of the pupils: <input type="submit" value="pass" name="pass_arguments" onclick="location.href='{% url '...' %} The mission is to pass the first name and surname of the pupil when I click a Button. For instance: 7 Pupils. When i click the Button of Pupil 3, a new page opens where i can see the first name and surname in a new template. How can I pass the first name and surname as values? Thank you very much. I'm really struggling. -
Updating django model when changing
The model has a "content" field. When changing this model, it is necessary to look for the symbol "<a" in the "content" field and add the line "rel =" nofollow "into it (as if in a tag). I’m trying to do this with a function in the models.py file. Tell me how to do this ? -
Django - have created a pdf file using ReportLab but how do i store it into a FileField record?
In views.py: c = canvas.Canvas(str(num)+'.pdf') c.setPageSize((page_width, page_height)) c.drawInlineImage('logo.jpg', margin, page_height - image_height - margin, image_width, image_height) c.setFont('Arial', 80) text = 'INVOICE' c.save() In models.py: class Invoices(models.Model): Date = models.DateTimeField() Name = models.CharField(max_length=100, blank=True, null=True) document = models.FileField(upload_to='temp/', blank=True, null=True) My view creates a record and completes the Date & Name record, i then create the pdf which works fine (can see it in my root directory) but how do i send it straight to the FileField, i'm using Heroku to host my package incase that causes more problems Thanks in advance Any -
access fields using intermediate model attributes in Django
I have 3 models and one of them is an intermediate model as the following: class Choice(models.Model): choice_text = models.CharField(max_length=20) class Question(models.Model): choices = models.ManyToManyField(Choice, through='QuestionChoice') class QuestionChoice(models.Model): choice = models.ForeignKey(Choice, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) correct = models.BooleanField(default=False) I am trying to access a particular question and then get the correct choice from the intermediate model. First_question = Question.objects.get(id=2) First_question.objects.filter(QuestionChoice__correct=True) this is the error I get Manager isn't accessible via Question instances I have read that I can't use First_question to access the intermediate model but using Question would retrieve all the question choices which is not what I am looking for. -
Return picture as base64 instead of its url In Django Rest
User model where the field ImageField class User(AbstractUser, TimeStamp): address = models.CharField(max_length = 30) phone = models.CharField(max_length=15, blank=True, null=True) picture = models.ImageField(upload_to='images/', null=True, blank=True, default='images/user.jpg') def get_picture_base64(self): return image_as_base64(settings.MEDIA_ROOT + self.picture.path) An here is the serializer and the view : class UpdateProfileSerializer(serializers.ModelSerializer): phone = serializers.CharField(required=False) picture = Base64ImageField(max_length=None, use_url=True, required=False) class Meta: model = Profile fields = ( 'picture', 'address', 'phone') The Api view on which I want to update user's fields : I want to return in json response beside the updated fields, the picture as base64 not as URL class UpdateProfileAPIView(UpdateAPIView): queryset = User.objects.all() serializer_class = UpdateProfileSerializer permission_classes = [IsAuthenticated] def get_object(self, queryset=None): return self.request.user def partial_update(self, request, *args, **kwargs): user = self.get_object() serializer = self.get_serializer(user, data=request.data, partial=True) if serializer.is_valid(raise_exception=True): self.perform_update(serializer) return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django + PostrgreSQL performance issues
i have a performance issue after using django-pgcrypto-fields: model is: class AssignedEmployee(models.Model): user_email = CharPGPSymmetricKeyField(max_length=50) project = models.ForeignKey('Project', on_delete=models.CASCADE, db_index=True) status_of_assignment = models.BooleanField(default=False, null=True) datetime_of_assignment = DateTimePGPSymmetricKeyField(null=True) exception_text = CharPGPSymmetricKeyField(max_length=255, null=True) class Meta: unique_together = (('user_email', 'project'), ) views.py: 1st: def action_required_projects(request): assigned_projects = AssignedEmployee.objects.filter( user_email__iexact=request.user.email, status_of_assignment=False).select_related('project').order_by('project_id') 2nd: def signed_projects(request): assigned_projects = AssignedEmployee.objects.filter( user_email__iexact=request.user.email, status_of_assignment=True).select_related('project').order_by('-project_id') So 2nd view works like 18 times slower. If i change status_of_assignment=True to status_of_assignment=False it works as fast as the 1st one. explain() and print_sql shows me this: for the first view: Sort (cost=238.09..238.10 rows=3 width=189) Sort Key: assignedemployee.project_id -> Nested Loop (cost=0.57..238.06 rows=3 width=189) -> Index Scan using assign_status__63421e_idx on assignedemployee (cost=0.29..213.08 rows=3 width=196) Index Cond: (status_of_assignment = false) Filter: ((NOT status_of_assignment) AND (upper(pgp_sym_decrypt(user_email, 'secret'::text)) = 'PAVEL@example.COM'::text)) -> Index Scan using projec_id_dcb74d_idx on project (cost=0.28..8.30 rows=1 width=443) Index Cond: (id = assignedemployee.project_id) SELECT "assignedemployee"."id", pgp_sym_decrypt("assignedemployee"."user_email", 'secret')::TEXT, "assignedemployee"."project_id", "assignedemployee"."status_of_assignment", pgp_sym_decrypt("assignedemployee"."datetime_of_assignment", 'secret')::TIMESTAMP, "project"."id", pgp_sym_decrypt("project"."language", 'secret')::TEXT, pgp_sym_decrypt("project"."client_name", 'secret')::TEXT, pgp_sym_decrypt("project"."engagement_name", 'secret')::TEXT, pgp_sym_decrypt("project"."deadline", 'secret')::DATE, "project"."status", pgp_sym_decrypt("project"."access", 'secret')::TEXT FROM "assignedemployee" INNER JOIN "project" ON ("assignedemployee"."project_id" = "project"."id") WHERE ("assignedemployee"."status_of_assignment" = FALSE AND UPPER(pgp_sym_decrypt("assignedemployee"."user_email", 'secret')::TEXT::text) = UPPER(Pavel@example.com)) ORDER BY "assignedemployee"."project_id" ASC [Time elapsed: 231.51ms] and for the 2nd Sort (cost=1988.54..1988.95 rows=166 width=189) Sort Key: assignedemployee.project_id DESC -> Hash Join (cost=427.77..1982.42 rows=166 … -
Django EmailMessage add attachement to an email
In my python django project i use this two method for send html email: def send_html_email(to_list, subject, template_name, context, sender=settings.DEFAULT_FROM_EMAIL): msg_html = render_to_string(template_name, context) msg = EmailMessage(subject=subject, body=msg_html, from_email=sender, to=to_list) msg.content_subtype = "html" # Main content is now text/html return msg.send() def emailsend(l_sender, l_lic, t_name='consok'): if t_name == 'lavoraok': templ = 'lavora_ok.html' ttitle = 'test: Nuova candidatura da sito web' elif t_name == 'lavoraok_cli': templ = 'lavora_ok_cli.html' ttitle = 'test: Nuova candidatura da sito web' else: templ = 'cons_del.html' ttitle = 'test: Appuntamento cancellato' context = { 'news': 'test consulenza', 'lic': l_lic } try: send_html_email(l_sender, ttitle, templ, context, sender='test@prova.com') except Exception as e: print('Email send error: ', e) all woks well, but now in my new form i got a field for attach a file to send via email. How can i implement my defs for attach file to email? So many thanks in advance -
NoReverseMatch at / Reverse for 'details' with no arguments not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/$']
models.py class Post(models.Model): title = models.CharField(max_length=200) auther = models.ForeignKey('auth.User',on_delete=models.CASCADE) body = models.TextField(max_length=300) def __str__(self): return self.title views.py file class PostView(ListView): model = Post context_object_name = 'posts' template_name = 'blog/post.html' class PostDetail(DetailView): model = Post context_object_name = 'postdetails' template_name = 'blog/detail.html' post.html <body> <h1><a href="{% url 'blog:details' %}">detail</a></h1> I also try this <a strong texthref="{% url 'blog:details' post.id %}">detail {% for p in posts %} <h1> Title: {{ p.title }}</h1> <h2>Auther: {{ p.auther }}</h2> <p>Text: {{ p.body }}</p> {% empty %} <h1>No post</h1> {% endfor %} </body> App url file blog_project/blog/urls.py urlpatterns = [ path('post/<int:pk>/',PostDetail.as_view(),name='details'), path('',PostView.as_view(),name='posts'), ] app_name = 'blog' project file blog_project/urls.py urlpatterns = [ path('',include('blog.urls')), path('admin/', admin.site.urls), ] I read lots of article but i can not solve it,Please help me to solve this problems, When i change somthing urls file then another occurs on rendering. Django version 2.2.5 -
local variable 'html_form' referenced before assignment
views.py def create_order(request): initial_date = { 'status':"In Progress" } form = OrderForm(request.POST or None, request.FILES or None,initial=initial_date, user=request.user) if request.method == 'POST': if form.is_valid(): order = form.save(commit = False) order.user = request.user; order.save() form = OrderForm(user=request.user) messages.success(request, "Successfully created") return redirect('/orderlist') context = {'form':form} html_form = render_to_string('accounts/templates/order_form.html', context, request=request, ) return JsonResponse({'html_form' : html_form}) this is my view function. I'm getting this error "UnboundLocalError at /orderlist/create_order/ local variable 'html_form' referenced before assignment" -
Is there anyway to get the current object in has_permission method while calling DetailView in Django CBV
I have a DetailView where I want to restrict the access to the payment based on the user project assignment related to this payment. I have the following code working just fine. Just wondering if there is a cleaner way to retrieve self.object within the has_permission instead of getting the object using the PK directly. class PaymentDetailView(LoginRequiredMixin, PermissionRequiredMixin, DetailView): model = Payment template_name = "finance/payments/details.html" context_object_name = "payment" def has_permission(self): payment = Payment.objects.get(pk=self.kwargs.get("pk")) # Check permission here based on the current user project assignment if condition: return True return False I understand that has_permission is part of PermissionRequiredMixin and not the DetailView and this might not be possible but I wonder if there is a better way to test this object-based permission. Note: the logic is a bit complicated and might not be as easy as a simple query (in fact it is actually based on the user role, project assignment, the time of assignment compared to the payment date, payment type.....) Thanks -
django css design checkbox too small
I have downloaded a design from the internet but the checkbox are too small. I don't have much time so can someone tell me how to overwrite the setting in the css file. Nothing seems to work. the django template is as follows: <form class="site-form" action="{% url 'doc_aide:the_doc_aide' pk=patient.id %}" method="post" enctype='multipart/form-data'> {% csrf_token %} <header class="first major"> <h2 class="icon fa-file-alt">Doctors Notes</h2> </header> {{ formset.as_p }} <input type="submit" class="btn btn-default" value="Write Prescription"> </form> the css file is rather I can't add but I can ensure you that input[type=checkbox] is nowhere to be found and if I add a new design it doesn't change anything. How can I find out where that particular code is so I can change it? -
Working with model forms and choose multiple items from many to many fields
I'm trying to using model forms and when creating a new mngreq,and i want to choose items from a manytomany django model fields that is who_user fields when i use admin site everything is ok but when i test it from my own html code it shows up but didnt save to database here is my code # models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=11) birth_date = models.DateField(null=True, blank=True) address = models.TextField(null=True, blank=True) profile_image = models.ImageField(upload_to='media/users', null=True, blank=True) def __str__(self): return self.user.get_full_name() class ManagementReq(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) who_user = models.ManyToManyField(Profile) content = models.TextField() creation_time = models.TimeField() attach = models.FileField(upload_to='media/manreqapp/files/%Y-%m-%d', null=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('mngreq-detail', kwargs={'pk': self.pk}) # views.py @login_required def MngReqCreate(request): if request.method == 'POST': mngreqform = MngReqForm(request.POST, files=request.FILES) if mngreqform.is_valid(): mngreq = mngreqform.save(commit=False) mngreq.author = request.user mngreq.creation_time = timezone.localtime(timezone.now()) mngreq.save() return HttpResponseRedirect(reverse('manreqapp:mngreq-list')) else: mngreqform = MngReqForm() context = { 'form': mngreqform, } return render(request, 'manreqapp/managementreq_create.html', context) {% extends "manreqapp/base.html" %} {% load static %} {% load crispy_forms_tags %} {% load widget_tweaks %} {% block extra_css %} <style> .vertical-center { display: flex; justify-content: center; } </style> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="vapid-key" content="{{ vapid_key }}"> … -
Creating object with foreign key in it
whenever I try to run "add_rat" in the below code I get the error Exception Value: Cannot assign "441": "Myrating.movieId" must be a "Movie" instance. I tried passing it as movieId_id=movieId in the function definition bu that gives the error: FOREIGN KEY constraint failed I also tried passing it as int() value but it did not work. I want to create Myrating object which has 2 foreign keys. admin.py: from django.contrib import admin from .models import Movie,Myrating from django.contrib.auth.models import User import csv # Register your models here. def add_set(modeladmin, request,queryset): with open('./movies.csv','r',encoding='utf-8', errors='ignore') as _filehandler: csv_file_reader=csv.DictReader(_filehandler) for row in csv_file_reader: movie=Movie.objects.create_movie(row['movieId'],row['title'],row['genres'],"mov.jpg") add_set.short_description = "New_Day" def add_rat(modeladmin, request,queryset): with open('./ratings.csv','r',encoding='utf-8', errors='ignore') as _filehandler: csv_file_reader=csv.DictReader(_filehandler) for row in csv_file_reader: movie=Myrating.objects.create_movie(int(row['userId']),Movie.objects.get(movieId=row['movieId']),float(row['rating'])) add_rat.short_description = "New_rat" def add_user(modeladmin,request,queryset): i=1 while i<=7045: user = User.objects.create_user(i, '', 'password') user.save() i+=1 add_user.short_description = "New_use" class movie_admin(admin.ModelAdmin): list_display=('title','genre') list_filter=('genre','title') actions=[add_set,add_user,add_rat] admin.site.register(Movie,movie_admin) admin.site.register(Myrating) models.py: from django.contrib.auth.models import Permission, User from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models class movie_manager(models.Manager): def create_movie(self, movieId,title,genre,movie_logo): movie = self.create(movieId=movieId,title=title,genre=genre,movie_logo=movie_logo) # do something with the book return movie class Movie(models.Model): movieId=models.PositiveIntegerField() title = models.CharField(max_length=200) genre = models.CharField(max_length=100) movie_logo = models.FileField() objects=movie_manager() def __str__(self): return str(self.title) class rating_manager(models.Manager): def create_movie(self, user,movieId,rating): movie = self.create(user_id=user,movieId=movieId.id,rating=rating) … -
ImproperlyConfigured error in creating new Django app
I'm getting this exact error while creating a new app(emulatorsMgmt): The included urlconf '<module 'apps.emulatorsMgmt' from './apps/emulatorsMgmt/init.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Here are the related files: urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.emulatorsMgmt.as_view(),name='emulatorsMgmt'), ] views.py: from django.shortcuts import render from django.views.generic import View # Create your views here. class emulatorsMgmt(View): def get(self, request): return render(request, 'hello.html') The hello.html is present in the templates/emulatorsMgmt folder. Also I have made the following addition in the urls.py of the central project: url(r'^emulatorsMgmt/', include('apps.emulatorsMgmt')) I have also added the app in my dirs of setting.py. I wonder where I am going wrong. Any help is greatly appreciated! -
how to avoid color codes in mod-wsgi error logs
I have deployed django application in apache using mod-wsgi, I have default log configuration of apache but logs generated in error_log are with color codes. Can someone suggest me how to avoid color codes in error_log file. Find the some Error logs below. OS: CentOS7, mod-wsgi:4.0.1, [Fri Jun 19 12:58:08.562426 2020] [wsgi:error] [pid 16039] [client 192.168.44.50:56120] \x1b[36m\x1b[0m [Fri Jun 19 12:58:08.562609 2020] [wsgi:error] [pid 16039] [client 192.168.44.50:56120] \x1b[36m16332\x1b[0m [Fri Jun 19 12:58:08.562808 2020] [wsgi:error] [pid 16039] [client 192.168.44.50:56120] \x1b[36m--5b2c6f38-11f0-4936-b31d-c673bc29764c\x1b[0m [Fri Jun 19 12:58:08.562984 2020] [wsgi:error] [pid 16039] [client 192.168.44.50:56120] \x1b[36mContent-Type: text/plain; charset=utf-8\x1b[0m [Fri Jun 19 12:58:08.563212 2020] [wsgi:error] [pid 16039] [client 192.168.44.50:56120] \x1b[36mContent-Disposition: form-data; name=is_app\x1b[0m [Fri Jun 19 12:58:08.563404 2020] [wsgi:error] [pid 16039] [client 192.168.44.50:56120] \x1b[36m\x1b[0m [Fri Jun 19 12:58:08.563587 2020] [wsgi:error] [pid 16039] [client 192.168.44.50:56120] \x1b[36m10\x1b[0m [Fri Jun 19 12:58:08.563775 2020] [wsgi:error] [pid 16039] [client 192.168.44.50:56120] \x1b[36m--5b2c6f38-11f0-4936-b31d-c673bc29764c--\x1b[0m [Fri Jun 19 12:58:08.563984 2020] [wsgi:error] [pid 16039] [client 192.168.44.50:56120] \x1b[36m\x1b[0m [Fri Jun 19 12:58:08.630140 2020] [wsgi:error] [pid 16039] [client 192.168.44.50:56120] \x1b[36mPOST /api/tmv1/agent-data-push/ - 201\x1b[0m [Fri Jun 19 12:58:08.630515 2020] [wsgi:error] [pid 16039] [client 192.168.44.50:56120] \x1b[36m{'content-type': ('Content-Type', 'application/json'), 'vary': ('Vary', 'Accept, Origin, Cookie'), 'allow': ('Allow', 'POST, OPTIONS'), 'x-frame-options': ('X-Frame-Options', 'DENY'), 'content-length': ('Content-Length', '65'), 'x-content-type-options': ('X-Content-Type-Options', 'nosniff')}\x1b[0m [Fri Jun 19 12:58:08.630765 2020] [wsgi:error] … -
How to Integrate Django's auth models with custom REACT front-end sign up
So, this question might be way too abstract but I feel the need to shoot the shot here. The Django I have been taught to use is quite out of convention where they do not use Django's default auth models/views. I will show you the example of my past SignUpView below: from .models import Customer class SignUpView(View): def post(self, request): data = json.loads(request.body) try: validate_email(data['email']) if len(data['password']) < 6: return JsonResponse({'message': '6자리 이상 입력하세요'}, status=400) if not Customer.objects.filter(email = data['email']).exists(): hashed_password = bcrypt.hashpw(data['password'].encode('utf-8'), bcrypt.gensalt()).decode('utf-8') Customer.objects.create( email = data['email'], password = hashed_password, username = data['username'], phone = data['phone'] ) return JsonResponse({'message':'SUCCESS'}, status=200) else: return JsonResponse({'message':'ALREADY_EXIST'}, status=400) except KeyError: return JsonResponse({'message':'INVALID_KEYS'}, status=400) except ValidationError: return JsonResponse({'message':'INVALID_EMAIL'}, status=400) However, here comes the day I get requested to create SuperUser functionality and custom permission functionality, thus forcing me to give up on the way I was taught to make signup view. Below is what I have created today, following along some blog post from django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth.models import Permission from django.contrib.auth.forms import UserCreationForm from django.views import View from django.contrib.auth import login from django.contrib.auth.decorators import login_required @login_required def index(request): return render(request,'accounts/index.html') def sign_up(request): context = {} form = UserCreationForm(request.POST … -
How to serve a static landing page on s3 base bucket URL to avoid Facebook Ads being blocked
We're using s3 to serve images for freelancer gigs on our freelancer marketplace. We often run ads on top selling experts on Facebook and all seemed to work well. However for the past 1 month FB has been continuously blocking our ads with the following error - the link goes against their community standards. Here is the screenshot of the error We have tried reaching out to FB support to no avail. Is there any way we can get around this. I have read some workaround like changing bucket URLs but it hasn't worked The error resurfaces even in sending messages via messenger as shown below Will serving a dummy html page on the below base URL fix the issue ? If yes how do I do it as uploading an index.html page didn't resolve the issue, changing properties to forward URL to another fetch too didn't work. Appreciate any help in finding some way to fix this gap -
How to use pk1 and pk2 in Django API?
I'm getting trouble when trying to queryset multiple pks (pk and pk2) in my URL. I want to do something like this: urlpatterns = [ path('tableau/<int:pk>/liste/<int:pk2>', views.ListeDetail.as_view()), ] I need a detail view of liste (pk2) contained in a tableau (pk). So far, here is my class but it does'nt work properly. class ListeDetail(generics.RetrieveUpdateDestroyAPIView): serializer_class = ListeSerializer def get_queryset(self): queryset = Liste.objects.filter(tableau_id=self.kwargs["pk"]) return queryset Anyone know how to work with multiple pks in the url ? -
Create Invoice for Client, Need to import client class data and product class data in django
I am a new Django learner, I am trying to create a web app with Django, I created client and product models. Now I need to create an invoice model that can import data from the client table and product table. Just by searching or dropdown option for unique fields for clients and products table Anyone can help me, please? -
Django query ends up with ORA-00932: inconsistent datatypes: expected - got CLOB
I have following query in my code packages = MyPackage.objects.all().values_list('name', 'version') packages_query = reduce( operator.or_, ( Q(packages_set__name=name, packages_set__version=version) for name, version in packages ) ) hosts = MyHost.objects.filter(packages_query).annotate( num_packages=Count('packages_set') ).filter( num_packages=len(packages) ) which ends up in ORA-00932: inconsistent datatypes: expected - got CLOB. I know what that error means but have no idea how to fix this properly.. I tried using "only" but the error is in Count('packages_set') which is vital for the query. Otherwise it's working just fine and when I get some set of attributes from the query, its working ok. Crashes only when trying to get the hosts itself. Is there any way how to fix this in django way? I know how to fix this in raw sql but editing the sql and triggering it manually seems as really shady way. -
Is it possible to validate uploaded csv file in Django?
My database will have a list of id. The uploaded csv file will contain many rows with id and quantity. When uploaded, I want to check to make sure that all the ids in the uploaded csv file matches with an id in the database. If it does, I want to cancel the upload. Is this possible to do in a Django website? If so, do I store the data in a table in the Django admin page itself? Any further details would be good too. Let's say I have this simple code for file upload: file = request.FILES['file'] decoded_file = file.read().decode('utf-8').splitlines() reader = csv.DictReader(decoded_file) -
How to send mail via a python script if MFA is enabled for that mail account?
I am not able to send mail through python script if MFA is enabled for my account. -
Django admin history button update
I'm new to django & I want to display both default history & Simple admin history. Right now when I inherit from SimpleAdminHistory it overrides the default History, I require for both of them to be displayed(2 buttons & user can select either one based on his requirements). The reason why I'm looking to implement this is because SimpleAdminHistory does not support inline history which I need to keep track of. I was wondering what would be the best way to approach this. I'm not looking for a complete solution more like a sense of direction. Any help is appreciated. -
Django Delete popup window
Right now when I click on the delete link in my template it redirects me to another delete template, where I can click the submit button to delete or cancel link to cancel. I want a popup window to display on the same template confirming my deletion. I have passed primary keys in my URL , so I'm a bit confused about what should I pass in my URL so the delete window appears on the same template. views.py def delete_order(request, pk): order = Order.objects.get(id=pk) if request.method == "POST": order.delete() return redirect('/orderlist') context = {'Order':order} return render(request, "delete.html", context) url.py path('delete_order/<str:pk>/', delete_order, name='delete-order'), Order_list.html {% extends 'base.html' %} <!DOCTYPE html> <html> <head> {% block content %} <center> <h1>Order Record</h1> </center> </head> <body> <div> <table class="table"> <thead class="bg-secondary"> <tr> <th scope="col">Order ID</th> <th scope="col">Customer ID</th> <th scope="col">Quote</th> <th scope="col">Box</th> <th scope="col">Pill Choice</th> <th scope="col">Shipping tracking</th> <th scope="col">Memo</th> <th scope="col">Status </th> <th scope="col"></th> <th scope="col"></th> <th scope="col"><a type="button" class="btn btn-outline-dark" href="{% url 'accounts:create-order' %}">Create</button></a></th> </tr> </thead> {% for Order in order %} <tbody> <tr> <th scope="row">{{ Order.id }}</th> <td>{{ Order.user }}</td> <td>{{ Order.quote}}</td> <td>{{ Order.box }}</td> <td>{{ Order.pill_choice }}</td> <td>{{ Order.shipping_tracking }}</td> <td>{{ Order.memo }}</td> <td>{{ Order.status }}</td> <td><a class="button" href="{% url … -
How can I run a function for just 5 minutes?
import logging from a.x.models import X from a.x.management.commands.syncx \ import Command as SyncCommand from a.x.adapter_classes import ADAPTER_CLASSES LOGGER = logging.getLogger(__name__) def logger_function(code): if not X.objects.filter(code=code).exists(): X.objects.create(code=code) LOGGER.info(f"{X} created") args = [] kwargs = {'x_code': code, 'class': False, 'database': 'default'} try: LOGGER.info(f"Starting syncx command for {code}") #or this command needs to be run just 5 minutes for every key SyncCommand().handle(*args, **kwargs) LOGGER.info(f"There is no error for {code}") except Exception as error: with open("logger.txt", "a") as file: file.write(f"{code}'s error is : {error}") LOGGER.info(f"Logging error about {code}\n") def run(): for key in ADAPTER_CLASSES.keys(): #this function needs to be run just 5 minutes for every key logger_function(key) My logger_function needs to be run for 5 minutes. Is there any timer decorator or thread destroyer with timer ? How can I do this. My for loop is shifting in keys and sending to logger function , if there any problem for try except block its okey , but if everything right for my SyncCommand it can take a many hours, bu i just want to logging errors in first 5 minutes.