Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
All equal values created by Faker using Factory Boy
Using Factory Boy and Faker in a Django project, I notice that objects created using Factory Boy, and using Faker to create names (company names in this example) doesn't create a unique name for new objects. Main question: are we using Faker wrong when using it as a separate library (first example), or is there just something inherent about Factory Boy that prevents Faker from working correctly as a separate library, when used with Factory Boy? import factory ... from faker import Faker from faker.providers import company ... fake = Faker('nl_NL') fake.add_provider(company) class PolicyBrandFactory(factory.django.DjangoModelFactory): class Meta: model = PolicyBrand name = fake.company() Results in (Pycharm debugger screenshot): (the point being non-unique company names) In the Factory Boy documentation I read that they have a wrapper around Faker, and using that I do get unique results: import factory ... class PolicyBrandFactory(factory.django.DjangoModelFactory): class Meta: model = PolicyBrand name = factory.Faker('company', locale='nl_NL') And the result: -
ModelSerializer and ModelViewSet in django rest framework
In DRF, we can use create/retrieve/update/destroy/list methods in ModelViewSet to handle GET, POST, DELETE, PUT request. and there is another set of methods in ModelSerializer namely create and update methods. Under what condition should I faver methods in ModelSerializer over those in ModelViewSet and viceversa? -
Relation does not exist Django Postgres
I recently changed the database from sqlite3 to Postgres. My Django apps are running perfectly, but when I go to the admin page and click on my predicts model, it says ProgrammingError at /admin/Atlus/predicts/ relation "Atlus_predicts" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "Atlus_predicts" models.py from django.db import models from django import forms class predicts(models.Model): firstname =models.CharField(max_length=15) info = models.TextField() def __str__(self): return self.firstname Traceback Environment: Request Method: GET Request URL: http://localhost:8000/admin/Atlus/predicts/ Django Version: 2.2.5 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4', 'rest_framework', 'corsheaders', 'main', 'accounts', 'Atlus', 'Boomerang'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/vipul/anaconda3/envs/librus/lib/python3.8/site-packages/django/db/backends/utils.py" in _execute 84. return self.cursor.execute(sql, params) The above exception (relation "Atlus_predicts" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "Atlus_predicts" ^ ) was the direct cause of the following exception: File "/home/vipul/anaconda3/envs/librus/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/vipul/anaconda3/envs/librus/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/vipul/anaconda3/envs/librus/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/vipul/anaconda3/envs/librus/lib/python3.8/site-packages/django/contrib/admin/options.py" in wrapper 606. return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/vipul/anaconda3/envs/librus/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/home/vipul/anaconda3/envs/librus/lib/python3.8/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/home/vipul/anaconda3/envs/librus/lib/python3.8/site-packages/django/contrib/admin/sites.py" in inner … -
Django: Is it okay to generate session_key even when no user is logged in?
Hi just wanna ask: Is it a good practice to generate Django's session_key (sessionid cookie) manually, outside Django's authentication layer? I am implementing a post hit/page views and post comment mechanism, and I wanna use the sessionid to use for the session field in PostHit and PostComment models. Reason being, I don't wanna create an entire logic for generating custom-made session keys for this purpose since I think Django's session_key is pretty straightforward and is enough to cater the recording of web visitor sessions. But I suddenly thought maybe the sessionid is appropriate only for logged-in users and shouldn't be generated for unauthenticated visitors. If it is not good anyway, do you have any better ways to generate session keys for both logged-in and anonymous visitors? Much thanks! SAMPLE IMPLEMENTATION OF session_key: class APIDetail__Post(generics.RetrieveUpdateDestroyAPIView): queryset = Post.objects.all().order_by('-publish_date') serializer_class = PostSerializer lookup_field = 'slug' permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get_queryset(self): post_slug = self.request.resolver_match.kwargs['slug'] post = Post.objects.get(slug=post_slug) if post: if post.published and post.approved: if not self.request.session.session_key: self.request.session.create() if not PostHit.objects.filter(post=post, session=self.request.session.session_key): view = PostHit( post=post, ip=self.request.META['REMOTE_ADDR'], created=datetime.now(), session=self.request.session.session_key) view.save() else: if not PostHit.objects.filter(post=post, session=self.request.session.session_key): view = PostHit( post=post, ip=self.request.META['REMOTE_ADDR'], created=datetime.now(), session=self.request.session.session_key) view.save() return self.queryset -
How not to read database every time for count using cron job
There are lot of reviews on the product in my website. Whenever I access the product list page, I have to get all the number of review on all the items.(So bunch of database access and calculation overhead) The realtime synchonization of the number of reviews is not necessary. So to reduce latency, I decided to make cron, which works once a day, to count the reviews on the item and write it to external Json file for reading in the web. what I'm wondering is, Is it the nice(and common) way for achieving what I hope? (I hope - when I need the number of reviews on the item, avoid database access to reduce latency) How to implement this using cron job?(how to make external json file from postgresql using cron?) I'm using django and postgresql for the project. Thank you :) -
Django ORM query manytomanytofiled to output a list againist a dict key
I am going through the trouble query many to field these are my models class Choice(models.Model): choice_text = models.CharField( max_length=200 ) class Question(models.Model): title = models.CharField( max_length=100 ) choices = models.ManyToManyField( Choice, through='QuestionChoice' ) class QuestionChoice(models.Model): question = models.ForeignKey( Question, on_delete=models.CASCADE ) choice = models.ForeignKey( Choice, on_delete=models.CASCADE ) I am tring to get all the Question with its all choices My output should loook like this: [ { 'title': 'a quetion title', 'choices': [ {'id': 1, 'choice_text': 'a choice text example' }, {'id': 1, 'choice_text': 'another text example' }, ] }, { 'title': 'another quetion title', 'choices': [ {'id': 1, 'choice_text': 'a choice text example' }, {'id': 1, 'choice_text': 'another text example' }, ] }, ] I am not getting how to get the output above like this. I mean, all the choice will be in a list of under the respected dict key choice. If you closely look at my expected, you will get it. Can you anyone help me with how to get it done? I tried with like this below: Question.objects.all().values('title', 'choices') but it returns a repeated time like how many choices it has. -
Django - Import Export - Save Field Names from Excel
I have a model that looks like this: class ExcelData(models.Model): var1 = models.IntegerField() var2 = models.IntegerField() var3 = models.IntegerField() And an excel sheet with 3 columns(col1, col2, col3), I want to import. Is it possible to overwrite the field names of the model with the column names of the excel sheet? Thank you for any suggestions -
Validate POST request (Vue + DRF)
So here's expected flow of the request: The user creates a new Language via an html form. [√ ] Vue via axios will fire a POST request to drf. [√ ] Drf will validate the data from the POST request (see if the language name/id/etc already exists) [x] Create the new language if it passes the validation. [x] I'm currently stuck on #3. I tried putting this on my LanguageViewSet: def post(self, request): language = request.data.get('language') serializer = LanguageSerializer(data=language) if serializer.is_valid(raise_exception=True): language_saved = serializer.save() return Response({"success": "Language '{}' created successfully!".format(language_saved.name)}) However, this doesn't somewhat work and gets completely ignored since: I tried commenting the post function, but still if I call a POST request via axios on the LanguageViewSet it would still post. probably a built-in POST feature? If the function is there, notice I used language = request.data.get('language') which means on my axios, the name of my data to be sent should be language right? otherwise it would ignore the POST request. I used created_lang in axios, fired the POST req but still it posted without any errors as if it completely ignored my post function. If I tried posting a new language of which it's name is already … -
how to get all the network tab logs in django when <iframe> accessing other urls in background?
In my template page ,I have an iframe tag with src="some.html" ,that is acessing and sending data to some other site (url) in background.And i can see all such data in my browsers network tab,is there any django ,or js way.... to log those access to a particular url on the view page. -
Django LoginRequiredMixin
When I want to imitate the class LoginRequiredMixin to create a class, I found there was not a function named LoginRequiredMixin in the parent class AccessMixin. Why does not an error occur when the function executes? class LoginRequiredMixin(AccessMixin): """Verify that the current user is authenticated.""" def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated: return self.handle_no_permission() return super().dispatch(request, *args, **kwargs) -
Django development STATIC_URL returns 404 when changing url
When i'm in the index directory, all works good. When i click a link to a child page, the static files aren't found. When at localhost:8000/home all works fine. When i go to localhost:8000/home/about i get "GET /home/about/static/css/bootstrap.css HTTP/1.1" 404 3159 This logic really get's me confused. Can some one explain this behaviour. settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_root/') # STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_root/')] MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root/') urls.py if settings.DEBUG: # urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) views.py def index(request): return render(request, template_name='index.html') def about(request): return render(request, template_name='about.html') Views are very basic. One of my thoughts was maybe a diffrent HttpResponse would somehow affect it? -
Django create custom group perms?
i'm trying to make a sort of employee management site for stores inside a franchise so all managers can access the sight but i want them to only be able to see the employees for their store. i just cant seem to find how to add custom permissions to the groups to make it they can only see people and things from x store rather from all of them. is this something that is possible to pull off? class EmployeeAdmin(admin.ModelAdmin): list_display = ['firstname', 'lastname', 'slug', 'store', 'position', 'joined', 'dob', 'under18', 'student',] list_filter = ['store', 'joined', 'under18', 'position'] list_editable = [ 'store', 'position'] prepopulated_fields = {'slug': ('firstname',)} search_fields = ('firstname', 'lastname',) this is what i have and i want to be able to hide store from certain groups -
How to implement functionality like when we type '@' to any search box then only it shows the list of users?
I want to implement autocomplete search functionality in my Django project like in slack or in whatsapp we put @ and it shows the list of all users which are present in the group. My requirement is to implement this functionality in Django project. -
Keep indentation width django admin autocompletion and django-mptt
I manage to find a way to keep the django-mptt indentation with the django (2.2.8) admin autocompletion activated on the field: I rewrite the AutocompleteJsonView.get inside my admin.py ObjectAdmin: from django.http import Http404, JsonResponse from mptt.settings import DEFAULT_LEVEL_INDICATOR class ObjectAdmin(ImportExportModelAdmin): from django.contrib.admin.views.autocomplete import AutocompleteJsonView def get(self, request, *args, **kwargs): """ Return a JsonResponse with search results of the form: { results: [{id: "123" text: "foo"}], pagination: {more: true} } """ if not self.model_admin.get_search_fields(request): raise Http404( '%s must have search_fields for the autocomplete_view.' % type(self.model_admin).__name__ ) if not self.has_perm(request): return JsonResponse({'error': '403 Forbidden'}, status=403) self.term = request.GET.get('term', '') self.paginator_class = self.model_admin.paginator self.object_list = self.get_queryset() context = self.get_context_data() return JsonResponse({ 'results': [ {'id': str(obj.pk), 'text': str(DEFAULT_LEVEL_INDICATOR * obj.level) + ' ' +str(obj)} for obj in context['object_list'] ], 'pagination': {'more': context['page_obj'].has_next()}, }) AutocompleteJsonView.get = get So basically, inside JsonResponse, {'id': str(obj.pk), 'text': str(DEFAULT_LEVEL_INDICATOR * obj.level) + ' ' +str(obj)} Instead of just {'id': str(obj.pk), 'text': str(obj)} Is there a better way to do this? Thanks! -
What is the best way to upload a csv from local machine onto the backend (Using Angular for front-end and Django for backend)
I want the user to be able to upload a csv, and this (after some modification) gets stored in the back-end server. I was currently passing a POST request with the csv as a string. I think this may fail for very large csv's. What is a better way to do it? -
uwsgi override django log
django log settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(thread)d %(module)s %(funcName)s %(lineno)d %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'file_django': { 'class': 'logging.handlers.TimedRotatingFileHandler', 'level': 'INFO', 'formatter': 'verbose', 'filename': '%s/logs/django.log' % BASE_DIR, 'when': 'midnight', }, }, 'loggers': { 'django': { 'handlers': ['console', 'file_django'], 'level': 'INFO', 'propagate': True, }, } } After I ran command python manage.py runserver, the logs were written into project/logs/django.log like this INFO 2019-12-17 16:04:29 140549957289792 autoreload run_with_reloader 597 Watching for file changes with StatReloader INFO 2019-12-17 16:06:26 140549579474688 basehttp log_message 154 "GET /static/css/index.b2cb0abe.css HTTP/1.1" 304 0 INFO 2019-12-17 16:06:26 140549571020544 basehttp log_message 154 "GET /static/js/index.b1c726ec.js HTTP/1.1" 304 0 INFO 2019-12-17 16:06:27 140549579474688 basehttp log_message 154 "GET /manage/user_info/ HTTP/1.1" 200 154 But if I start my project with uwsgi --init app.ini, nothing will be written into django.log app.ini: [uwsgi] module = project.wsgi:application master = true process = 5 threads = 100 buffer-size = 32768 http = 0.0.0.0:8018 project/wsgi.py: os.environ.setdefault('DJANGO_SETTINGS_MODULE', f'project.settings.prod') application = get_wsgi_application() How to keep the django log in django.log if I … -
Django rest framework does not allow connection
I'm making android app with django server. I use django rest framework When android app send some data to server, there is no log django server showing in cmd. and server do not get any request. And android shows error message failed to connect to /10.80.162.133 (port 1289) from /10.80.163.129 (port 60989) after 10000ms But with postman, everything works well I think there is an error at server part This is my django settings.py import os import datetime BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '8wxm7e451m83j%)c8a+cf+#&#vg-qr1l-l%jx+ri@#r2^3_%nw' DEBUG = True ALLOWED_HOSTS = ['*', '.pythonanywhere.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'corsheaders', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth.registration', 'diary', ] REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', ], 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'diary.backend.MyTokenAuthentication', ), 'AUTHENTICATION_BACKENDS' : ( 'diary.backend.MyBackend', ) } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': … -
Having issue with 1&1 Hosting of Django
I follow this github link and I run all the command using PUTTY and connect with my hosting server https://github.com/sparagus/django-shared-hosting-1and1 and still its not working. after completing all the step I try to run server with, python manage.py runserver 0.0.0.0:8000 and python manage.py runserver 127.0.0.1:8000 and its not working with me I check my domain http://www.******.com & http://www.******.com/your_site also but it an empty page without any error -
Running Centralized Service on Elastic Beanstalk
I have setup a Django server on AWS Elastic Beanstalk. In that server, I have following services Application server Celery Worker Celery Beat I have using Docker to deploy my application which means I build my docker image, us that image to run all three services. My Dockerrun.aws.json file is below. { "AWSEBDockerrunVersion": 2, "containerDefinitions": [ { "command": [ "sh", "-c", "./entry_point.sh && gunicorn Project.wsgi:application -w 2 -b :8000 --timeout 120 --graceful-timeout 120 --worker-class gevent" ], "environment": [ ], "essential": true, "image": "695189796512.dkr.ecr.us-west-2.amazonaws.com/Project-20181107174734", "name": "app", "memory": 500, "portMappings": [ { "containerPort": 8000, "hostPort": 80 } ] }, { "command": [ "celery", "-A", "Project", "beat", "--loglevel=info", "--uid", "django" ], "environment": [ ], "essential": true, "image": "695189796512.dkr.ecr.us-west-2.amazonaws.com/Project-20181107174734", "memory": 200, "name": "celery-beat" }, { "command": [ "celery", "-A", "Project", "worker", "--loglevel=info", "--uid", "django" ], "environment": [ ], "essential": true, "image": "695189796512.dkr.ecr.us-west-2.amazonaws.com/Project-20181107174734", "memory": 200, "name": "celery-worker" } ], "family": "", "volumes": [] } Problem: This configuration is working fine. But the problem with this configuration is that on all my nodes, all three services run. When load increases, my server scales up to multiple nodes and all services run on each node. I can have multiple celery worker running on server as my task … -
AttributeError: 'TestSuite' object has no attribute 'client'
I'm writing Django unit test for Login form. Below is my sample code. from unittest import TestCase from django.contrib.auth.models import User class TestSuite(TestCase): def setUp(self): self.credentials = { 'username': 'testuser', 'password': 'secret'} User.objects.create_user(**self.credentials) def test_login(self): # send login data response = self.client.post('/accounts/login', self.credentials, follow=True) # should be logged in now self.assertTrue(response.context['user'].is_active) But when I'm executing from my console it's throwing the below error. System check identified no issues (0 silenced). E ERROR: test_login (accounts.tests.test_form.TestSuite) Traceback (most recent call last): File "C:\Django\webapplication\accounts\tests\test_form.py", line 15, in test_login response = self.client.post('/accounts/login', self.credentials, follow=True) AttributeError: 'TestSuite' object has no attribute 'client' Ran 1 test in 0.502s -
how to push multivalues from many element with same class or id in ajax
so i have make a form , that user can append the form is they need additional column , for example i have column name in the form , if people want to add more column name , they just press the add button , and the select element for column name will be added so it will have 2 select element with same class, but the problem is , i dont know how to send the data with ajax so django views can get the data.. every time i try to print the result , it will print as [] that it failed to push the data here's the code html <div class="row mt"> <div class="col-lg-12"> <div class="form-panel"> <form class="form-horizontal style-form" action="#"> <div class="form-group"> <label class="control-label col-md-3">Database Name</label> <div class="col-md-4"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select id = "tableselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> <!-- <li><a href="#"></a></li> --> {% for table in obj2 %} <option value = "{{table}}" >{{ table }}</option> {% endfor %} <!-- <li><a href="#">Dropdown link</a></li> --> </option> </select> </div> </div> </div> </div> <div class="form-group"> <label class="control-label col-md-3">Table Name</label> <div class="col-md-4"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select id="dataselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> </select> </div> </div> </div> </div> <div class="form-group"> <button class="btn btn-theme" onclick="return appendBox()">Add</button> … -
POSTMAN : Convert HTML response to JSON
I am running a Website using Python and Django . Here is my views .py : def user_login(request): user=0 inactive=0 if request.method=='POST': username=request.POST.get('username') print(username) password=request.POST.get('password') print(password) user=authenticate(username=username,password=password) if user: if user.is_active: login(request,user) profile=Profile.objects.get(user=user) return HttpResponseRedirect(reverse('accounts:index_with_pk',kwargs={'pk':profile.pk})) else: inactive = 1 return render(request, 'accounts/login.html', {'user': user, 'inactive':inactive}) else: print("Some one tried to login and failed") print("They typed : UserName {} and Password {}".format(username,password)) user=1 return render(request, 'accounts/login.html', {'user': user, 'inactive': inactive}) else: return render(request,'accounts/login.html',{'user':user, 'inactive': inactive}) When i run this in POSTMAN , i am getting the response in HTML but I want to get the response in JSON . In POST method , i requested this url : http://127.0.0.1:8000/accounts/login . The response in HTML , not in JSON. -
Unable to delete user from Admin panel which was created using Django-Allauth
I am new to Django and trying to add social login options to a project I am working on. I am currently using Django-Allauth for the same. Currently I have incorporated only Google login into my project. Everything works fine. I have created a custom user model for my project with email as the username. When a user tries to sign up using the Sign Up template I have provided, I can delete the user from the database without any problems. But if I try to delete any user from the admin panel who signed in using the Google option of django-allauth, I get __str__ returned non-string (type CustomUser) error. Only way for me to reset everything is to simply delete the model and redo everything. Below is how my model looks like. I am using Django 3.0 and the latest version of Django-Allauth. I am not sure how to solve this problem. Any help on this would be appreciated. models.py class CustomUser(AbstractBaseUser): email = models.EmailField(unique=True, max_length=100) first_name = models.CharField(max_length=35) last_name = models.CharField(max_length=35) mobile = models.CharField(max_length=11, blank=True, default='') city = models.CharField(max_length=35, blank=True, default='') def __str__(self): return self.email Settings.py # Application definition INSTALLED_APPS = [ # Default Apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', … -
Django Constraints Problem: Unable to create a custom check constraint with foreign key refrences
I'm unable to database level constraint to make sure that crm_user's crm_account belongs to crm_account in ContactOwnership. I tried the following ways: Way No. 1: Cyclic Dependency Error, so, django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. error. class ContactOwnership(models.Model): crm_account = models.ForeignKey('crm.CRMAccount', on_delete=models.CASCADE) # `crm_account` is added here for de-normalisation due to excessive joins when directly accessed through # `crm_user only`. crm_user = models.ForeignKey('crm.CRMUser', on_delete=models.CASCADE) contact = models.ForeignKey('contact_management.Contact', on_delete=models.CASCADE) # override update to check integrity: crm user should belong to same crm_account class Meta: unique_together = [['crm_account', 'crm_user', 'contact']] constraints = [ models.CheckConstraint(check=Q( crm_account=models.Subquery(CRMAccount.objects.filter(crm_account=models.OuterRef('crm_account'))[:1]) ), name='contact-ownership-account-integrity') ] Way No. 2: Using Q and F, but Join operation not permitted in constraints. class ContactOwnership(models.Model): crm_account = models.ForeignKey('crm.CRMAccount', on_delete=models.CASCADE) # `crm_account` is added here for de-normalisation due to excessive joins when directly accessed through # `crm_user only`. crm_user = models.ForeignKey('crm.CRMUser', on_delete=models.CASCADE) contact = models.ForeignKey('contact_management.Contact', on_delete=models.CASCADE) # override update to check integrity: crm user should belong to same crm_account class Meta: unique_together = [['crm_account', 'crm_user', 'contact']] constraints = [ models.CheckConstraint(check=Q(crm_account=F('crm_user__crm_account') ), name='contact-ownership-account-integrity') ] -
I want to get the value of the input box next to the button by jquery
I want to get the value of the input box next to the button html <span> <input type="text" value="{{p.filename}}" id="file_{{p.id}}" size=60 onclick="copy_for_file_name({{p.id}})"> <button class="badge badge-pill badge-dark file_history_button" name="button">history</button> </span> but it's not work // file_history_button $('body').on('click', '.file_history_button', function (e) { const file_name = $(this).siblings().find('input').val(); alert("file_name : ", file_name); }); result is empty do you know what is wrong?