Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django unittests fixture loading error when using --parallel
I am working on a project that has a substantial amount of (Django) unit tests, total run-time about 10 minutes. We're hoping to use --parallel to speed things up a bit, without having to chop op the test suite ourselves. I am running into a fixture problem when running --parallel. Running without --parallel, or using lower values like 1 or 2 work fine. As soon as I chose 3 or higher (--parallel 3), tests start failing with an error about not being able to load the fixture because a column doesn't exist. On consecutive runs, it's different tests failing, sometimes more, sometimes less. ./manage.py test dojo.unittests --pattern="test_a*.py" -v 3 --parallel 4 ERROR: test_full_scan (dojo.unittests.test_apiv2_scan_import_options.ScanImportOptionsTest) Import the ZAP scan with a test file. ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/valentijn/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/valentijn/venv/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/home/valentijn/venv/lib/python3.8/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/home/valentijn/venv/lib/python3.8/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/home/valentijn/venv/lib/python3.8/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'delete_duplicates' in 'field list'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.8/unittest/suite.py", line 163, in _handleClassSetUp … -
Reverse for 'forum_post' with no arguments not found. 1 pattern(s) tried: ['forumpost/(?P<pk>[0-9]+)/$'] How can I do to solve the problem?
I would like to link this function to the link in the base Templates, but I have this error, what solution could be found? Should I use the Reverse function? my views def forumPostList(request, pk): conversation = get_object_or_404(Conversation, pk=pk) form_response = PostModelForm() posts_conversation = Post.objects.filter(conversation=conversation) context = {"conversation": conversation, "posts_conversation": posts_conversation, "form_response": form_response } return render(request, "account/forum_post.html", context) <!-- begin snippet: js hide: false console: true babel: false --> {% extends 'base.html' %} {% block content %} <h1>Received messages:</h1> <hr> <br> {% for post in posts_conversation %} <h3>{{ conversation.title }}</h3> <p>Posts: {{ post.author_post.posts.count }}</p> <p>Posts: {{ post.author_post.username }}</p> {% endfor %} {% endblock content %} my base <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url 'forum_post' %}">forum_post</a> </li> -
Django change argument value of a custom filter in template
currently i have 2 filters, classroom(recinto) and course(carrera) i want to get only the courses that are assigned to the selected classroom, for that i got models called "CarreraRecinto". Models: class Recinto(models.Model): codigo = models.CharField(max_length=10, unique=True) nombre = models.CharField(max_length=300) class Meta: ordering = ['codigo'] def __str__(self): return f"{self.codigo} - {self.nombre}" class Carrera(models.Model): codigo = models.CharField(max_length=5, unique=True) nombre = models.CharField(max_length=300) def __str__(self): return f"{self.codigo} - {self.nombre}" class CarreraRecinto(models.Model): carrera = models.ForeignKey(Carrera, on_delete=models.CASCADE) recinto = models.ForeignKey(Recinto, on_delete=models.CASCADE) Views: class EditorInventarioView(LoginRequiredMixin, TemplateView): template_name = "pages/editor-inventario/estandar.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["recintos"] = Recinto.objects.values("id", "codigo", "nombre") context["carreras"] = Carrera.objects.values("id", "codigo", "nombre") return context editor_inventario_view = EditorInventarioView.as_view() Filter: @register.filter(name="fc") def filter_carreras(carrera, recinto): qs = Carrera.objects.filter(carrerarecinto__recinto=recinto) return qs template: <div class="col-lg-4"> <label for="laboratorioSeleccionado"> Selecciona Ficha FER: </label> <select class="form-control" id="laboratorioSeleccionado" style="width: 100%;"> {% for recinto in recintos%} <option value="{{ recinto.id }}"> {{ recinto.codigo }}_{{ recinto.nombre }}</option> {% endfor %} </select> </div> <div class="col-lg-3"> <label for="carreraSeleccionada"> Selecciona carrera: </label> <select class="form-control" id="carreraSeleccionada" style="width: 100%;"> {% for carrera in carreras|fc:17 %} <option value="{{ carrera.id }}">{{ carrera.nombre }}</option> {% endfor %} </select> </div> what i need to do, is to change in Template the value "17" from the fc(filter_carreras) based on the selected value from the previous filter … -
Django: store variables in database and pass them between different modules
In my model I'm trying to calculate my user age and create for them an id code and I want this information to be saved in my database, but "age" and "id_code" fields are missing in my database. If I change the name of the function age and id variable are not computed at all. **accounts.models** class UserInformation(models.Model): name = models.CharField(max_length=250) lastname = models.CharField(max_length=250) phone = models.CharField(max_length=250) birthday = models.DateField() age = models.CharField(max_length=2) id = models.CharField(max_length=250) def __str__(self): self.name + '_' + self.lastname + '_' + str(self.birthday.year) def age(self): age = datetime.now().year - int(self.birthdate.year) return age def id_code(self): id_code = self.name + '_' + self.lastname + '_' + int(self.birthday.year) return id_code **accounts.forms.py** class UserInformationForm(forms.ModelForm): class Meta: model = UserInformation fields = ('name', 'lastname', 'birthday', 'phone') **accounts.views.py** def add_information(request): if request.method == 'POST': form = UserInformationForm(request.POST, request.FILES) if form.is_valid(): form.instance.user = request.user form.save() return redirect('home') else: form = UserInformationForm() return render(request, 'add_information.html', {'form': form}) I've also an another models file in another app where I've two quiz for my user. I'd like to save in my database with answers also the id code created in the other models file and use the userinformation answer to create the string name to use … -
deploy django app on aws lightsail containers
WHAT I'M TRYING TO DO AND WHAT I DID i'm trying to deploy a django app through a container in amazon lightsail containers. i've found several tutorial on how to do this but some of them seem to overcomplicate things to such a way that the files became unreadable. in particular everybody start using some complex database but i should be fine using the standard db.sqlite3 of django. finally i stumbled upon this tutorial that seems clear enough. i thought i could simply skip the Postgres part and use the rest of it. it worked. MY CONFIGURATION These are my files that manage the containers. i have multicontainer setup. nginx act as reverse proxy that get all the request and serve static file and media. The other container is the django app. I use docker-compose to build and start the images. Dockerfiles this is the Dockerfile in my app: # pull official base image FROM python:3.9.6 # set work directory its an absolute path WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy project COPY . . and this … -
Cannot add new post via fetch
i'm trying to send new post via fetch, but every time i get these two errors(visible in an image). Could you tell me why i'm getting this errors? fetch('/posts', { method: 'POST', body: JSON.stringify({ body: document.querySelector('#compose-body').value }) }) .then(response => response.json()) .then(result => { // Print result console.log(result); }); [errors] https://i.stack.imgur.com/7Lp2V.jpg -
Getting a type error at Articles/1/:get() got multiple values for argument 'id'
class Article_List(APIView): def get(self,request): articles = Article.objects.all() serializer = ArticleSerializer(articles, many=True) return Response(serializer.data) def post(self,request): serializer = ArticleSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # Bad Request class ArticleDetails(APIView): def get_objects(self, id): try: return Article.objects.get(id=id) except Article.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) def get(self, id): article = self.get_objects(id) serializer = ArticleSerializer(article) return Response(serializer.data) def put(self, request , id): article = self.get_objects(id) serializer = ArticleSerializer(article, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request,id): article = self.get_objects(id) article.delete() return Response(status=status.HTTP_204_NO_CONTENT) -
I want to retrieves all Post objects which have at least one followUser whose user=request.user
FieldError at /en/account/profile/follow_list/ Cannot resolve keyword 'followidf' into field. Choices are: author, author_id, This spanning can be as deep as you’d like. It works backwards, too. While it can be customized, by default you refer to a “reverse” relationship in a lookup using the lowercase name of the model. This example retrieves all Post objects which have at least one followUser whose user=request.user class Post(models.Model): title = models.CharField(max_length=250) excerpt = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) favourite = models.ManyToManyField( User, related_name='favouriteUser', default=None, blank=True) avatar = models.ImageField( upload_to=user_directory_path, default='users/avatar.png') bio = models.TextField(max_length=5500, blank=True) fullName = models.CharField(max_length=221, blank=True, default=rand_slug(5) ) dr = models.BooleanField( default=False ) slug = models.SlugField(max_length=250, unique=True, blank=True, default=rand_slug(8)) class followUser(models.Model): folPr = models.ForeignKey(Profile, related_name='followfp',on_delete=models.CASCADE, default=None, blank=True) follUser = models.ForeignKey(User, related_name='followidf',on_delete=models.CASCADE, default=None, blank=True) vote = models.BooleanField(default=True) publish = models.DateTimeField(default=timezone.now) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.follUser.username @ login_required def follow_list(request): new2 = Post.objects.filter( followidf__followidf=request.user ) return render(request, 'accounts/follow_list.html', {'new': new2 } ) -
AttributeError at /create_order/4 in Django
I am making inline formsets for create new products in each client, but when I try to save it throw me this error views.py: Here im focus in the fuction "createOrder" for create the orders of customers from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * from django.forms import inlineformset_factory from .forms import OrderForm # Create your views here. def home(request): orders_value = Order.objects.all() customer_value = Customer.objects.all() total_orders_value = orders_value.count() total_customers_value = customer_value.count() pending_value = orders_value.filter(status='Pending').count() delivered_value = orders_value.filter(status='Delivered').count() context = {'orders_key': orders_value, 'customer_key': customer_value, 'total_orders_key':total_orders_value, 'pending_key': pending_value, 'delivered_key': delivered_value} return render (request, 'accounts/dashboard.html', context) def products(request): products_value = Product.objects.all() return render (request, 'accounts/products.html', {'products_key': products_value}) def customer(request, pk_test): customer_value = Customer.objects.get(id=pk_test) orders_value = customer_value.order_set.all() orders_value_count = orders_value.count() myFilter_value = OrderFilter() context = {'customer_key':customer_value, 'orders_key': orders_value, 'orders_key_count': orders_value_count, 'myFilter_key':myFilter_value} return render (request, 'accounts/customer.html', context) def createOrder(request, pk): OrderFormSet= inlineformset_factory(Customer, Order, fields=('product', 'status'), extra=10) customer = Customer.objects.get(id=pk) form_set_value= OrderFormSet(queryset=Order.objects.none() ,instance=customer) if request.method == 'POST': form_set_value= OrderFormSet(request.POST, instance=customer) if form_set_value.is_valid: form_set_value.save() return redirect('/') context = {'form_set_key':form_set_value} return render(request, 'accounts/order_form.html', context) def updateOrder(request, pk): order = Order.objects.get(id=pk) form_value = OrderForm(instance=order) if request.method == 'POST': form_value = OrderForm(request.POST, instance=order) if form_value.is_valid: form_value.save() return redirect('/') context = {'form_key':form_value} return render(request, 'accounts/order_form.html', … -
Django: An alternative to using composite keys
I have the following 2 tables. Discount: id, supplier_id, buyer_id, discount_rate (with supplier_id and buyer_id being unique_together) Product: id, product_name, supplier_id, buyer_id, price Just to explain why I have a buyer_id in my product table: A product is offered to a specific buyer only. So at the time of loading the products into my Product table, I already know who the potential buyer will be. Discounts are not product-specific but rather a supplier would offer a discount specific to the buyer. The discount_rate can change therefore I cannot capture the rate in the product table. So when the user/buyer views a product, I want to get the discount_rate offered by suppliers to that specific buyer and calculate the discounted price. I previously did this in ASP.NET by making the buyer_id and supplier_id composite keys and using that as a foreign key. Since composite keys are not available in Django, how can I get the discount which applies to the buyer/supplier relationship? I can change the database design, any suggestions are welcome. -
How to get data from aa website inside an I frame
Basically, my intention is to scrape an ecommerce website and when the checkout button is clicked in the cart and get the items price and name and images if evailable. I've looked at iframe, but I think it might not work because of same site policy, So I'm asking if anyone has done this before and what's a good method of implementing this. If there is any alternative I would like that, as I wouldn't want to be on the wrong side of the law. -
Remote Postgresql is very slow
I run .py files using Django ORM, that connected to Postgresql server on another server. Both servers working on Ubuntu 20.04 when i run the same file it takes the following time: 2-3 seconds on server with postgresql 8-12 seconds on another server. I tried: Turn off firewall on both servers (sudo ufw disable) Change postgres configs and then restart postgres server Use pgBouncer I checked internet speed on the servers and its normal This is postgresql.conf # Generated by PGConfig 2.0 beta ## http://pgconfig.org # Memory Configuration shared_buffers = 2GB effective_cache_size = 6GB work_mem = 41MB maintenance_work_mem = 512MB # Checkpoint Related Configuration min_wal_size = 512MB max_wal_size = 2GB checkpoint_completion_target = 0.9 wal_buffers = 16MB # Network Related Configuration listen_addresses = '*' max_connections = 1000 # Storage Configuration random_page_cost = 1.1 effective_io_concurrency = 200 # Worker Processes max_worker_processes = 8 max_parallel_workers_per_gather = 4 max_parallel_workers = 8 # Logging configuration for pgbadger logging_collector = on log_checkpoints = on log_connections = on log_disconnections = on log_lock_waits = on log_temp_files = 0 lc_messages = 'C' # Adjust the minimum time to collect data log_min_duration_statement = '10s' log_autovacuum_min_duration = 0 # 'csvlog' format configuration log_destination = 'csvlog' In pg_hba i just insert 1 … -
No: 'noindex' detected in 'X-Robots-Tag' http header
I have this problem with my sitemap No: 'noindex' detected in 'X-Robots-Tag' http header, and I think this is why my sitemap show "Sitemap could not be read" Does anyone has an idea how to solve it. I am using Django this the URL of my sitemap https://www.freeconvert.tk/sitemap.xml #Screenshots https://i.stack.imgur.com/1Z7yF.png https://i.stack.imgur.com/vfs9a.png https://i.stack.imgur.com/GekJU.png #sitemaps.py from convert.models import Snippet from django import http from django.urls import reverse from django.contrib import sitemaps from .models import Snippet class StaticViewsSitemap(sitemaps.Sitemap): priority = 1.0 changefreq = "daily" def items(self): return [ 'home', ] def location(self, items): return reverse(items) class SnippetSitemap(sitemaps.Sitemap): priority = 1.0 changefreq = "daily" def items(self): return Snippet.objects.all().order_by('id') -
Django - pass value from html template to python function
I am trying to spin first Django project and I am struggling how to pass value to python function from html. Basically, I have 1 placeholder with 3 buttons next to it. I have file.html in templates. <form method="POST" action=""> {% csrf_token %} <input type="text" name="name_id" placeholder="placeholder value"/> <input type="submit" value="Value 1"/> <input type="submit" value="Value 2"/> <input type="submit" value="Value 3"/> </form> I am trying to pass placeholder value to views.py. In views.py I have 3 functions. I want to execute only one of them based on value. Value 1 from html triggers function 1 in views Value 2 from html triggers function 2 in views Value 3 from html triggers function 3 in views I am not sure how to handle urls.py All files are in same app/folder Any help is much appreciated. -
How to update Django models from another app?
I have a running Django server using MySQL.I want to modify its models from another python program. I came up with a few ideas. Directly insert data into MySQL (will this reflect on model objects?) Create a REST interface I'm unfamiliar with Django's ORM, what is the right approach? -
django test multiple testcases in for loop
I want to test register view in django project, so I build some fake test cases(self.correct_samples) after register successfully, it should redirect to home page which means the status code should be 302. from django.test import TestCase from django.urls.base import reverse class RegisterTests(TestCase): def setUp(self): url = reverse('account:register') self.response = self.client.get(url) self.correct_samples = ( ('testuser1@email.com', 'testuser', 'test112233', 'test112233'), ('fakeuser@email.com', 'fake123', 'fakeuser111', 'fakeuser111'), ('correct@email.com', 'Jack', 'myfavorite', 'myfavorite'), ('failemail', 'Jack', 'myfavorite', 'myfavorite'), # fail for purpose ) def test_register_form(self): for test_case in self.correct_samples: email, username, password1, password2 = test_case self.response = self.client.post(reverse('account:register'), data={ 'email': email, 'username': username, 'password1': password1, 'password2': password2, }) self.assertEqual(self.response.status_code, 302) self.assertRedirects( self.response, expected_url='/', status_code=302, target_status_code=200) The fourth data in self.correct_samples which is ('failemail', 'Jack', 'myfavorite', 'myfavorite') should be a fail case. but after python manage.py test. It passed. (env) C:\Users\User\myblog>python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). C:\Users\User\myblog\env\lib\site-packages\whitenoise\base.py:115: UserWarning: No directory at: C:\Users\User\myblog\staticfiles\ warnings.warn(u"No directory at: {}".format(root)) . ---------------------------------------------------------------------- Ran 1 test in 0.195s OK Destroying test database for alias 'default'... Here comes the tricky thing, it failed after switching order from fourth to first. from django.test import TestCase from django.urls.base import reverse class RegisterTests(TestCase): def setUp(self): ... self.correct_samples = … -
How to solve value error -cannot assign... in Django
I added a new row to my model that assigns the recent project to the page where I can turn on some charts but if I hit the save button I get this error message that I can't figure out why: ValueError at /mpa/project_details/1/ Cannot assign "'1'": "ProjectDetailsAdmin.projekt" must be a "Projekt" instance. views.py @user_passes_test(lambda u: u.is_superuser) def project_details(request, projekt_id): projekt = Projekt.objects.raw('SELECT projekt_id, id FROM stressz_profile WHERE stressz_profile.projekt_id=%s', [projekt_id]) projects_details = Profile.objects.filter(projekt_id=projekt_id) allprojects = Projekt.objects.all() ... lots of queries here context = { ... 'projekt': projekt, 'projects_details': projects_details, 'allprojects': allprojects, ... } if request.method == 'POST': projekt = request.POST.get('projekt') projekt_name = request.POST.get('projekt_name') r01 = request.POST.get('r01') szervkult_adm = ProjectDetailsAdmin(projekt=projekt, projekt_name=projekt_name r01=r01) szervkult_adm.save() return render(request, 'stressz/project_details.html', context) models.py class ProjectDetailsAdmin(models.Model): def __str__(self): return str(self.projekt_name) projekt = models.ForeignKey('Projekt', on_delete=models.CASCADE, default=False, null=True ) projekt_name = models.TextField(max_length=200, null=True ) r01 = models.IntegerField(null=True, blank=True, default=0) class Projekt(models.Model): def __str__(self): return str(self.projekt) projekt = models.TextField(max_length=150) html <div class="container bg-warning my-3">Válaszd ki projektet: <select class="form-select" id="projekt" name="projekt" aria-label=""> {% for i in allprojects %} <option>{{ i.id }}</option> {% endfor %} </select> </div> Thank you very much in advance! -
How to use __range in Django
class Order(models.Model): customer = models.ForeignKey('Customer' , on_delete=models.SET_NULL , null= True , blank = True) date_ordered = models.DateTimeField(auto_now_add = True) I have this in order model . Now I want to take order.objects.filter and take only data whose date_ordered is between , date_ordered and ( date_ordered + 7 days ) . Is this possible using __range or not ? -
How do I connect python web app with sql server and create a dynamic queries
I have a project where I have a SQL server with order records and customers records. And I need to create a web app that authenticates the user and then queries the SQL server for this customer's orders using a dynamic SQL query e.g select * from orders where customer_number = "User customer number that is authenticated" What is the best approach to dealing with this? Should I use Django or flask? This is like homework for school I thought it would be easy but I couldn't find anything on the web to approach this. This is how I got started: with a flask. I made a separate database to contain the information about authenticated users, such as their email address, customer number, and a login page. Any guidance will be appreciated. Thanks -
How can I add a field to a queryset and populate it within a loop?
I have a queryset foo that contains a couple thousand items. Now I would like to add a field bar to this queryset whose value depends on some logic embedded in a loop. So I want to iterate foo and enrich bar for each item. # Views.py def example(request): [..] # Create `Bar` field for queryset foo.annotate(bar='') # Iterate queryset for item in foo: [..] # logic that returns a string # Populate field 'bar' item.bar = 'example_string' However, it already breaks at foo.annotate(bar='') returning QuerySet.annotate() received non-expression(s): . -
Request get data yields none from a request sent from pc to django app
I have a django app with views file set up as def SomeView(response): if response.method == 'GET' data = response.GET.get("test") return HttpResponse(data) and another python file i am using to make requests to my local django app like import requests payload = {'test': 1} r = requests.get("127.0.0.1:8000" , data = payload) print(r.text) Basically i would like to return a http response based on the data sent through GET request so expected output is: 1 but the actual out i recieve is None Please guide me towards the correct way to do it. -
How to process multiple Objects at once (using Django)
I used Ajax to send data (list type -> ex: ['4', '6', '10', '11']) to 'study/add_teacher' url page. So, it was successful until I got the data from the page. In the next step, problem is not resolved, The data of request.POST.getlist obtained through Ajax are 'id' of Student model. So I want to add the currently logged in user name (request.user.first_name) to the teacher field of these objects. It looks like views.py needs to be edited, is there a way to process objects all at once? [urls.py] path('study/add_teacher/', views.add_teacher, name='add_teacher'), [views.py] def add_teacher(request): if request.method == 'POST': ids = request.POST.getlist('chkArray') ---> chkArrary = ['4', '6', '10', '11'] Student.objects.filter(id__in=ids).update(teacher=request.user.first_name) return HttpResponseRedirect(f'/research/supporting/') -
a different chat appearance/look for both side
I'm trying to implement a chat room with websockets, everything works fine but the problem is how can I differentiate the look for both sides, I want the current user to have a blue message background and other participants have different colors, for example black, how can I do that, any suggestions will be appreciated. Here is what I got And here’s what I want it to be -
Cannot resolve keyword 'author' into field
Here is the issue.I am trying to delete the tags related to my model. I can create them but whenever i try to use HTTP DELETE on ExampleModelTags, i face with the following issue. Error: Cannot resolve keyword 'author' into field. Choices are: id, examplemodel, examplemodel_id, tag, timestamp I can't understand what is the issue, i can create them so the algorithm works. The tags can connect to their parent model . But whenever i try to do HTTP DELETE on ExampleModelTags, i get that issue. Where is the problem that i don't see? Model.py class ExampleModelTag(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) tag = models.CharField(max_length=35,null=True,blank=True) examplemodel = models.ForeignKey(ExampleModel, on_delete=models.CASCADE,null=True,blank=True, related_name='examplemodeltags') timestamp = models.DateTimeField(auto_now_add=True) class ExampleModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE,null=True,related_name='examplemodels') examplemodel = models.CharField(unique=False,max_length=100,null=True,blank=True) timestamp = models.DateTimeField(unique=False,auto_now_add=True) Serializer.py class ExampleModelTagSerializer(serializers.ModelSerializer): class Meta: model = ExampleModelTag fields = ("id","examplemodel","tag","timestamp") def validate(self, attrs): attrs = super().validate(attrs) if attrs['examplemodel'].author.id != self.context['request'].user.pk: raise ValidationError('Unauthorized Request') return attrs class ExampleModelSerializer(serializers.ModelSerializer): examplemodeltags_set = ExampleModelTagSerializer(source='examplemodeltags',required=False,many=True) class Meta: model = ExampleModel fields = ("id","author","examplemodel","examplemodeltags_set","timestamp") def validate(self, attrs): attrs = super().validate(attrs) if attrs['author'].id != self.context['request'].user.pk: raise ValidationError('Unauthorized Request') return attrs -
trigger a function after a while django python
I use django for a project. Users can make exchanges. If one user places an order with another and the second user accepts. I would like that after 24 hours if the order is not processed by the seller it is canceled. How can I do this?