Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pytest django TestCase give strange failures
I have a very simple class which fails on any version of pytest>3.0.0. from django.test import TestCase class TestTestCase(TestCase): """Tests for the TestCase class.""" def test_that_client_exists(self): """Assert that the class has a client.""" assert self.client I am using the following version: platform Linux Python 2.7.11 pytest-3.3.1 py-1.5.2 pluggy-0.6.0 django-2.9.2 And I get the following error: self = <myproject.tests.test_test_case.TestTestCase testMethod=test_that_client_exists> def test_that_client_exists(self): """Assert that the class has a client.""" > assert self.client E AttributeError: 'TestTestCase' object has no attribute 'client' However, if I downgrade to pytest==3.0.0 and pluggy-0.3.1, the code executes without any issues. My question is this, what is going on? What could be causing this? It is as if pytest is calling the test_that_client_exists but is not calling __call__ which calls _pre_setup. Has anyone seen anything like this? -
Django Form: NoReverseMatch
Getting an error: NoReverseMatch: Reverse for 'post_new' not found. 'post_new' is not a valid view function or pattern name. my form in base.html: > <form action="{% url 'post_new' %}" method="post"> > {% csrf_token %} > Name:<br> > <input type="text" name="name"><br> > Text:<br> > <input type="text" name="text"> > <input type="submit" value="Submit"> </form> views.py: def post_new(request): posts = Post.objects.all() name = request.POST['name'] print(name) return render(request, 'blog/base.html', {'posts': posts}) urls.py: urlpatterns = [ url(r'^$', views.base), url(r'^post_new/$', views.post_new, name='post_new'), ] -
Pass JSON data in Django context
Normally, if I want to return JSON data from a Django view, I can use a JsonResponse like so: from django.http import JsonResponse def my_view(request): return JsonResponse({'my_key': 'my_value'}) That data is sent to the frontend as a JavaScript object that I can immediately use. I'd like that same ease of use added to the context of a view, like so: class WebsiteView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['my_var'] = {'my_key': 'my_value'} return context However, rendering the template with {{ my_var }} gives: {&quot;my_key&quot;: &quot;my_value&quot;} Ultimately, what I want is for {{ my_var }} to return the plain string rather than the HTML encoded version: {"my_key": "my_value"} This way, I can easily load it into a JavaScript object with JSON.parse('{{ my_var }}'). I know that one way to achieve this is by manually unescaping the HTML entities, but I was wondering if there was a better way to do this. -
Setting up Ubuntu Server 16.04 with Apache to run Django
I have Ubuntu Server 16.04 running Achape. I am trying to get Apache to run Django. So far I have created a project in Django and can get it to run on port 80 by using the command "sudo python3 manage.py runserver 192.168.1.230:80". I would like to have Apache setup to run Django so I do not have to do this command. I have looked for 6 hours now and tried 10+ different ways to do this and can't get it to work. I usually end up getting a 500 Internal Error. I have changed the apache2.conf file, and 000-default.conf file. What should I do? -
troubles modules Django mas os - pycharm
dears. I'm new in python/django. I just try Install and configure an enviroment from my ubuntu to my mac os. I've installed Python 3.6 , Django 2.0 and i'm using pycharm. When I tried run with "runserver", I got this error: /Users/fabio/Documents/projects/lib/python3.6/site-packages/magic/__pycache__/_cffi__xa0d5132dx54cebdac.c:208:10: fatal error: 'magic.h' file not found #include <magic.h> ^~~~~~~~~ 1 error generated. /Users/fabio/Documents/projects/lib/python3.6/site-packages/magic/__pycache__/_cffi__xa0d5132dx54cebdac.c:208:10: fatal error: 'magic.h' file not found #include <magic.h> ^~~~~~~~~ 1 error generated. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10ea68268> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/unixccompiler.py", line 118, in _compile extra_postargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/ccompiler.py", line 909, in spawn spawn(cmd, dry_run=self.dry_run) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/spawn.py", line 36, in spawn _spawn_posix(cmd, search_path, dry_run=dry_run) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/spawn.py", line 159, in _spawn_posix % (cmd, exit_status)) distutils.errors.DistutilsExecError: command '/usr/bin/clang' failed with exit status 1 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/fabio/Documents/projects/lib/python3.6/site-packages/cffi/ffiplatform.py", line 55, in _build dist.run_command('build_ext') File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/dist.py", line 974, in run_command cmd_obj.run() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/command/build_ext.py", line 339, in run self.build_extensions() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/command/build_ext.py", line 448, in build_extensions self._build_extensions_serial() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/command/build_ext.py", line 473, in _build_extensions_serial self.build_extension(ext) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/command/build_ext.py", line 533, in build_extension depends=ext.depends) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/ccompiler.py", line 574, in compile self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/unixccompiler.py", line 120, in _compile raise CompileError(msg) distutils.errors.CompileError: … -
Django model history by date and datetime
Assume I have model like this: class Account(models.Model): balance = models.IntegerField() debt = models.IntegerField() history = HistoricalRecords() I'm using django-simple-history to get instance of the model as it would have existed at the provided date and time: inst = Account.history.as_of(datetime.datetime.now().date) It's working fine, but I want to get instance where debt field is represented as it would have existed at the provided date and time, and then debt field will be most recent of that date. I don't know if this is possible, didn't find anything about that. -
Prefetch the contents of files referenced by the ORM
My situation is that I'm using the Django ORM to fetch a list of objects, each with a file. I then need to access the file-data for each and every object in the list. We're hosting our files on S3, and it seems to take a long time every time I call f.read() I'm wondering, is there a way to pre-fetch the contents of the file, so that f.read() doesn't have to make another round-trip? Anything else I can do to speed this up? Any help is appreciated, and let me know if there is more I can clarify. -
How to update a Wagtail Page
I am using a wagtail_hook to update a Page object and am running into trouble. More specifically, when an end-user hits the "Save draft" button from the browser I want the following code to fire. The purpose of this code is to change the knowledge_base_id dynamically, based on the results of the conditional statements listed below. def sync_knowledge_base_page_with_zendesk2(request, page): if isinstance(page, ContentPage): page_instance = ContentPage.objects.get(pk=page.pk) pageJsonHolder = page_instance.get_latest_revision().content_json content = json.loads(pageJsonHolder) print("content at the start = ") print(content['knowledge_base_id']) kb_id_revision = content['knowledge_base_id'] kb_active_revision = content['kb_active'] if kb_active_revision == "T": if kb_id_revision == 0: print("create the article") content['knowledge_base_id'] = 456 #page_instance.knowledge_base_id = 456 # change this API call else: print("update the article") elif kb_id_revision != 0: print("delete the article") content['knowledge_base_id'] = 0 #page_instance.knowledge_base_id = 0 print("content at the end = ") print(content['knowledge_base_id']) #page_instance.save_revision().publish So when the hook code fires, it updates the draft with all the info EXCEPT the knowledge_base_id. However when I change the knowledge_base_id like this (seen commented out above) page_instance.knowledge_base_id = 0 And save it like this (also seen commented out above) page_instance.save_revision().publish() It saves the updated knowledge_base_id BUT skips over the other revisions. In short, what the heck am I doing wrong. Thanks in advance for the assist. … -
Retrieving values from backwards relationship as a list of integers instead of list of tuples?
Right now I have a column named 'Value' in my 'Data' model, which has a ForeignKey from 'FOO' model: class FOO(models.Model): label = models.CharField(max_length=10, primary_key=True) ... class Data(models.Model): label = models.ForeignKey(Tickers, on_delete=models.CASCADE) Volume = models.FloatField(default=0) ... I'm fetching related objects as follows: v = FOO.objects.get(pk='something') vol = v.foo_set.values_list('Volume') and a get a list of tuples, which, afterwards, I have to convert to list integers with list comprehension. Is there a more elegant way to get a list of integers directly? Thanks -
Token based authentication not using JWT?
Whats a good practice for developing token based authentication for my app not using JWT? -
How to deserialize nested serializers with Django Rest Framework
i have in models.py class Variants(Model): class Meta: db_table = 'variants' id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=False, null=False) client = models.ForeignKey(Client, on_delete=models.CASCADE, null=False, blank=False) created_at = models.DateField(auto_created=True, default=now, blank=True) updated_at = models.DateField(auto_now=True, null=True, blank=True) and class VariantOptions(Model): class Meta: db_table = 'variant_options' id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=False, null=False) variant = models.ForeignKey(Variants, on_delete=models.CASCADE, null=False, blank=False) created_at = models.DateField(auto_created=True, default=now, blank=True) updated_at = models.DateField(auto_now=True, null=True, blank=True) and in serializers.py class VariantOptionsSerializer(serializers.ModelSerializer): class Meta: model = models.VariantOptions fields = ['name'] class VariantsSerializer(serializers.ModelSerializer): options = VariantOptionsSerializer(many=True) class Meta: model = models.Variants fields = ['name','client','options'] def create(self, validated_data): options_data = validated_data.pop('options') variant = models.Variants.objects.create(**validated_data) for option_data in options_data: models.VariantOptions.objects.create(variant=variant, **option_data) return variant and my view class VariantsCreate(APIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = serializers.VariantsSerializer def post(self, request, format=None): serializer = serializers.VariantsSerializer(data=request.data) if serializer.is_valid(): saved = serializer.save() return Response(serializer.data) ==> serializer.data gives error return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) i have this error Got AttributeError when attempting to get a value for field options on serializer VariantsSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Variants instance. Original exception text was: 'Variants' object has no attribute 'options'. but the data has already been validated by the call to is_valid() … -
django and mysql - select distinct column with filters
suppose, I have a table with 3 columns: create table t1 (c1 int, c2 int, c3 int) i want to return a list of distinct values of c2 after applying filters on c1, c2 and c3 at the SQL level, I can do this easily: select distinct (c1) from t1 where c1=10 and c2>30 and c3 in (1,2,3) what is the best way to do so in django? I don't want to use .raw SQL since the filters are dynamic and it will be a nightmare to build the appropriate SQL query (there are more than 30 columns in the real table). is there a way to create a queryset with filters against all the table colums that will return only sub columns of the table? if so the distinct() would have worked Thanks for any tip Eyal -
Error: No UserDetails model is Created
I'm trying to reduce the image size before upload. I'm using default User model given by django & linking it to another model just to add few more things to the user profile. This is how models.py looks like, class UserDetails(models.Model): user = models.OneToOneField(User) profile = models.ImageField(upload_to='profile_image', blank=True) ... def save(self, *args, **kwargs): img = Image.open(self.profile) resize = img.resize((240, 240), Image.ANTIALIAS) new_image = BytesIO() resize.save(new_image, format=img.format) temp_name = self.profile.name self.profile.save(temp_name, content=ContentFile(new_image.getvalue()), save=False) super(UserDetails, self).save(*args, **kwargs) Problem is that when I'm signing up with fields username, first_name & password, it's not creating a UserDetails model along with that user. So, if I try to visit any user's profile it gives an error, no UserDetails model is present. If I remove the image compression code from the model & sign up again everything starts working perfectly fine. How can we fix that? Thank You . . . -
Django multiple databases - correct router class
I would like to use two databases in my application: local database external database in the first one I want to save all django tables , e.g auth_group To do this I tried to use router class, but unsuccessfully - it doesn't work. Below you can find my code Django 1.11 setings file: DATABASE_ROUTERS = ['mainApp.models.DefaultDBRouter','subfolder.newApp.models.testDBRouter',] models.py - main app - I want to use default DB for this model from __future__ import unicode_literals from django.db import models class list_a( models.Model ): region = models.CharField(max_length=50, verbose_name="Region") country = models.CharField(max_length=50, verbose_name="Country") def __unicode__(self): return str( self.country ) class DefaultDBRouter(object): """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Reads go to a default. """ return "default" def db_for_write(self, model, **hints): """ Writes always go to default. """ return 'default' def allow_relation(self, obj1, obj2, **hints): """ Relations between objects are allowed if both objects are in the default. """ db_list = ('default') if obj1._state.db in db_list and obj2._state.db in db_list: return True return None def allow_migrate(self, db, app_label, model=None, **hints): """ All non-micro-management models end up in this pool. """ return True models.py - test app - I want to use … -
Is possible to monitor a celery task in a django view without block the server
I have a long running task that I need to decouple from my normal django app. Is called from several clients, and wonder if is possible to give them the ilusion of a synchronous call, where the server take the job of monitor the job and return back when it finish. This mean, that I only need to offload the server and not need to worry about blocking the clients (this is already solved). @task def sync(): # A long process here... So, in my view is possible to do something like: def sync_database(request): while timeout(60): #Monitor task, if error or result: sleep(1) return sync.result without kill the performance? -
Why a call to a celery task block forever?
I follow the tutorial at http://docs.celeryproject.org/en/master/django/first-steps-with-django.html from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cobros.settings') app = Celery('cobros') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() # Settings CELERY_APP="cobros" CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE and call my first job: @task def add(x, y): logger.info("Sum ", x, y) return x + y def syncClientAsync(): baseDir = getBaseDir(str(cobrador.id)) print("Delay...") return add.delay(4, 4) #No work return add.delay(4, 4).get(timeout=1) #No work When I run the code python get stuck/blocked forever. Redis and Celery are running and not report any error or problem. -
Queryset contentype show fields name and values in template table
I got a view that receives a model and field the user passes via post (existing model and field inside the app of course) and makes a queryset filter on it, then i need to show in my template that result in a table (name fields must be the column headers) and their respective values. This what i got so far trying to serialize the queryset result in order to make it easier to show in template: Views.py: from django.contrib.contenttypes.models import ContentType class CommitteeReport(BaseView): template_name = 'committee/committee_report.html' def post(self, request, **kwargs): myfield = request.POST['field'].lower() my_model = request.POST['model'].lower() queryset_obj = ContentType.objects.get(model = my_model).model_class().objects.filter(**{myfield:True}) return render(request, self.template_name,{ 'requirements': queryset_obj, }) And my template: <div class="tab-pane active" id="tab_1"> <table class="datatable table table-striped table-hover" cellspacing="0"> <thead> <tr> {% for key in requirements %} <th>{{ key.fields }}</th> {% endfor %} </tr> </thead> <tbody> {% for item in requirements %} <tr>{{ item.value }}</tr> {% endfor %} </tbody> </table> </div> Thing is, i don't get result or if i change the tag inside the termplate, i get the objects dictionary for every row. Any idea of how to achieve what i need ?, thanks in advance. -
NameError: name 'reload' is not defined python 3.6.4
After installing Xadmin, i encounter some problems. And there is my error details: [File "C:\Users\Harry\PycharmProjects\mxonline\lib\site-packages\xadmin\sites.py", line 9, in <module> reload(sys) NameError: name 'reload' is not defined]1 i've tried import importlib importlib.reload(sys) but it still doesn't work. i use python 3.6.4 -
Aldryn NewsBlog Designing a Template
The documentation for aldryn news-blog is very vague and i don't understand how to use articles. I'm trying to make a section page where each instance of an article creates a panel with the article's featured image and the name as the footer which will also be a button. Each article will create a new column. When there is 4 articles in a column, a new row will be started for the next article. I constantly receive the following errors when I adjust. Could not parse the remainder: '(loop.index,4)' from 'divisibleby(loop.index,4)' or for {% if loop.index|divisibleby 4 %} divisibleby requires 2 arguments, 1 provided How would I go about fixing this forloop and having it display. Django V- 1.8 {% load i18n staticfiles thumbnail cms_tags apphooks_config_tags %} {% extends "base.html" %} <div class="container"> <div class="row"> {% for article in article_list %} <div class="col-4"> <div class="panel panel-default"> <div class=panel-body> <img src="{% thumbnail article.featured_image 800x450 crop subject_location=article.featured_image.subject_location %}" alt="{{ article.featured_image.alt }}"> </div> <div class=panel-footer> <a href="{{ article.get_absolute_url }}" class="btn btn-light btn-lg btn-block aria-pressed=False label={{ article.slug_source.fieldname }}"> </div> {% if loop.index|divisiableby 4 %} </div> <div class="row"> {% endif %} {% endfor%} </div> </div> -
Django-Leaflet show custom layers on a form
I have two models, one that shows a marker(PointField) and one that generates PolygonFields. In my views, i can perfectly show all the data on a map. However, I would like to show the same data when creating a new geometry. Question is, how do I overlay the marker and the polygonField data as a layer in a form. models class MyPolygon(gis_models.Model): geom = gis_models.PolygonField() objects = gis_models.GeoManager() class MyPoints(gis_models.Model): geom = gis_models.PolygonField() objects = gis_models.GeoManager() views class PolygonCreateView(CreateView): form_class = PolygonForm template_name = 'applications/create_polygon.html' success_url = '/applications/polygon' def view_polygon(request): polygons= ReserveAirspace.objects.all() return render(request, 'applications/polygons.html',{'polygons':polygons}) same applies to the points. html {{form.geom}} How do i add all the existing polygons and points to the form field above in the template??? -
Django ManyToManyField that only works one way
I have my models set up as follows: class Product(models.Model): related_products = models.ManyToManyField('self', blank=True, related_name='related_products') As you can see, the relation is to itself. Now, lets say I have 3 products in my database: A, B, C. Product B's related product is Product C. Now, if I add Product B to the related product for product A, then Product B's related product changes from C to A, C. I don't want this, I want the change to only go one way. If I add B to A's related products, then B's related product won't change. Hope this is clear. How can I do this? Thanks! -
how o make django-autocomplete light return selected text not id
I have a simple form which lets a user select his country, state and district and redisplays the selected data. Everything works as expected apart from the fact that what is displayed is not the "text" but "ids" of the selected data. Expectation: You belong to India, Punjab, Jalandhar. Me too. ;) Output: You belong to 1, 2, 4. Me too. ;) # my form class MyInfoForm(forms.Form): country = forms.ModelChoiceField( queryset=Country.objects.all(), widget=autocomplete.ListSelect2( url='country-autocomplete', ) ) state = forms.ModelChoiceField( queryset=State.objects.all(), widget=autocomplete.ListSelect2( url='state-autocomplete', forward=(forward.Field('country'),) ) ) district = forms.ModelChoiceField( queryset=District.objects.all(), widget=autocomplete.ListSelect2( url='district-autocomplete', forward=(forward.Field('state'),) ) ) # my view which handles MyInfoForm class CountryView(FormView): template_name = 'home.html' form_class = MyInfoForm success_url = '/thanks/' def form_valid(self, form): print("Request :", self.request.POST) country = self.request.POST["country"] state = self.request.POST["state"] district = self.request.POST["district"] msg = "You belong to {country}, {state}, {district}. Me too. ;)".format( country=country, state=state, district=district) return HttpResponse(msg) # other auto-complete views (similar to official tutorials) class CountryAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Country.objects.none() qs = Country.objects.all() if self.q: qs = qs.filter(country_name__istartswith=self.q) return qs class StateAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated(): return State.objects.none() qs = State.objects.all() country = self.forwarded.get('country', None) if country: qs = … -
Implementing the custom permissions from the Django REST framework tutorial
I'm following the Django REST framework tutorial (part 4) but I'm observing a discrepancy between the behavior of my API and what is expected according to the tutorial. Here is my project-level urls.py: from django.contrib import admin from django.urls import path, include from rest_framework.urlpatterns import format_suffix_patterns from snippets import views urlpatterns = [ path('admin/', admin.site.urls), path('users/', views.UserList.as_view()), path('users/<int:pk>/', views.UserDetail.as_view()), path('', include('snippets.urls')) ] urlpatterns += [ path('api-auth/', include('rest_framework.urls')) ] and here is the included snippets.urls: from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from snippets import views urlpatterns = [ path('snippets/', views.SnippetList.as_view()), path('snippets/<int:pk>/', views.SnippetDetail.as_view()) ] urlpatterns = format_suffix_patterns(urlpatterns) I've created a permissions.py with a custom permission class IsOwnerOrReadOnly: from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: return True # Write permissions are only allowed to the owner of the snippet. return obj.owner == request.user and I've added this class to permission_classes in the SnippetDetail class in views.py: from django.contrib.auth.models import User from snippets.models import Snippet from snippets.serializers import SnippetSerializer, UserSerializer from rest_framework … -
How to deserialize data from multiple sources for one model using DRF?
I am transitioning some data over to use DRF. I have a POST endpoint that takes a JSON payload, parses relevant fields, and creates multiple objects out of that data. Each subsequent object created also relies on the previous object created (see example below). I am trying to figure out how to accomplish below, using DRF to deserialize data. It doesn't exactly have to be modeled like the code below, but I need the same end result. def job_start(request, plat_name="other", script_version="1"): a_product, created = Product.objects.get_or_create(name="Mobile") a_platform, created = Platform.objects.get_or_create(name=plat_name) tool, created = Tool.objects.get_or_create( product=a_product, platform=a_platform, url=jenkins_dump.url) job, created = Job.objects.get_or_create(name=jenkins_dump.job_name, tool=tool) job_in_progress, _ = Status.objects.get_or_create(name="IN_PROGRESS") start_time_raw = datetime.fromtimestamp(jenkins_dump.start_time / 1000) job_execution = JobExecution.objects.create(build_id=jenkins_dump.execution_number, job=job, time_start=start_time_raw, status=job_in_progress, pipeline_script_version=script_version) # what I want to do # serializer = ProductSerializer(request.data) # if serializer.is_valid(): # serializer.save() # serializer = ToolSerializer(request.data) # if serializer.is_valid(): # serializer.save() I'm wondering how I can serialize all these values and then when I create an object, append it to the serialized data, then pass that serialized data to the next object serializer, etc. -
Django. Comparing the model fields before saving for the admin panel
I'm new to Django and I have a question (Yes, yes, I was looking for and did't find ...). There are two models: class CounterDetail(models.Model): counter = models.ForeignKey(Counter, on_delete=models.CASCADE) date_placing = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=False) verifying_period_mounts = models.IntegerField(blank=False, null=False) and class Detail(models.Model): counterdetail = models.ForeignKey(CounterDetail, on_delete=models.CASCADE) date_last_verification = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=False) date_obxoda = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=False) How to implement the check when adding an entry to the second model through the admin panel: field date_obxoda = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=False)more then date_placing = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=False) from another model. Please give an example, thank you.