Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to split one database into two with django
I have one big data table that I want to turn into two tables Accordingly, I need certain columns from the big table in the first table Аnd in the second table I need to transfer the remaining columns here my old model.py class HV(models.Model): from direction.models import Project id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) address = models.CharField(max_length=90) username = models.CharField(max_length=60) password = models.BinaryField() kind = models.CharField(max_length=60) enabled = models.BooleanField(default=True) availability = models.BooleanField(default=True) time_unavailable = models.DateTimeField(null=True) direction = models.ForeignKey(Department, on_delete=models.PROTECT, null=True, default=None) project = models.ForeignKey(Project, on_delete=models.PROTECT, null=True, default=None) class Meta: managed = True db_table = 'hv_list_service' def __str__(self): return self.name and my new models.py class ClusterName(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) kind = models.CharField(null=True, max_length=10) enabled = models.BooleanField(default=True) availability = models.BooleanField(default=True) time_availability = models.DateTimeField() direction_id = models.ForeignKey(Department, on_delete=models.PROTECT) project_id = models.ForeignKey(Project, on_delete=models.PROTECT) class Meta: managed = True db_table = 'vmlist_cluster_name' def __str__(self): return self.name class ClusterPooling(models.Model): id = models.AutoField(primary_key=True) address = models.CharField(null=True, max_length=120) username = models.CharField(null=True, max_length=50) password = models.BinaryField(null=True) cluster_name_id = models.ForeignKey(ClusterName, null=True, on_delete=models.PROTECT) active = models.BooleanField(null=True) class Meta: managed = True db_table = 'vmlist_cluster_polling' def __str__(self): return self.address I know you can transfer data from one table to another using Django, but I have no idea what … -
How can make foreignKey from the same table in django?
How can make foreign-key from the same table in Django admin? For example, I have data of persons with first name and last name: Joe Ni Joe Ri Bob Gh and I have a Person model: class Person(models.Model): name = models.CharField(max_length=25) lname = models.CharField(max_length=25, blank=False) def __str__(self): return str(self.name) class MyModel(models.Model): first_name = models.ForeignKey(Person, on_delete=models.CASCADE) last_name = models.ForeignKey(Person, on_delete=models.CASCADE) Now i wanna choose for example the value 'Joe' in "MyModel" and then it will show me all the other valid options for this first name: NI, RI How can i do it? TNX guys -
Cannot raise ParseError from Django ViewSet
I have a method in a ViewSet where I want to validate that request.data is a list. If it is not, I would like to raise a ParseError(). However, my code crashes when I actually raise said ParseError and I don't understand why. I can easily raise ValidationError()s and both are subclasses of APIException, which the documentation states to be handled automatically. # views.py class MyViewSet(viewsets.GenericViewSet): ... @action(methods=['post'], detail=False, url_path='bulk-create') def bulk_create(self, request, *args, **kwargs): # Assert that request.data is a list of objects if not isinstance(request.data, list): raise ParseError("Expected the data to be in list format.") # Actually process incoming data ... Calling the route with anything other than a list correctly triggers my if statement, but instead of returning a proper response with status.HTTP_400_BAD_REQUEST, the server crashes and I receive the following error: Traceback (most recent call last): 2022-05-17T12:23:45.366216553Z File "/opt/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner 2022-05-17T12:23:45.366221178Z response = get_response(request) 2022-05-17T12:23:45.366223345Z File "/opt/venv/lib/python3.9/site-packages/debug_toolbar/middleware.py", line 67, in __call__ 2022-05-17T12:23:45.366225470Z panel.generate_stats(request, response) 2022-05-17T12:23:45.366238220Z File "/opt/venv/lib/python3.9/site-packages/debug_toolbar/panels/request.py", line 30, in generate_stats 2022-05-17T12:23:45.366240470Z "post": get_sorted_request_variable(request.POST), 2022-05-17T12:23:45.366346803Z File "/opt/venv/lib/python3.9/site-packages/debug_toolbar/utils.py", line 227, in get_sorted_request_variable 2022-05-17T12:23:45.366352511Z return [(k, variable.getlist(k)) for k in sorted(variable)] 2022-05-17T12:23:45.366354803Z TypeError: '<' not supported between instances of 'dict' and 'dict' Because of the … -
Django admin import-export one model and two different csv files depending select options?
I am using django-import-export, and want to import to one model different CSV files. I mean for example I have a model Statement class Statement(models.Model): amount = MoneyField(max_digits=14, decimal_places=4, default_currency='EUR', currency_field_name='currency', default="0.0000", currency_max_length=5, null=True ) type = models.CharField(name='type', choices=Type.choices, max_length=50, default=Type.INCOME) But I want to import statement files from different bank accounts, and, of course, the structure of each file can be different. One bank has CSV like ref_code, amount, currency, direction 1569852, 10.00, EUR, Income The second bank has a structure Order number, Amount, Curr, Account No 569486, 10.99, EUR, BE658954412 But I want to import this data, parse and insert it into the same table. I created a Resource class, Custom Import Form, etc. class StatementResource(resources.ModelResource): amount = Field(attribute='amount', column_name='Amount') currency = Field(attribute='currency', column_name='Currency') class Meta: model = Statement ... class CustomImportForm(ImportForm): bank = forms.ModelChoiceField( to_field_name='pk', queryset=Bank.objects.all(), required=True) Then I rewrite get_import_data_kwargs @admin.register(Statement) class StatementAdmin(ImportExportModelAdmin): resource_class = StatementResource def get_import_form(self): return CustomImportForm def get_import_data_kwargs(self, request, *args, **kwargs): form = kwargs.get('form') if form: return {"bank": form.cleaned_data["bank"]} return dict() But how to parse CSV depending on which bank is selected? -
How to display KML layers on google maps JavaScript
What is the best practice to display KML layers on google maps js? I have an HTML page with google maps on it that takes some arguments and context from Django view and displays back a map with some info like KML Layers . Here is how I do this : Map HTML page <script> // Initialize and add the map let poly; let map; let bounds = []; let cords = []; let point_1_marker = []; let point_2_marker = []; let normaPointMarker = []; let flightPlanCoordinates = []; let pt1; let pt2; let kmlLayer; function initMap() { const lat = "{{lat}}"; const lng = "{{lng}}"; const myLocation = { lat: parseFloat(lat), lng: parseFloat(lng) }; const map = new google.maps.Map(document.getElementById("map"), { zoom: 14, center: myLocation, zoomControl: false, streetViewControl: false, fullscreenControl: false, }); const marker = new google.maps.Marker({ position: myLocation, map: map, }); {% if go_to_my_location %} console.log("loc true"); map.setCenter(myLocation); {% endif %} //Breach Part {% if breach == 'true' %} var isClosed = false; var poly = new google.maps.Polyline({ map: map, path: [], strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 2 }); var clickedPoints = [] google.maps.event.addListener(map, 'click', function (clickEvent) { if (isClosed) return; var markerIndex = poly.getPath().length; var isFirstMarker = markerIndex … -
How do you list blog posts from a specific category?
So the site is built similarly to a blog. Basically update=post and timeline=catagory I'm trying to make a page where the categories are listed and you can click on them and it will list all the posts under that category. Right now, it will list the categories and when you click on it, it does go to the specific one, but how do I list all the articles inside it? Right now all I can do is display the title of the category. I realize that's because I've created the queryset for the catagory but Is there a way to call upon the posts corresponding to that category in my HTML? Or do I have to switch to using the post in my queryset. If so how do I do that because I tried and boy did that create a lot of errors. models.py urls.py views.py timelineArticles.html timelines.html -
Django - modify login view using built in login mechanism
I have created login mechanism basing on build in functionality and using this tutorial: https://learndjango.com/tutorials/django-login-and-logout-tutorial Now I need to access what is entered in username field in build in view created by django.contrib.auth. Need to do this from login view because i need to log failed login attempt with IP adress. The problem is i do not have this view in my views.py because its somehow built-in urls.py: urlpatterns = [ [...] path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), [...] ] .../templates/registration/login.html [...] <form method="post"> {% csrf_token %} <h2><p class="font-weight-bold">{{ form.as_p }}</p></h2> <button type="submit" class="btn btn-dark">Login</button> </p> </form> [...] How to access or eventually overwrite this view without changing anything else within app. -
Django .save() method not saving
I'm trying to save a text imput from an HTML page, and then display it on a redirect. It seems that the .save() method isn't working. I'm quite new to Django and HTML in general. I've followed the official Django tutorial and trying to apply the concepts from that into this app. Basically, it is supposed to take a user input from an HTML page and then save it to a list of names. Then, I want to redirect to another page which displays a list of these names. Anyone have any ideas? Here's my code: In views.py: from django.shortcuts import render, HttpResponseRedirect, redirect from .models import Contact def addListing(request): if request.method == 'POST': new_contact = Contact( full_name=request.POST['fullname'], ) new_contact.save() return redirect('listings') return render(request, 'farmsearch/add_listing.html') def listings(request): farms = Contact.objects.all() return render(request, 'farmsearch/listings.html', {'farms': farms}) In models.py: from django.db import models class Contact(models.Model): full_name = models.CharField(max_length=250) def __str__(self): return self.full_name In add_listing.html: <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]> <html class="no-js"> <![endif]--> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link … -
trying to use channels in Django caused these errors
I was trying to use channels in Django, To do that I followed a tutorial and made these changes in the asgi.py file from channels.routing import ProtocolTypeRouter application = ProtocolTypeRouter( { "http":get_asgi_application() }) and these in the settings.py file ASGI_APPLICATION = 'lostAndFound.wsgi.application' after that, i restarted the server and got an internal server error, and the error in the terminal `Exception inside application: WSGIHandler.__call__() takes 3 positional arguments but 4 were given Traceback (most recent call last): File "/home/alaa/.local/lib/python3.10/site-packages/channels/staticfiles.py", line 44, in call return await self.application(scope, receive, send) TypeError: WSGIHandler.call() takes 3 positional arguments but 4 were given` can anyone plese help me with this -
Django many-to-many model generation
I am making an offer creation module in Django, I have a product and a variant object, the product variant is connected with a many-to-many relationship. What I want to do is to save the products by selecting them while creating the offer, but at the same time to offer the option to choose the variants under the products. The problem here is that the products and variants are not separate. model.py class offerProductVariant(models.Model): offerProduct = models.ManyToManyField(product) offerVariant = models.ManyToManyField(variant) class offer(models.Model): offerName = models.CharField(max_length=50) offerCustomer = models.ForeignKey(customer,on_delete=models.CASCADE,null=True,blank=True) offerCompany = models.ForeignKey(company,on_delete=models.CASCADE,blank=True) offerDate = models.CharField(max_length=40) offerProductVariantMany = models.ManyToManyField(offerProductVariant,blank=True) views.py def teklifsave(request): if not request.user.is_authenticated: return redirect('login') if request.method == 'POST': form = offerCreate(request.POST) form2 = offerCreateProduct(request.POST) if form.is_valid(): m = offer( offerName = form.cleaned_data['offerName'], offerCompany = form.cleaned_data['offerCompany'], offerCustomer = form.cleaned_data['offerCustomer'], offerDate = form.cleaned_data['offerDate'] ) m.save() if form2.is_valid(): op = offerProductVariant() op.save() fproducts = form2.cleaned_data['offerProduct'] print(fproducts) fvariants = form2.cleaned_data['offerVariant'] print(fvariants) for fproduct in fproducts: print(fproduct) op.offerProduct.add(fproduct) op.save() for fvariant in fvariants: print(fvariant) op.offerVariant.add(fvariant) op.save() m.offerProductVariantMany.add(op) return redirect('offer') return redirect('offer') -
Problems with Django forms and Bootstrap
Im making a form in django, were I style it with Widgets: from django.forms import ModelForm, TextInput, EmailInput, NumberInput from .models import * class DateInput(forms.DateInput): input_type = 'date' class PatientForm(ModelForm): class Meta: model = Patient fields = ['fornavn', 'efternavn', 'email', 'birthday', 'id_nr'] widgets = { 'fornavn': TextInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Fornavn' }), 'efternavn': TextInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Efternavn' }), 'email': EmailInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Email' }), 'birthday': DateInput(attrs={ 'format':'DD/MM/YYYY', 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'dd/mm/yyyy', }), 'id_nr': NumberInput(attrs={ 'class': "form-control", 'style': 'max-width: 300px;', 'placeholder': 'Ønsket patientnummer' }), } However when inserting the form in the template with a Bootstrap Card styling, the form isnt rendering, and I'm left with only the names of the input fields, no fields for input and even missing the submit button. Template as follows: {% load crispy_forms_tags %} {% block content %} <div class="container p-5"> <div class="row p-5"> <div class="card p-3" style="width: 40rem;"> <h3 class="p-2 m-1">Opret patient</h3> <hr> <form action="" method="post" class=""> {% csrf_token %} {{ form|crispy }} <input type="submit" name="Opret" class="float-end"> </form> </div> </div> </div> {% endblock %} Any suggestions? -
How to make model.ImageField as mandatory in django admin?
I need to make upload image in django admin panel as a mandatory field, is there any possibility? Here what i did. **Model.py** class ContentData(models.Model): title = models.CharField(max_length=100,null = True) description = models.TextField(null=True) image = models.ImageField(upload_to="uploads", blank=True) is_active = models.IntegerField(default = 1, blank = True, null = True, help_text ='1->Active, 0->Inactive', choices =( (1, 'Active'), (0, 'Inactive') )) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title -
Django graphene: add field resolver with saving of the type inherited from the model
I have a node inherited from the model: class OrderModel(models.Model): FAILED = "failed" REQUIRES_PAYMENT_METHOD = "requires_payment_method" ORDER_STATUSES = ( (FAILED, FAILED), (REQUIRES_PAYMENT_METHOD, REQUIRES_PAYMENT_METHOD), ) STATUSES_MAP_FOR_NOT_ADMINS = { REQUIRES_PAYMENT_METHOD: FAILED, } status = models.CharField(_('status'), choices=ORDER_STATUSES, default=NEW_ORDER, max_length=255) class Meta(object): db_table = 'order' verbose_name = _('order') verbose_name_plural = _('orders') class OrderNode(PrimaryKeyMixin, DjangoObjectType): status = graphene.String def resolve_status(self, info): if info.context.user.is_admin: return self.status return self.STATUSES_MAP_FOR_NOT_ADMINS.get(self.status, self.status) class Meta: model = OrderModel filter_fields = GrantedOrderFilter.Meta.fields interfaces = (relay.Node, ) I want to add a custom status resolver to map statuses displayed for the users. But with the current implementation, I'm losing the typing for the status field. Is there any way I can save typing generated from the model and add the custom resolver? -
connection to server at "localhost" , port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections?
I am doing a project using django rest framework. It was working ok, but at the moment I am getting error connection to server at "localhost"(127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? I knew that the problem with postgresql. Because I've tried to connect it with pgadmin, and also gives me this error. I am using Ubuntu OS, when I checked ubuntu not listening port 5432. postgresql.conf # - Connection Settings - listen_addresses = '*' # what IP address(es) to listen on; # comma-separated list of addresses; # defaults to 'localhost'; use '*' for > # (change requires restart) port = 5432 # (change requires restart) max_connections = 100 # (change requires restart) #superuser_reserved_connections = 3 # (change requires restart) #unix_socket_directories = '/var/run/postgresql' # comma-separated list > # (change requires restart) When I run service postgresql status, it says following. ● postgresql.service - PostgreSQL RDBMS Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor pr> Active: active (exited) since Tue 2022-05-17 09:22:03 +05; 1h 9min ago Process: 6270 ExecStart=/bin/true (code=exited, status=0/SUCCESS) Main PID: 6270 (code=exited, status=0/SUCCESS) May 17 09:22:03 mirodil-vivobook systemd[1]: Starting PostgreSQL RDBMS... May 17 09:22:03 mirodil-vivobook systemd[1]: Finished PostgreSQL RDBMS. Here is … -
How to get ETA when fetch data from postgres?
I have Django project and in some view users can select what data their want to fetch from DB. But when query is large and fetching take some time ~ 10min users dont know there is an error or just fetching time. How can i get aproximatelly execution time when fetching data from postgres? And how can i display that? -
Django | Not Found issue while updating record
Other Coding I did ***urls.py of web app path adding ***: path('update/updaterecord/int:id', views.updaterecord, name='updaterecord'), views.py file of web app : update coding info: def updaterecord(request, id): first = request.POST['first'] last = request.POST['last'] member = Members.objects.get(id=id) member.firstname = first member.lastname = last member.save() return HttpResponseRedirect(reverse('index')) -
Python Django Rest - Return extra field with lowest, highest and average values of some other field
I'm new to Django and APIs in general and I want to create a Django based API using Django Rest Framework. Here's what I want to do: Endpoint to age range report: curl -H 'Content-Type: application/json' localhost:8000/reports/employees/age/ Response: { "younger": { "id": "1", "name": "Anakin Skywalker", "email": "skywalker@ssys.com.br", "department": "Architecture", "salary": "4000.00", "birth_date": "01-01-1983"}, "older": { "id": "2", "name": "Obi-Wan Kenobi", "email": "kenobi@ssys.com.br", "department": "Back-End", "salary": "3000.00", "birth_date": "01-01-1977"}, "average": "40.00" } Endpoint to salary range report: curl -H 'Content-Type: application/json' localhost:8000/reports/employees/salary/ Response: { "lowest ": { "id": "2", "name": "Obi-Wan Kenobi", "email": "kenobi@ssys.com.br", "department": "Back-End", "salary": "3000.00", "birth_date": "01-01-1977"}, "highest": { "id": "3", "name": "Leia Organa", "email": "organa@ssys.com.br", "department": "DevOps", "salary": "5000.00", "birth_date": "01-01-1980"}, "average": "4000.00" } I have two apps, employees and reports. Here's employees/models.py: class Employee(models.Model): name = models.CharField(max_length=250, default='FirstName LastName') email = models.EmailField(max_length=250, default='employee@email.com') departament = models.CharField(max_length=250, default='Full-Stack') salary = models.DecimalField(max_digits=15, decimal_places=2, default=0) birth_date = models.DateField() Here's employees/serializers.py: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ['id', 'name', 'email', 'departament', 'salary', 'birth_date'] I'm not sure how to create my views and serializers for my report app. How should I approach this? How can I return an extra field with a calculation between values of another … -
Django Views filter objects by user from custom model
I've created custom user model, and i'm trying to filter data in views.py by that user. The error i get is: 'SomeClassView' object has no attribute 'user' My goal is to 'encapsulate' data for each user. user model: class CustomUserManger(BaseUserManager): use_in_migrations = True def create_user(self, email, username, password, **other_fields): email = self.normalize_email(email) user = self.model(email=email, username=username, **other_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to staff') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to superusers') return self.create_user(email, username, password, **other_fields) class User(AbstractUser, PermissionsMixin): username = models.CharField(_('username'), max_length=20, unique=True) email = models.EmailField(unique=True) password = models.CharField(max_length=128) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) objects = CustomUserManger() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.username Views: class SomeClassView(viewsets.ModelViewSet): user = SomeClass.user serializer_class = WagonSerializer authentication_classes = (SessionAuthentication, ) @login_required def get_queryset(self): user = self.request.user return SomeClass.objects.filter(user=user) -
django-auth-ldap - modify debug messages / adding IP adress
Is it possible to somehow modify django-auth-ldap messages logged in log? I need to log IP adress alongside user if login failed: 2022-05-17 12:54:08 [DEBUG] Authentication failed for yyyyy: failed to map the username to a DN. 2022-05-17 12:54:32 [DEBUG] Authentication failed for xxxxx: user DN/password rejected by LDAP server. -
Connectivity issues to Sybase database as a secondary database with Django
I can connect to sybase database with FreeTDS and pyodbc as follows: # hello_sybase.py import pyodbc try: con = pyodbc.connect('Driver={FreeTDS};' 'Server=10.60.1.6,2638;' 'Database=blabla;' 'uid=blabla;pwd=blabla') cur = con.cursor() cur.execute("Select * from Test") for row in cur.fetchall(): print (row) cur.close() con.close() except Exception as e: print(str(e)) I tried to connect in a django view as follows: import pyodbc CONN_STRING = 'Driver={FreeTDS};Server=10.60.1.6,2638;Database=blabla;uid=blabla;pwd=blabla' def my_view(request): with pyodbc.connect(CONN_STRING) as conn: cur = conn.cursor() cur.execute('SELECT * FROM test') rows = list(cur.fetchall()) return render(request, 'my_template.html', {'rows': rows}) When I run python manage.py runserver and run the code in the above view. I have this error message '08001', '[08001] [FreeTDS][SQL Server]Unable to connect to data source (0) (SQLDriverConnect)') I tried to put TDS_Version=7.4 as was mentioned here in the comment, but it didn't helped. Is it possible that these are issues with the threading as is said in that comment? How can I fix it? The code works without django, but with python manage.py runserver it doesn't work. -
Django_jsonform not detecting changes, when attempting to makemigrations
I've added explanation to JSON form but when i attempt python manage.py makemigrations questions, says no changes detected in app "questions" I've added questions to INSTALLED_APPS in settings.py This only happens when i edit the JSON form. If i edit outside, then makemigrations work? class NewQuiz(models.Model): ITEMS_SCHEMA = { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'question_english': { 'type': 'string' }, 'answers': { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'answer_english': { 'type': 'string' }, 'is_correct': { 'type': 'boolean', 'title': 'Is correct', 'default': False, } } } }, 'explanation_english': { 'type': 'string' }, } } } How do i solve? -
isADirectoryError [Errno 21] while trying to render custom select form field
I am working with Python framework Django v2.2. I am trying to add custom attributes to <option> elements so that they are constructed as <option ext='xx'>. The forms are generated with Django admin templating and I am trying to extend them rather than creating completely new ones. My code: class CustomFormatSelect(forms.Select): def __init__(self, attrs=None, choices=(), disabled_choices=()): super(forms.Select, self).__init__(attrs, choices=choices) def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): if index: dataformat = DataFormat.objects.get(id=index) extension = dataformat.ext option = super(forms.Select, self).create_option(name, value, label, selected, index, subindex, attrs) option['attrs']['ext'] = extension return option format = forms.ModelChoiceField(queryset=DataFormat.objects.all(), required=True, widget=CustomFormatSelect(attrs={'class':'file_formats'})) I am using Django debug mode and after this chunk is executed I get error: [Errno 21] Is a directory: '.../miniconda3/envs/migrator_admin/lib/python3.7/site-packages/django/contrib/admin/templates' Further messages: In template .../templates/django/forms/widgets/select.html, error at line 3 And it points to line in template: 3 {% include option.template_name with widget=option %}{% endfor %}{% if group_name %} I am pretty new one to Django, so my question is should I do it this way (if it is solvable), or should I create completely new template which is separated from Django admin ? -
Django view not rendering - sidebar & header loads fine but main content does not load
I've been through so many different things and I just can't work it out; need a fresh set of eyes haha My view does not render and this seems to be the case across my apps and landing page - the sidebar and header loads fine, footer looks to partially load but I believe this is due to the fact the main content does not load. Current HTML page screenshot - not rendering view views.py from django.shortcuts import redirect, render from django.views import View from django.views.generic.base import TemplateView from django.contrib.auth.mixins import LoginRequiredMixin from django.core.paginator import Paginator from django.http import request from django.http.response import HttpResponse from django.conf import settings # Form Imports from .models import NewRecipeForm ######################################### # Form Pages # ######################################### # Recipe View class RecipesView(LoginRequiredMixin, View): def get(self, request): content = {} content['heading'] = "Recipes Database" content['pageview'] = "Recipes & Formulations" return render(request, 'nf_recipes/recipes-database.html', content) ######################################### # Form Pages # ######################################### # Add New Recipe Form class AddNewRecipeForm(LoginRequiredMixin, View): def get(self, request): add_new_recipe_form = NewRecipeForm() content = {} content['heading'] = "Add New Recipe" content['pageview'] = "Recipes & Formulations" content['add_new_recipe_form'] = add_new_recipe_form return render(request, 'nf_recipes/add-new-recipe.html', content) def post(self, request): if "add-new-recipe-submit" in request.POST: add_new_recipe_form = NewRecipeForm(request.POST) add_new_recipe_form.save() return redirect("/nf_recipes/recipe-db") # … -
Django db_router does not exclude app models as expected
I am trying to create an application where one server communicates with many other worker servers. Those servers will each have their own DB which should only contain the tables for their own models. I have created a database router which unfortunately does not work as the migrate command continues to create auth, contenttypes and virtually all Django application models in the database that as per the router, should contain none of that and only the worker server specific models. Expected in database: Worker Server Model 1 Actually produced in database: Worker Server Model 1 auth_group auth_group_permissions auth_permission auth_user auth_user_groups all the rest of the django models Code in Settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'server_1_db', 'USER': 'postgres', 'PASSWORD': 'admin', 'HOST': '127.0.0.1', 'PORT': '5432', } } DATABASE_ROUTERS = ['ApplicationServer_2.db_routers.RestRouter'] Router code: class RestRouter: app_labels = {"DoNOTadd", "auth", "admin", "sessions", "contenttypes"} def db_for_read(self, model, **hints): if model._meta.app_label not in self.app_labels: return 'default' return "For read db" def db_for_write(self, model, **hints): if model._meta.app_label not in self.app_labels: return "default" return "For write db" def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label not in self.app_labels or obj2._meta.app_label not in self.app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): … -
Want to build custom Audit logging
We have a enterprise application in django, want to do few enhancements Enhancements : i don't want to save log change data in django_admin_logs table in db, instead of this , we have a external service where we want to append all the logs there , There is a history page in django when we click on the models data , on history page what we want is to show data on that page by making a get call to audit service When we changed something in the entry we want to make a post call to audit service and with old and new data Can someone explain how can i achieve that