Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django and "more information" forms
I have a form that, on submit, displays a form asking for more info. I'm sure this is easy if I could name it, but it's not quite obvious to me. I have a form that looks like this: class QuickMailingListSignupForm(ModelForm): class Meta: model = User fields = ('email',) labels = { 'email': "Adresse mél", } I stick it on various pages so people can enter an email address and sign up for my newsletter. On submit (to a different path/page), I ask you for a captcha. class MailingListSignupForm(ModelForm): captcha = CaptchaField( label="Je suis humain", help_text="...", error_messages=dict(invalid="captcha incorrect, ...")) ... class Meta: model = User ... The first form, which just gets the email, forwards to this view, whose job is to manage the remainder of the interaction: class QuickMailingListSignup(FormView): template_name = 'mailing_list/quick_signup.html' form_class = MailingListSignupForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['...'] = ... return context def form_valid(self, form): # ?? So my problem is that I'll never get to that # ??: the first form is submitting a QuickMailingListSignupForm and the second should either process a MailingListSignupForm or else extract the email address from the QuickMailingListSignupForm, push it into a MailingListSignupForm, and then go on to manage that … -
Django version of request.args.get() function in Flask
I am migrating my code from Flask to Django and this line from Flask doesn't seem to work in Django auth_token = request.args['code'] I googled a lot but can't seem to find the correct parameter to request the authorization token! -
Django gives "502 Bad Gateway" error on Google App Engine
I'm trying to deploy a Django application on Google App Engine in the Standard Python3.8 environment. I followed all the steps in this document. App runs fine on my local with google cloud database. However I receive 502 Bad Gateway error visiting Web Url. I found a lot of different questions but technology is changing a lot, and none of them helped so far. Lastly, I came across this question today, but it says create a gcloud.py file that I never seen in google documents that's why I haven't applied that solution but decided to ask you. I get this error when visiting page Traceback (most recent call last): _find_and_load (<frozen importlib._bootstrap>) And this is the stack trace from the error: File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked: ModuleNotFoundError: No module named 'main' at _find_and_load (<frozen importlib._bootstrap>:991) at _gcd_import (<frozen importlib._bootstrap>:1014) at import_module (/opt/python3.8/lib/python3.8/importlib/__init__.py:127) at import_app (/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/util.py:358) at load_wsgiapp (/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py:39) at load (/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py:49) at wsgi (/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/app/base.py:67) at load_wsgi (/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/workers/base.py:144) at init_process (/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/workers/base.py:119) at init_process (/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/workers/gthread.py:92) at spawn_worker (/layers/google.python.pip/pip/lib/python3.8/site-packages/gunicorn/arbiter.py:583) my_site/wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_site.settings") application = get_wsgi_application() This is my app.yaml runtime: python38 handlers: # This configures Google App Engine to serve the files in the app's … -
How to tie id of question field to answer filed in formset ? django
When I am trying to choose an answer for the second question, the radio selected from the first question shifts to the second one. Am I going the right way? if not, then what is the best way to do this? index.html <form action="{% url 'index'%}" method="POST"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form.teacher }} {{ form.department }} {% for question in question %} {{ question }} {{ form.answer }} {% endfor %} {% endfor %} <input type="submit" value="Vote"> models.py class Student_Answer(models.Model): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) department = models.ForeignKey(Department, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES, default=1) views.py def index(request): question = Question.objects.all() AnswerFormset = formset_factory(AnswerForm) if request.method == "POST": formset = AnswerFormset(request.POST) if formset.is_valid(): for form in formset: form.cleaned_data form.save() return HttpResponseRedirect('/submit/') else: formset = AnswerFormset() context = { 'formset': formset, 'question': question } return render(request, 'index.html', context) -
Django - 'elif'. Did you forget to register or load this tag?
I am developing a simple Django app. Is the piece of code below even valid? My code : {% if request.session.role is "Manager" %} {% extends 'manager_base_nav.html' %} {% elif request.session.role is "Agent" %} {% extends 'agent_base_nav.html' %} {% else %} {% extends 'customer_base_nav.html' %} {% endif %} -
{% include %} tag does not appear Django
I am trying to make include {% include %} in Django. But I face some trouble This is the base form.html file that I trying to inherit: <form class = 'form' method = 'POST' action = ""> {% csrf_token %} {{form.as_p}} <input type= "submit" value = "{{ btn_title }}" /> </form> and this is the inherited create.html: **{% include "form.html" with form=form btn_title = "Tweet" %} But Actually I have this error:- TemplateSyntaxError at /tweets/2/update Unknown argument for 'include' tag: 'input|btn_title'. Request Method: GET Request URL: http://localhost:8000/tweets/2/update Django Version: 3.0.6 Exception Type: TemplateSyntaxError Exception Value: Unknown argument for 'include' tag: 'input|btn_title'. Exception Location: C:\Python\lib\site-packages\django\template\loader_tags.py in do_include, line 311 Python Executable: C:\Python\python.exe Python Version: 3.6.8 Python Path: ['D:\From Torrents\Web , flask , django from torrent\[FreeCourseSite.com] ' 'Udemy - Tweetme Build a Twitter-like app step by step with Django\src', 'C:\Python\python36.zip', 'C:\Python\DLLs', 'C:\Python\lib', 'C:\Python', 'C:\Users\pc\AppData\Roaming\Python\Python36\site-packages', 'C:\Users\pc\AppData\Roaming\Python\Python36\site-packages\win32', 'C:\Users\pc\AppData\Roaming\Python\Python36\site-packages\win32\lib', 'C:\Users\pc\AppData\Roaming\Python\Python36\site-packages\Pythonwin', 'C:\Python\lib\site-packages'] Server time: Mon, 21 Dec 2020 16:35:25 +0000 -
How to access data from a webpage using Django?
I am new to Django. I am trying to access this webpage's data and store it in some database (like sqlite). But I couldn't fetch the data. I am not sure whether this task requires the use of IMDB API or if it's possible without the use of it. This is what I have tried: # view.py from django.shortcuts import render import requests from django.http import HttpResponse import urllib.request, json def index(request): r = requests.get('https://www.imdb.com/chart/top?ref_=nv_mv_250').json() d = {'v': r} return render(request, 'index.html', context = d) I am getting this error by running the above code: JSONDecodeError at / Expecting value: line 4 column 1 (char 3) It would be great if someone can help me out. -
Add arguments from strings to a python function
I want to create a method, which can dynamically add keyword arguments to another function that I intend to call within this method, something like: def func(query1: str, query2: str): func2(query1, query2) where, the query1, query2 in the func are strings of the type "a=3", "b=4", the func should essentially take these strings and then call them in a keyword argument way like: func2(a=3, b=4) I want to know if this kind of implementation is even possible or if there are any workarounds for achieving the same goal. The reason why I want this is because I have a django application in which I want to create a model where I can store some filter rules and apply them each time that view is called, so I want to allow the user to select a bunch of filters and then I want to store them in the database and call those rules to get a queryset specific to that user's preferences. def some_view(request): # Get the filter rule strings from the model queryset = some_model.objects.filter(<Pass all the rules here from those strings>) return Response edit: Add more details on the use case -
How can I modify exisitng pdf?
how can I add text over different PDF templates, I want create Automate application to fill existing pdf with different layout, The issue i need to import pdf and automated fill it from model using django admin, there any way to do that, i searched in many pkg all library using to convert form template to pdf or only extract text from pdf! -
How can i use MultiSelectField in drf patch?
i have MultiSelectField in model field.when i want to use field in drf patch, i get this error: ''' rest_framework.exceptions.ValidationError: {'visit_type': [ErrorDetail(string='"[0]" is not a valid choice.', code='invalid_choice')], 'visit_method': [ErrorDetail(string='"[]" is not a valid choice.', code='invalid_choice')], 'visit_duration_plan': [ErrorDetail(string='"[]" is not a valid choice.', code='invalid_choice')]} ''' -
how to render image and remove the html tags in content from django ck editor in django template
I tried so many times , but i didn't get any solution for rendering image and content without html tags , i used {{content|safe}} for rendering content on template and i tried strip_tags for html tags removal but it didn't work well for url's , can anyone suggest me why i am getting html tags while rendering in templates. Models.py class Product(models.Model): name = models.RichTextUploadingField(max_length="125") description = models.RichTextUploadingField() views.py def poll(): context = questions.object.all() return render(request, 'quiz.html', context) template: <html> <body> {% for q in context %} <div id="section{{forloop.counter}}"> <script type="text/javascript"> marks.push(Number("{{marks}}")); neg_marks.push(Number("{{neg_marks}}")); </script> <p id="{{forloop.counter}}"><span>{{forloop.counter}}.{{q.question|linebreaks}} </span></p> {% if q.figure %} <img src="{{q.figure.url}}" alt="image" class="img-fluid" width="200px" height="200px"><br><br> {% endif %} <input type="radio" id="{{forloop.counter}}option1" name="{{forloop.counter}}" value="1"> <label for="{{forloop.counter}}option1">{{q.option_1|safe }}</label><br> <input type="radio" id="{{forloop.counter}}option2" name="{{forloop.counter}}" value="2"> <label for="{{forloop.counter}}option2">{{q.option_2|safe}}</label><br> {% if q.option_3 != "" %} <input type="radio" id="{{forloop.counter}}option3" name="{{forloop.counter}}" value="3"> <label for="{{forloop.counter}}option3">{{q.option_3|safe}}</label><br> {% endif %} {% if q.option_4 != "" %} <input type="radio" id="{{forloop.counter}}option4" name="{{forloop.counter}}" value="4"> <label for="{{forloop.counter}}option4">{{q.option_4|safe}}</label><br> {% endif %} {% if q.option_5 != "" %} <input type="radio" id="{{forloop.counter}}option5" name="{{forloop.counter}}" value="5"> <label for="{{forloop.counter}}option5">{{q.option_5|safe }}</label><br> {% endif %} {% if forloop.first %} <p role="button" class="btn btn-warning" id="next{{forloop.counter}}" onclick="next_section(this.id)" style="float: right;">Next</p> {% elif forloop.last %} <p role="button" class="btn btn-warning" id="prev{{forloop.counter}}" onclick="prev_section(this.id)" style="float:left;">Previous</p> {% else %} … -
GET and POST from Chrome Extension to Django Server
I am trying to get information from a view I created in Django (using Django as a REST API) by calling it from my Chrome Extension, having the view perform a quick calculation and then posting that result to the chrome extension. I am not able to successfully get any data from the view, but the view is working and running just fine. What should my .js file look like to send a GET request to the Django view? Here is the .js (NOTE: to test I am simply trying to get the ip address to show the connectivity works): fetch("http://127.0.0.1:8000/") .then(function (response) { return response.json(); }) .then(function (myJson) { document.getElementById("place").innerHTML = myJson.ip; }) .catch(function (error) { console.log("Error: " + error); }); -
Oracle backend does not support timezone-aware datetimes when USE_TZ is False
I am saving date-time value in oracle using Djanog. My model has last_updated_at = DateTimeField(). This date-time value will be displayed by other application that is not developed in Django. I set last_updated_at with date-time which is not in UTC but it's always saving it in UTC timezone. When I set USE_TZ = False it gives error Oracle backend does not support timezone-aware datetimes when USE_TZ is False I also tried TIME_ZONE = 'Asia/Karachi' in settings.py but still date is saved in UTC. Any who can help please??, Thanks -
Please I have been encountering this problem over a week
Anytime I run my login url ,it runs twice in the terminal the first being "GET / login". Then it prints some things from the view. "POST / login". Unknown The post / login always return unknown Please I need help -
how to create a button or an option to connect to Data in Django web app
I wanted to create a Web app(basic analytics app) using Django,in which there should be a option to connect to databases or connect to CSV e.t.c, and that data needs to be populated on the screen(app). Iam just a beginner,Please help me with any necessary code or requirements. Thanks in advance for any help or advice. -
RuntimeError: __class__ not set defining 'Message' as <class 'rapidsms.contrib.messagelog.models.Message'>
I have runtime error in migrate step. -- python manage.py migrate RuntimeError: class not set defining 'Message' as <class 'rapidsms.contrib.messagelog.models.Message'> To setup your local environment you should create a virtualenv and install the necessary requirements:: virtualenv start_rsms1-env On Posix systems you can activate your environment like this:: source start_rsms1-env/bin/activate On Windows, you'd use:: start_rsms1-env\Scripts\activate Then:: cd start_rsms1 pip install -U -r requirements/base.txt Run migrate:: python manage.py migrate You should now be able to run the development server:: python manage.py runserver -
Pytest not working with Django and Docker - AssertionError: local('/dev/console') is not a file
I'm running a Django application in Docker and everything works fine but when I try try to run tests it fails with quite ambiguous error. running docker-compose run djangoapp coverage run -m pytest result: Creating djangoapp_run ... done ================================================= test session starts ================================================== platform linux -- Python 3.8.5, pytest-6.2.1, py-1.10.0, pluggy-0.13.1 rootdir: / collected 0 items / 1 error ======================================================== ERRORS ======================================================== ____________________________________________ ERROR collecting test session _____________________________________________ usr/local/lib/python3.8/dist-packages/_pytest/runner.py:311: in from_call result: Optional[TResult] = func() usr/local/lib/python3.8/dist-packages/_pytest/runner.py:341: in <lambda> call = CallInfo.from_call(lambda: list(collector.collect()), "collect") usr/local/lib/python3.8/dist-packages/_pytest/main.py:710: in collect for x in self._collectfile(path): usr/local/lib/python3.8/dist-packages/_pytest/main.py:546: in _collectfile assert ( E AssertionError: local('/dev/console') is not a file (isdir=False, exists=True, islink=False) =============================================== short test summary info ================================================ ERROR - AssertionError: local('/dev/console') is not a file (isdir=False, exists=True, islink=False) !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! =================================================== 1 error in 0.33s =================================================== docker-compose: version: '3' services: djangoapp: build: . container_name: djangoapp ports: - '8000:80' - '1433:1433' volumes: - ./djangoapp:/var/www/html/djangoapp environment: - PYTHONUNBUFFERED=0 -
How can I update my filter function to work generically?
I overrode the SAVE function in one of my models, and now I want to put it in a MIXIN to be used by other models. But I have one part I'm not sure how to make generic. It looks like this: MyModel.objects.filter(code=code).exists() How can I make this generic so it will work with whatever model imports the override? -
Why am i getting "Error running :Checksum"?
Error running 'Checksum': Cannot run program "D:\pythonProject\Estore\venv\Scripts\python.exe" (in directory "D:\Estore\cart\PayTm"): CreateProcess error=2, The system cannot find the file specified. -
how can i collect imgaes from template and save it to database in django
I want users to add blogs with images. So I have to collect images from them through the template and save them to the database. But it's just collect the name of the images. views.py ''' def create_post(request): if request.method == 'POST': title = request.POST['title_id'] catagory = request.POST['catagory_id'] #author = request.POST['author_id'] description = request.POST['description_id'] notes = request.POST['notes_id'] image = request.POST['image_id'] author = request.user if not User.objects.filter(username=author).exists(): messages.warning(request,'There is no account by this username. Please make sure you intput your username associated with your account') return redirect("/blog/create_blog/") blog_post = Applyforposting(title=title, catagory=catagory,content=description,author=author,notes=notes, images=image) blog_post.save() messages.success(request,'Your Submission is successful. Wait for approval') return render(request,'blog/create_post.html')''' models.py ''' class Applyforposting(models.Model): approved = models.BooleanField(null=True, blank=True, default=False) serial_number = models.AutoField(primary_key=True) title = models.CharField(max_length=100) catagory = models.CharField(max_length=15) content = models.TextField() author = models.CharField(max_length=100) apply_date = models.DateTimeField(auto_now=True) notes= models.CharField(max_length=300, null=True, blank=True) images = models.ImageField(upload_to='media/', null=True, blank=True) def __str__(self): return str(self.serial_number) + '->' + self.author + '->' + str(self.apply_date) + 'approved>>>'+str(self.approved)''' -
Pagination with annotated prefetch data
I wanted to speed up the API, so i had added pagination with annotations to get a count of a certain data. The problem with the prefetched annotated data is that it doesn't consider the pagination and if there are 1000 records it'll prefetch the data for annotation of 1000 records even if i want only 10 records in the first page.Is there a way to prefetch data to work with pagination? class ListCourseAssignments(generics.ListAPIView): serializer_class = AssignmentModuleSerializer pagination_class = SetByTenPagination filter_backends = [filters.SearchFilter] search_fields = ['name'] permission_classes = [ permissions.IsAuthenticated, CreateAssignmentPermission] def get_queryset(self): active_statuss = [EnrolmentStatusValues.APPROVED.value, EnrolmentStatusValues.WITHDRAW_PENDING.value] now = timezone.now() assignments = SimpleAssignmentModule.objects.filter( course_share_item__course__id=self.kwargs.get('pk')) unit = self.request.query_params.get('unit') if unit: assignments_in_unit = CourseShareItemModule.objects.filter(module__in=assignments.values_list( "id", flat=True), group__id=unit).select_related('module').values_list("module__id", flat=True) assignments = assignments.filter(id__in=assignments_in_unit) assignments = assignments.annotate( subject_id=Subquery(SimpleAssignmentModule.objects.filter(id=OuterRef('id')).only('id').annotate( subject_name=F('course_share_item__course__id')).values('course_share_item__course__id')[:1]), unit_id=Subquery(CourseShareItemModule.objects.filter(module__id=OuterRef('id'), course_share_item=OuterRef( 'course_share_item')).only('id').annotate(unit_name=F('group__id')).values('group__id')[:1]), subject_name=Subquery(SimpleAssignmentModule.objects.filter(id=OuterRef('id')).only('id').annotate( subject_name=F('course_share_item__name')).values('course_share_item__name')[:1]), unit_name=Subquery(CourseShareItemModule.objects.filter(module__id=OuterRef('id'), course_share_item=OuterRef( 'course_share_item')).only('id').annotate(unit_name=F('group__name')).values('group__name')[:1]), submitted_count= SQCount( AssignmentModuleProgress.objects.filter( Q(module_progress__module_progress_course_progresses__course_progress_userenrolments__expiry_date__isnull=True) | Q( module_progress__module_progress_course_progresses__course_progress_userenrolments__expiry_date__gt=now), module_progress__module_progress_course_progresses__course_progress_userenrolments__deleted=False, module_progress__module_progress_course_progresses__course_progress_userenrolments__user__is_suspended=False, module_progress__module_progress_course_progresses__course_progress_userenrolments__user__tenant__is_suspended=False, module_progress__module_progress_course_progresses__course_progress_userenrolments__status__short_name__in=active_statuss, module_progress__module__id=OuterRef('id'), is_submitted=True, ).values( 'module_progress__module_progress_course_progresses__course_progress_userenrolments').distinct() ), to_grade_count= SQCount( AssignmentModuleProgress.objects.filter( Q(module_progress__module_progress_course_progresses__course_progress_userenrolments__expiry_date__isnull=True) | Q( module_progress__module_progress_course_progresses__course_progress_userenrolments__expiry_date__gt=now), module_progress__module_progress_course_progresses__course_progress_userenrolments__deleted=False, module_progress__module_progress_course_progresses__course_progress_userenrolments__user__is_suspended=False, module_progress__module_progress_course_progresses__course_progress_userenrolments__user__tenant__is_suspended=False, module_progress__module_progress_course_progresses__course_progress_userenrolments__status__short_name__in=active_statuss, module_progress__module__id=OuterRef('id'), is_submitted=True, score=None ).values( 'module_progress__module_progress_course_progresses__course_progress_userenrolments').distinct() ) ) return assignments.order_by(F('due_date').asc(nulls_last=True)) -
Django can't connect MySQL But MySQL server is normally work
I Installed mysqlclient for python 3.8.4 and My django Database Setting is this. DATABASES = { 'default': { 'ENGINE' : 'django.db.backends.mysql', 'NAME' : 'testdb', 'USER' : 'root', 'PASSWORD' : 'tjdnftkfka0501', 'HOST' : '127.0.0.2', 'PORT' :'3306', } } [MYSQL Server is Good][1] [1]: https://i.stack.imgur.com/owfW4.png and I Tested Again that in the vscode. the result it server successfully connect . so ..My question is.. why Django can't connect MySQl??? jun_webserver2) C:\Users\lenovo\TechBlog\Server\Server>py manage.py migrate Traceback (most recent call last): File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\django\db\backends\mysql\base.py", line 234, in get_new_connection return Database.connect(**conn_params) File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\MySQLdb\__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\MySQLdb\connections.py", line 179, in __init__ super(Connection, self).__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2059, <NULL>) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\lenovo\Envs\jun_webserver2\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, … -
How can I use slice filter in Django?
How can I filter content like 0-9 then 9-18 then 18-28 and so on.. in Django using a slice filter or any other option?, SO please suggest me. <li class="mega-title"><span>column 01</span> <ul> {% for category in categories %} {% for subcategory in category.children.all|slice:":9" %} <li><a href="{% url 'shop' shop='shop' pk=subcategory.pk %}">{{subcategory.title}}</a></li> {% endfor %}{% endfor %} </ul> </li> <li class="mega-title"><span>column 02</span> <ul> {% for category in categories %} {% for subcategory in category.children.all|slice:"[09:9]" %} <li><a href="{% url 'shop' shop='shop' pk=subcategory.pk %}">{{subcategory.title}}</a></li> {% endfor %}{% endfor %} </ul> </li> -
settings.DATABASES is improperly configured” error django 3.1 while running inspect db
I am trying to create models using inspect db command from postgres db. When i run the command,i am getting raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Below is my settings.py DATABASES = { 'default': { }, 'population_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS' : { 'options': '-c search_path=dbo' }, 'NAME': 'SQLOPS_Population', 'USER': 'devsqlservice', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '5432', } } -
How to correctly enforce field combination in another table (Django)?
I have Outcode model that has a one-to-many relationship with SubOutcode model: class Outcode(models.Model): outcode = models.CharField(max_length=4, primary_key=True) class Meta: managed = True db_table = 'outcode' SubOutcode model: class SubOutcode(models.Model): outcode = models.ForeignKey('Outcode', models.DO_NOTHING) sub_outcode = models.CharField(max_length=4, default="") class Meta: managed = True constraints = [ models.UniqueConstraint(fields=['outcode', 'sub_outcode'], name='unq_sub_outcode') ] db_table = 'sub_outcode' I want to be able to create Property records only if the matching combination of fields exists in SubOutcode. How do I setup Property correctly? My current setup doesn't work as it looks if Outcode and SubOutcode exist separately as per below, but I want Property to enforce the combination if that makes sense? Thank you for your help. class Property(models.Model): property_outcode = models.ForeignKey('Outcode', models.DO_NOTHING) property_sub_outcode = models.ForeignKey('SubOutcode', models.DO_NOTHING, to_field='sub_outcode')