Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to give unique together in flask?
I am defining a table in Flask like groups = db.Table( "types", db.Column("one_id", db.Integer, db.ForeignKey("one.id")), db.Column("two_id", db.Integer, db.ForeignKey("two.id")), UniqueConstraint('one_id', 'two_id', name='uix_1') #Unique constraint given for unique-together. ) But this is not working. -
How can I integrate MDB(Material Bootstrap Design) with Django? and what is the suitable files tree organization
How can I integrate MDB(Material Bootstrap Design) with Django? -
TemplateDoesNotExist Error Django not-defined template appers
First, I got an error message on web browser here. It says, 'TemplateDoesNotExist at / index.html, base/item_list.html'. Console error message says, Internal Server Error: / Traceback (most recent call last): File "C:\Users\kgwtm\Desktop\Django\Django-Fujimoto\VegeKet\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\kgwtm\Desktop\Django\Django-Fujimoto\VegeKet\venv\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\kgwtm\Desktop\Django\Django-Fujimoto\VegeKet\venv\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\kgwtm\Desktop\Django\Django-Fujimoto\VegeKet\venv\lib\site-packages\django\template\response.py", line 81, in rendered_content template = self.resolve_template(self.template_name) File "C:\Users\kgwtm\Desktop\Django\Django-Fujimoto\VegeKet\venv\lib\site-packages\django\template\response.py", line 63, in resolve_template return select_template(template, using=self.using) File "C:\Users\kgwtm\Desktop\Django\Django-Fujimoto\VegeKet\venv\lib\site-packages\django\template\loader.py", line 47, in select_template raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) django.template.exceptions.TemplateDoesNotExist: pages/index.html, base/item_list.html [23/Feb/2022 16:19:38] "GET / HTTP/1.1" 500 83837 In the first place, I don't even create or declare 'base/item_list.html' in any file in Django project. I've created 'config' project and 'base' app. Project 'config' file organization here. App 'base' file organization here. config/urls.py here. from django.contrib import admin from django.urls import path from base import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.IndexListView.as_view()), ] base/views/item_views.py here from django.shortcuts import render from django.views.generic import ListView from base.models import Item class IndexListView(ListView): model = Item template_name = 'pages/index.html' base/views/init.py here. from .item_views import * So, templates/pages/index.html here. {% extends 'base.html' %} {% block main %} {% for object in object_list %} <p> <a href="/items/{{object.pk}}/"> {{object.name}} … -
"'str' object has no attribute 'tag'" error in Django Tutorial
I am following the Django Tutorial to learn how to work with it, but I have encountered an error very early in it and I'm not sure how to fix it. It happened while creating the django project and doing the 'Write your first view' section: https://docs.djangoproject.com/en/dev/intro/tutorial01/#write-your-first-view After following those steps carefully, while executing python3 manage.py runserver the following error appears: AttributeError: 'str' object has no attribute 'tag' This is the full error trace: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/home/noctis/.local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/noctis/.local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/home/noctis/.local/lib/python3.9/site-packages/django/core/management/base.py", line 438, in check all_issues = checks.run_checks( File "/home/noctis/.local/lib/python3.9/site-packages/django/core/checks/registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/noctis/.local/lib/python3.9/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/noctis/.local/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/noctis/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 448, in check for pattern in self.url_patterns: File "/home/noctis/.local/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/noctis/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 634, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/noctis/.local/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/noctis/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 627, in urlconf_module return import_module(self.urlconf_name) File … -
How to pass a list of dictionaries in a function?
I am working on a teacher grading system in Django. I want functionality in which there is some entry like subject id and student's marks from the frontend. My app on the backend takes these two-parameter and creates a list of dictionaries with subject id and marks and pass it on another function and that function will sum up all the marks and give me a total and next average and percentage etc. But right now, I am stuck with total only so, when I pass this list of dictionaries in a function it gives me an error. class Marks_entry: def marks_entry(subject_id, marks): try: subject_id = int(input(f'Enter subject id: ')) marks=int(input(f'Enter marks: ')) except ValueError: print(f'You can only try integers:') marks_entry=[] marks_entry.append({ "subject_id": subject_id, "marks": marks }) marks_calculation = marks_calculation(marks_entry) return marks_calculation def marks_calculation(marks_entry): total = sum(item['marks'] for item in marks_entry) return total marks=0 subject_id= 0 b= Marks_entry b.marks_calculation(marks, subject_id) error is: Enter subject id: 1003 Enter marks: 58 Traceback (most recent call last): File "c:\Users\Lenovo\Documents\TGS\controller.py", line 53, in <module> b.marks_entry(subject_id, marks) File "c:\Users\Lenovo\Documents\TGS\controller.py", line 43, in marks_entry marks_calculation = marks_calculation(marks_entry) UnboundLocalError: local variable 'marks_calculation' referenced before assignment -
Django / GraphQL -- 2 types have fields that are referencing each other causes a crash
I have 2 graphql types that each have fields that refer to the other. There is an error because one of the types has not been declared when the first one is read. The issue is that the type should be instantiated before using it in a field. But since the two types refer to each other, One is always being referred to before it has been instantiated. Any ideas on how to solve? Here is a link to the parts of the code that are relevant: https://gist.github.com/olivermontalbano/ce8db9fd62619b983ed68b6933ff7e64 -
Django ManyToManyField with through -- how can I not lose data not selected in the QuerySet?
Django Newbie here. I have some trouble with a ManyToMany relationship and a through field. I am trying to create a tool where staff members can apply for shifts on events (Bar, entry control, etc.). Therefore I created a Staff object (this is the person with all her roles etc.) and linked it by ManyToManyField to a ScheduledShift object (which contains event date, time and duties). I want to be able to present each day as a view to the user where he/she can just tick the shifts he/she is available that day. This works and it also writes the correct data (i.e. the staff id and the shift id for all the shifts he/she ticked) for that day into the "through" table (StaffShift object). The relevant code looks like this: models.py class Staff(models.Model): ... shifts = models.ManyToManyField(ScheduledEventShift, through='StaffShift') class StaffShift(models.Model): staff = models.ForeignKey(Staff, on_delete=models.CASCADE) shift = models.ForeignKey(ScheduledEventShift, on_delete=models.CASCADE) views.py class StaffShiftUpdateView(ObjectUpdateView): model = Staff ... def get_form(self, form_class=None): form = super().get_form(form_class=self.form_class) day = datetime(self.kwargs.get('year'), self.kwargs.get('month'), self.kwargs.get('day')) form.fields['shifts'].queryset = ScheduledEventShift.objects.filter( event__event_date=day).order_by('event__event_date') return form ('event' is a property in the ScheduledEventShift object) My problem is that by writing those ids into the through table, all other rows for that user that … -
I'm trying to save an image using django html form without using model ! is it possible
I am getting attribute error. AttributeError at /file_upload 'TemporaryUploadedFile' object has no attribute 'save' views.py Thank you so much -
how to filter by month from template
I'm attempting to channel a datetime field by month and year. Though no one can really say why while entering both month and year I get back a vacant set returned. Model class SpareParts(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) amount = models.IntegerField(blank=False, null=False) date = models.DateField(blank=False, null=False) And i want to filter on the basis of vehicle and month vise and here is mine view VIEWS.py def view_spare(request): sparepart = SpareParts.objects.all() vehicle_filter = request.POST.get('vehicle') # get the value of the date field month_filter = request.POST.get('month') # get the value of the date field if vehicle_filter: if month_filter: sparepart = sparepart.filter(vehicle=vehicle_filter,date__month=month_filter).aggregate(Sum('amount')) return render(request,'invoice/spare_parts_list.html',{'sparepart':sparepart}) and i want render the whole month sum of amount in template -
Django table update using Ajax
I want to update my django template data using Ajax. I want to let the users update the status from the dropdown and it should reflect without the page being refreshed Please refer this Django template {% for vulnerability in vulnerabilitys %} <tr> <th scope="row" >{{vulnerability.id}}A{{vulnerability.sNo}}</th> <td>{{vulnerability.vul_title}}</td> <td>{% for asset in vulnerability.asset.all %}{{asset}}<br>{% endfor %}</td> <td><span {% if vulnerability.severity|lower == 'info' %} class="badge rounded-pill bg-info" {% elif vulnerability.severity|lower == 'high' %} class="badge rounded-pill bg-danger" {% endif %}> {{vulnerability.severity}}</span></td> <td>{{vulnerability.vul_url}}</td> <td>{{vulnerability.last_seen|date:'d-m-Y H:i'}}&nbsp;<i class='fas fa-clock' style='color:rgb(48, 75, 228)'></i></td> <td><select id="ab" data-item = {{vulnerability.id}} qty-item="{{vulnerability.status}}" class="update" onchange="if (this.selectedIndex) doSomething();"> {% if vulnerability.status == 'Open' %} <option value="{{ vulnerability.status }}">{{ vulnerability.status }}</option> <option value="InProgress">InProgress</option> <option value="Fixed">Fixed</option> </select> {% elif vulnerability.status == 'InProgress' %} <option value="{{ vulnerability.status }}">{{ vulnerability.status }}</option> <option value="Open">Open</option> <option value="Fixed">Fixed</option> </select> {% else %} <option value="{{ vulnerability.status }}">{{ vulnerability.status }}</option> <option value="InProgress">InProgress</option> <option value="Open">Open</option> </select> {% endif %} <h5>{{vulnerability.status}}</h5></td> </tr>{% endfor %} script in the template $(document).on('change', '.update', function(){ // var item = $(this).closest('tr'); // editItem(item); var pid = $(this).attr('data-item'); var stat = $(this).attr('qty-item'); var x = document.getElementById("ab").value; console.log("OLD",stat); console.log("NEW",x) var elem = document.getElementById('myTable2'); elem.style.color = 'green'; $.ajax({ url:'/statUpdate/', data:{'pid': pid, 'stat':stat, 'x':x}, // dataType:'json', success: function(data){ // $('h5').html(data); } }); … -
How to differentiate between user inactivity and continous http request in django?
I would like to logout the session if there is no activity on web application from user. Currently, I have implemented custom middleware to logout for configured time interval. In my application, there is need to do continuous polling every 2 seconds. But, in my custom middleware class "def process_request(self, request)" gets called everytime when polling is getting executed. So, the session never gets logout, as this polling also it is considering as user activity. Now, how do I differentiate between user inactivity & polling? Code: from django.utils.deprecation import MiddlewareMixin from django.contrib.auth import logout from django.contrib import messages from datetime import datetime, timedelta from django.contrib import auth from django.conf import settings class CustomMiddleware(MiddlewareMixin): def process_request(self, request): if not request.user.is_authenticated : #Can't log out if not logged in return try: if datetime.now() - request.session['last_touch'] > timedelta( 0, settings.AUTO_LOGOUT_DELAY * 60, 0): auth.logout(request) del request.session['last_touch'] return except KeyError: pass request.session['last_touch'] = datetime.now() settings.py: SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' AUTO_LOGOUT_DELAY = 1 -
Celery Beat Django
I am trying to run beat celery function but I am getting an error of: Error: Unable to parse extra configuration from command line. Reason: not enough values to unpack (expected 2, got 1) This is my code: @periodic_task(name="fun_123", run_every=crontab(minute="1")) def fun_123(context): bill = Bill.objects.get(id=context["id"]) if bill.date < make_aware(datetime.now()): bill.check = False bill.save() This is my command that I am using command: celery -A backend worker -l DEBUG -BE fun_123 -
how we can add delivery charges area wise in django ecommerce project
Hi I am working on Django Ecommerce Project and I want to set delivery charges According area wise can any one guide me how I can add delivery charges using Django?? -
Django TemplateView is not Working with This Code
Am having issues writting Views for django oscar extended TemolateView class CatalogueView(TemplateView): """ Browse all products in the catalogue """ context_object_name = "products" template_name = 'oscar/catalogue/browse.html' model = Product def get(self, request, *args, **kwargs): try: self.search_handler = self.get_search_handler( self.request.GET, request.get_full_path(), []) response = super().get(request, *args, **kwargs) except InvalidPage: # Redirect to page one. messages.error(request, _('The given page number was invalid.')) return redirect('catalogue:index') return response def get_search_handler(self, *args, **kwargs): return get_product_search_handler_class()(*args, **kwargs) def get_context_data(self, **kwargs): context = super(CatalogueView, self).get_context_data(**kwargs) ctx = {} ctx['summary'] = _("All products") ctx['pro_list'] = Product.objects.all() ctx['pro_list1'] = Product.objects.all().filter().order_by('upc') search_context = self.search_handler.get_search_context_data( self.context_object_name) ctx.update(search_context) return ctx Don't mind the messy Code indentation format. Django Oscar uses the class based TemplateViews and I want to write more queresets for my products model but everything seems not working. get_context_data will not work. I need a way to add more Queresets to the TemplateView in the catalogue view. How can this be resolved? I need to filter more queresets for the Product django django-models django-views -
i faced CircularDependencyError in django
I faced a CircularDependencyError error. so i tried find . -path "/migrations/.py" -not -name "init.py" -delete find . -path "/migrations/.pyc" -delete and delete db.sqlite3 file and then i tried python manage.py makemigrations and migrate but it's still error what is auth.0013_historicaluser, auth.0014_delete_historicaluser, users.0001_initial ?? well i used AbstractUser and django-simple-history. i really confused... what happend...? Traceback (most recent call last): File "/data/test-table/manage.py", line 22, in <module> main() File "/data/test-table/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/root/miniconda3/envs/gdaj/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/root/miniconda3/envs/gdaj/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/miniconda3/envs/gdaj/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/root/miniconda3/envs/gdaj/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/root/miniconda3/envs/gdaj/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/root/miniconda3/envs/gdaj/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 92, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/root/miniconda3/envs/gdaj/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/root/miniconda3/envs/gdaj/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/root/miniconda3/envs/gdaj/lib/python3.9/site-packages/django/db/migrations/loader.py", line 286, in build_graph self.graph.ensure_not_cyclic() File "/root/miniconda3/envs/gdaj/lib/python3.9/site-packages/django/db/migrations/graph.py", line 274, in ensure_not_cyclic raise CircularDependencyError(", ".join("%s.%s" % n for n in cycle)) django.db.migrations.exceptions.CircularDependencyError: auth.0013_historicaluser, auth.0014_delete_historicaluser, users.0001_initial class PayHistoryChange(models.Model): branch = models.ForeignKey("Branch", on_delete=models.CASCADE, null=False) payhistory = models.ForeignKey("PayHistory", on_delete=models.CASCADE, null=False) ... history = HistoricalRecords() -
get() returned more than one Item -- it returned 2! - Django Foreign Key Query
I have table A which has a column which is a Foreign Key - details_id pointing to a Primary Key in another table B in Django class A(models.Model): per_id = models.TextField(primary_key=True) hobby = models.TextField() details_id = models.ForeignKey(B, models.DO_NOTHING, blank=True, null=True) # the foreign key class B(models.Model): details_id = models.AutoField(primary_key=True) # the primary key fav_food = models.TextField() I am trying to fetch the details_id in table B, from the per_id in table A qs=qs.filter(per_id="2398") # this gives me the queyset for the person with per_id=2398 details=qs[0].details_id.details_id # this line gives the error The problem is that since there are 2 entries in the table B which have the same details_id, I am getting the following error - get() returned more than one B -- it returned 2! Table A - Table B - And I want to retrieve both of the values How can I do that? Any help on this would be greatly appreciated!! -
Save data into mutli model uising django orm join
I am facing a problem with Django I have 2 models"batch", "batchyeild", these 3 have different forms and users enter data into it Now I am creating another form "History" In which the user will enter the data but In my backend, the data which will come from "history" will be distributed in these 3 model tables DB Now the payload requested data of history is batch_status commodity name pesticide actual produce acerage variety_id end_date I will be distributively saved in 2 models the batch has batch_status commodity name pesticide actual produce average variety_id and batchyeild has columns end_date the viewof both looks like class BatchViewSet(viewsets.ModelViewSet): permission_classes = [permissions.AllowAny] serializer_class = BatchSerializer queryset = Batch.objects.all() http_method_names = ['get', 'post', 'patch', 'delete'] pagination_class = GeneralPagination filterset_fields = ['farm_id', 'batch_status'] def create(self, request, *args, **kwargs): """ This function is used to create/update Batch objects for the provided list based on batch_id """ # todo to be optimised. # get the user data in logged_in_user_data from the request headers decoding the authorization key header = {'Content-Type': 'application/json', 'Authorization': request.headers['Authorization']} logged_in_user_data = get_user_data(request.headers['Authorization']) # # user_id will contain the user id of the logged in user user_id = logged_in_user_data.get('secondary_user_tbl_id') for data in request.data: data['updated_by_id'] … -
Deploying Django Application on Digital Ocean
I am migrating to digital Ocean for app hosting. I have setup the static file handling to be done by white-noise on my settings.py file, I have run the collectstatic command on my local machine and it works. When the app is being build on digital ocean it encounter's an error. The error stack is as below. -----> $ python manage.py collectstatic --noinput [skakey] [2022-02-23 06:00:36] Traceback (most recent call last): [skakey] [2022-02-23 06:00:36] File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 243, in fetch_command [skakey] [2022-02-23 06:00:36] app_name = commands[subcommand] [skakey] [2022-02-23 06:00:36] KeyError: 'collectstatic' [skakey] [2022-02-23 06:00:36] During handling of the above exception, another exception occurred: [skakey] [2022-02-23 06:00:36] Traceback (most recent call last): [skakey] [2022-02-23 06:00:36] File "/workspace/manage.py", line 25, in <module> [skakey] [2022-02-23 06:00:36] main() [skakey] [2022-02-23 06:00:36] File "/workspace/manage.py", line 21, in main [skakey] [2022-02-23 06:00:36] execute_from_command_line(sys.argv) [skakey] [2022-02-23 06:00:36] File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line [skakey] [2022-02-23 06:00:36] utility.execute() [skakey] [2022-02-23 06:00:36] File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute [skakey] [2022-02-23 06:00:36] self.fetch_command(subcommand).run_from_argv(self.argv) [skakey] [2022-02-23 06:00:36] File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 250, in fetch_command [skakey] [2022-02-23 06:00:36] settings.INSTALLED_APPS [skakey] [2022-02-23 06:00:36] File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 84, in __getattr__ [skakey] [2022-02-23 06:00:36] self._setup(name) [skakey] [2022-02-23 06:00:36] File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 71, in _setup [skakey] [2022-02-23 … -
How to get the plane password of Django admin user in pre_save signal when creating user from admin panel?
I need to log Django admin users in 3ed party authentication service. For that I need plane password without hashing. Here I used pre_save signal. That approach works well when I create an API endpoint for registration. But when I create an admin user from Django it always comes with defalut hashed password. Any idea how to get the plane password? -
How to rollback non linear migrations in django?
Suppose I have following migrations in Django. X / \ A B [A and B can represent any number of linear migrations.] \ / Y (merge migration). How can I rollback only B and Y? And keep A as it is. -
Different HTTP request method in a django view class
I had written a view class that has 4 request methods(PUT, POST, DELETE, GET). I want to limit the access via 405 error(Method Not Allowed).2 of my methods do not need any id(The POST and GET) but the others need id. how can I write URLs with different names, for different methods? my view: class CourseAPI(GenericAPIView): permission_classes = [IsAuthenticated] serializer_class = CourseSerializer def get(self, request, *args, **kwargs): def put(self, request, *args, **kwargs): def post(self, request, *args, **kwargs): def delete(self, request, *args, **kwargs): here is my URLs: path( "responsible-person/list/", CourseAPI.as_view(), name="course-list", ), path( "course/<int:pk>/delete/", CourseAPI.as_view(), name="delete-course", ), path( "course/<int:pk>/edit/", CourseAPI.as_view(), name="update-course", ), path( "course/add/", CourseAPI.as_view(), name="add-course", ), is there any way to write like this? path( "course/add/", CourseAPI.post.as_view(), name="add-course", ) -
Django/React/Axios Trying to create an image gallery
I have a web app for an alumni group that manages events, scholarships, etc. I have the models and web pages to display all event details, but I'm struggling to allow a user to upload multiple images for a particular event. Each event has an id and other fields, and the gallery has the image and a foreign key to the event id, so images with event_id 3 all are assigned to the event with id 3, etc. At the moment, I've got all of the other fields to display with my api urls being consumed by axios (pics below). I can successfully upload all images to an event in the django backend. I would like to display those images at the bottom right under Event pictures. I'll deal with modals to enlarge them later. My events details page. import React, { useState, useEffect } from "react"; import { useParams, useNavigate } from "react-router"; import { Link } from "react-router-dom"; import { getEventById, deleteEventById, getGallery, getGalleryById, getGalleryByEventId } from "../../api/apiCalls"; import { Card, CardGroup, Col, Modal, Button } from "react-bootstrap"; import "./Event.css"; const EventDetail = () => { const [event, setEvent] = useState([]); const { id } = useParams(); const … -
Get the current chat history after page refresh
I have created a chatbot that can be added in any website and bot will added on all pages of website. Bot is working fine problem is after page refresh or going another page of website, current chat history is lost. How can I show show current chat after page refresh. I am using django channels for live chat and saving messages in database. When chat start I create a history instance in Histoy model, and then save every message in Conversation model This is model to save the chat. This is chat to customer care type app so messages are saved in question/answer form. class ChatHistory(models.Model): TYPE = ( ('bot_chat', 'bot_chat'), ('user_chat', 'user_chat') ) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='company_chat') customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING, related_name='customer_chat') date_time = models.DateTimeField(auto_now_add=True) chat_type = models.CharField(max_length=10, choices=TYPE) talker = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='user_chat', null=True) saved_status = models.BooleanField(default=False) trained_status = models.BooleanField(default=True) class Meta: ordering = ['-pk'] class Conversation(models.Model): history = models.ForeignKey(ChatHistory, on_delete=models.CASCADE, related_name='chat_history') question = models.TextField(null=True) answer = models.TextField(null=True) time = models.TimeField(auto_now_add=True) -
Nginx configuration with gunicorn
Api is in Django framework and the Web app is in Angular both are different projects. Nginx and gunicorn worked well and upload both projects in the same directory but when I hit my domain it shows Django application default page. I want to show my static html page instead of Django default page. 'server{ listen 443; server_name class.domain.com; root /var/www/html/; index index.html; location /static/ { try_files $uri $uri/ /index.html; } location ~ ^/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } }' -
how to display models.full_clean() ValidationError in django admin?
https://docs.djangoproject.com/en/4.0/ref/models/instances/#validating-objects from django.core.exceptions import ValidationError try: article.full_clean() except ValidationError as e: # Do something based on the errors contained in e.message_dict. # Display them to a user, or handle them programmatically. pass There tell us can Display them to a user, how to display errors in Admin? When I do nothing: When Settings.py Debug = True, it always render a ValidationError at /admin/xxx/xxx/xxx/change/ page. When Settings.py Debug = False, it always render a HTTP 500 page.