Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calculate multiple annotated properties based on 2-layer deep one-to-many relationships in Django
I am looking for a more-optimal way to get annotated values on records of a model when in order to calculate those values I must annotate a set of records on the base model, which needs to use values that IT calculates from a set of records on it. Here is the structure of the models: class Employee(models.Model): first_name = models.CharField() last_name = models.CharField() client = models.ForeignKey("app.Client") class DocumentTemplate(models.Model): name = models.CharField() warning_days = models.IntegerField() client = models.ForeignKey("app.Client") class EmployeeDocument(models.Model): document_template = models.ForeignKey("app.DocumentTemplate") employee = models.ForeignKey("app.Employee") @property def current_document(self): return self.documents.latest("date_added") @property def expiration_date(self): current_document = self.current_document if not current_document: return None return current_document.expiration_date @property def near_expiration_date(self): current_document = self.current_document if not current_document and current_document.expiration_date is not None: return None return currnet_document.expiration_date - timedelta(days=self.documenttemplate.warning_days) class EmployeeDocumentInstance(models.Model): employee_document = models.ForeignKey("app.EmployeeDocument", related_name="documents") date_added = models.DateTimeField(auto_now_add=True) expiration_date = models.DateField(null=True) document_instance_date = models.DateField(null=True) is_a_failure = models.BooleanField(default=False) When I retrieve Employee records, it is very common that I will need to know the following information for each employee records as well: are there any of my EmployeeDocuments that have zero EmployeeDocumentInstance's? how many of my EmployeeDocument.expiration_date values are less than today's date? how many of my EmployeeDocument.near_expiration_date values are less than today's date? I don't … -
"Can't connect to local MySQL Server" using SSH tunnel
Starting an SSH tunnel to MySQL so MySQL Workbench can connect to the remote DB using the following command: ssh -L 3306:localhost:3306 <username>@<domain> -N MySQL Workbench is able to connect without issue doing this. I was also trying to spin up a local copy of the Django application and connect to the remote test DB and I get met with: django.db.utils.OperationalError: (2002, 'Can\'t connect to local MySQL server through socket \'/var/run/mysqld/mysqld.sock\' (2 "No such file or directory")' Looking at the Django settings, everything looks correct. Just seems like Django is ignoring the tunnel despite using the same port. Django is in virtualenv so wonder if something there might be causing it. Any suggestions? -
how to check what port django used on a running server? `manage.py runserver 0.0.0.0:<port>`
I need to troubleshot a django app which already running in a server. I'd like to access the APP URL IP:PORT but I don't know what port former developer used to run it. Eg: manage.py runserver 0.0.0.0:<port> Is there a possibility to check out this used port with something like netstat -ano | grep ... netstat -ano | grep runserver doesn't provide anything. -
Configuring user permissions with django
299/5000 Hi, I wrote an API service with Django. I have authorized the user to list only clients via django admin panel. When I enter the django admin panel with the user name I authorize, there is no problem in the authorization. But when I access the api service, he never sees authority. Can you help me ? api/permissions.py from rest_framework.permissions import BasePermission class IsOwner(BasePermission): def has_permission(self, request, view): return request.user and request.user.is_authenticated message = "you cannot change data that you do not own !" def has_object_permission(self, request, view, obj): return (obj.user == request.user) or request.user.is_superuser views.py class CustomerListAPIView(ListAPIView): serializer_class = CustomerCreateSerializer permission_classes = [IsOwner] filter_backends = [SearchFilter] search_fields = ['customerName', 'customerSurname', 'customerIdentityNo'] def get_queryset(self): queryset = Customer.objects.filter(user=self.request.user) return queryset settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissions' ] } -
How do I prevent a 500 CORS error when attempting to create and download a csv file containing a large data set using python's StreamingHttpResponse?
The function runs and works perfectly fine for a small data set, but for a large data set, the following error is produced: (URL is hidden in the red) A 500 CORS error. As you can see from the code below, I've tried adding multiple response headers to the response (StreamingHttpResponse object) with a focus on extending the amount of time the function can run/execute/query before being timed out. I've also tried adding headers to handle the cross site issue which I don't believe is a problem in the first place because the function works perfectly fine with a small dataset: def create_and_download_csv(self, request): qs = self.filter_queryset(self.get_queryset()) serialized = self.serializer_class(qs, many=True) # mapping csv headers to columns headers = { "column_header": "Column Header", "column_header": "Column Header", "column_header": "Column Header", "column_header": "Column Header", } response = StreamingHttpResponse( renderers.CSVStreamingRenderer().render( serialized.data, renderer_context={'header': headers.keys(), 'labels': headers} ), content_type="text/csv", ) response["Access-control-Allow-Headers"] = "*" response["Connection"] = "keep-alive" response["Content-Disposition"] = 'attachment; filename="status.csv"' response["Access-Control-allow-origin"] = "*" response["Keep-Alive"] = 200 response["Timeout"] = 100 print(response) return response Perhaps I'm placing the headers in the wrong place? Or could it be that the docker container the project runs on is where I should configure the timeout value? Please help if you … -
Django Forms.py Change EmailField Value To Auto Populated value="{{ user.email }}"
I want my Django form's EmailField to auto populate with the user's email. How does this get accomplished? Full Code: https://dpaste.org/4PrR Instead of 'value':'hi' I want 'value':{{ user.email }} Code from forms.py: payment_email = forms.EmailField(widget=forms.TextInput(attrs={'class':'form-control', 'autocomplete':'off', 'type':'email', 'id':'email', 'value':'hi', 'readonly':'readonly'}), required=True) def __init__(self, *args, **kwargs): super(PaymentForm, self).__init__(*args, **kwargs) self.fields['payment_email'].label = "Email:" -
How do I write this Django query with two joins and where clauses?
Considering the following model scheme: class A(models.Model): b = models.ForeignKey(B, on_delete=models.CASCADE) x = models.IntegerField(blank=True, null=True) class B(models.Model): x = models.IntegerField(blank=True, null=True) class C(models.Model): b = models.ForeignKey(B, on_delete=models.DO_NOTHING) y = models.DateTimeField() How do I get the number of C objects from the database limited by a filter by both C.y and A.x? -
Need advice on SaaS project based on Django
I need advice: I want to create a Django App SaaS and Im on the point where I create Database Models. But how can I use a database for each customer without duplicate the code? I read a lot about database routing but nothing I can find passes to my solution. I want to have for each user a database which fits to Customer number example Customer 10001 gets DB 10001 which holds the same standard models plus his articles and configs. Base SQL is a mySQL I think if I just use one database it would out perform and gets slowly. regards Christopher. -
What is the Django query for the below SQL statement?
There is a simple SQL table with 3 columns: id, sku, last_update and a very simple SQL statement: SELECT DISTINCT sku FROM product_data ORDER BY last_update ASC What would be a django view code for the aforesaid SQL statement? This code: q = ProductData.objects.values('sku').distinct().order_by('sku') returns 145 results whereas this statement: q = ProductData.objects.values('sku').distinct().order_by('last_update') returns over 1000 results Why is it so? Can someone, please, help? Thanks a lot in advance! -
UpdateView using FormView
I have a Formview and an UpdateView which are conflicting with each other. They are supposed to work together but not in this way. Whenever I try to use the UpdateView the values get passed through the FormView for saving which causes it to send back form validation errors e.g. 'A video with this Title already exists'. How do I get the UpdateView to not rely on the FormView? Or to work with the FormView? It seems all the UpdateView is doing is pointing to the FormView. FormView: class VideoUploadView(FormView): form_class = VideoUploadForm success_url = '/videos' template_name = 'videos/video_form.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) form.instance.sender = self.request.user if form.is_valid(): form.save() # doing stuff form.save() messages.success(self.request, self.success_message) if request.is_ajax(): return JsonResponse({'success': True, 'url': reverse('videos-home')}) else: return redirect(self.success_url) else: if request.is_ajax(): return JsonResponse({'success': False, 'error': form.errors}) else: return render(request, self.template_name, {'form': form}) UpdateView: class VideoUpdateView(UpdateView): model = Video form_class = VideoUploadForm Urls.py: urlpatterns = [ path('', views.VideoListView.as_view(), name='videos-home'), path('upload/', views.VideoUploadView.as_view(), name='videos-upload'), path('<int:pk>', VideoDetailView.as_view(), name='videos-detail'), path('<int:pk>/delete/', VideoDeleteView.as_view(), name='videos-delete'), path('<int:pk>/viewed/', views.mark_as_viewed, name='mark-as-viewed'), path('<int:pk>/update/', VideoUpdateView.as_view(), name='videos-update'), path('<int:pk>/notify', VideoNotificationView.as_view(), name='videos-notify'), ] -
DJango Error -django.db.utils.DataError: value too long for type character varying(1)
I have been trying to do this data migration and i keep getting this error django.db.utils.DataError: value too long for type character varying(1) My goal is to add a row to the User table here is the migration file I have written, but I cannot find the model that has a max_length of 1 ''' # Generated by Django 2.2.7 on 2019-12-13 14:52 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('shared', '0001_initial'), ] def doit(apps, schema_editor): Tuser = apps.get_model('shared', 'User') nice = Tuser(user_id=True, first_name='Tom', last_name='Beals', membership= 'Di') nice.save() operations = [ migrations.RunPython(doit), ]``` here is my models.py file. (the model I referencing is the last one) # Create your models here. class Games(models.Model): game_id=models.AutoField(primary_key=True) game_name=models.CharField(max_length=15) game_odds=models.DecimalField(max_digits=5, decimal_places=2) class GameAccount(models.Model): game_account_id=models.AutoField(primary_key=True) class Deck(models.Model): image = models.ImageField(upload_to='images/deckOfCards/') suit = models.CharField(max_length=30) rank = models.CharField(max_length=30) worth = models.IntegerField() class Dice(models.Model): image = models.ImageField(upload_to='images/dieFace/') side = models.IntegerField class Rooms(models.Model): BED_CHOICES=[ ('S', 'Single'), ('D', 'Double'), ('Q', 'Queen'), ('K', 'King'), ] FLOOR_CHOICES = [ ('1', 'First'), ('2', 'Second'), ('3', 'Third'), ('4', 'Fourth'), ] room_num=models.AutoField(primary_key=True) room_price=models.DecimalField(max_digits=5, decimal_places=2) room_bed=models.CharField(max_length=30, choices=BED_CHOICES) room_floor=models.CharField(max_length=30, choices=FLOOR_CHOICES) class UserAuth(models.Model): user_auth_id=models.AutoField(primary_key=True) user_username=models.CharField(max_length=30) user_pass=models.CharField(max_length=12) class UserHistory(models.Model): user_history_id=models.AutoField(primary_key=True) previous_account_balance=models.DecimalField(max_digits=5, decimal_places=2) average_user_stay=models.DateTimeField() class UserAccount(models.Model): user_account_id=models.AutoField(primary_key=True) user_account_alias=models.CharField(max_length=30) user_account_balance=models.DecimalField(max_digits=5, decimal_places=2) user_account_image=models.ImageField(upload_to='images/userAccountImage/') class UserResortConfig(models.Model): user_resort_config_id=models.AutoField(primary_key=True) is_return_user=models.BooleanField() class UserResortData(models.Model): user_resort_data_id=models.AutoField(primary_key=True) … -
Django missing 1 required positional argument "username"
My error: create_superuser() missing 1 required positional argument: 'username' def create_superuser(self, email, username, password): user = self.create_user( email = self.normalize_email(email), password=password, username = username, ) user.is_admin = True user.is_superuser = True user.save(using=self._db) return user what is the problem? -
django dynamic custom queryset
I have a table to store view events, that is, if a user views an entity, a record will be stored into that table. This table is represented by a model that has a generic relation, that is, it can be related to any other model. I have defined a mixin ViewTracked that should be extended by any model that can be tracked (i.e. class SomeModel(ViewTracked)). I want to have a custom method for queryset of objects manager called custom_method for example. I know that I can define a custom Manager and override the objects manager with it easily, but the problem is that the tracked model can already have a custom manager that has his own custom queryset, so I can't simply override it and lose the custom queryset that it has. Unfortunately, I couldn't find a proper way of doing this, so I tried to add a metaclass to override the manager's get_queryset and add my custom method to it, but for some reason, when I call SomeModel.objects it always returns None. Here's what I tried: # Meta class class ViewTrackedMeta(ModelBase): def __new__(mcs, class_name, base_classes, attributes_dict): # let ModelBase do its magic new_class = super().__new__(mcs, class_name, base_classes, attributes_dict) … -
Change Django Form Attribute on view
I'm using a Django Form with a DatePicker widget. I have to define the Min and Max date of the datepicker on a class level. I would like to have these two values change when I run my view, otherwise, it keeps the Min and Max date values from the time that I start my django server. from django import forms from bootstrap_datepicker_plus import DatePickerInput import pandas as pd import datetime as dt MIN_DATE = dt.datetime.today().strftime('%m-%d-%Y') MAX_DATE = (dt.datetime.today() + dt.timedelta(days=92)).strftime('%m-%d-%Y') class TableEdit(forms.Form): Account = forms.CharField(label='Account', max_length=10) Hedge = forms.CharField(label='Hedge', max_length=10) Date = forms.DateField(widget=DatePickerInput( options={ 'format': 'MM/DD/YYYY', 'minDate': MIN_DATE, 'maxDate': MAX_DATE })) How can I modify my MIN_DATE and MAX_DATE form attributes everytime that I call my form from a view? Thank you -
Python - Is there a way to memoize calculations after serialization?
Is there a way to memoize or cache some calculations after serializing a queryset using Django REST? I need to group array of objects by some property. This calculation happens every request, but the serialized data is not dynamic at all, it changes every 1-2 days, so I want to cache it somehow. class ServiceViewSet(viewsets.ModelViewSet): queryset = Service.objects.all() serializer_class = ServiceSerializer def list(self, request, *args, **kwargs): service_list = self.serializer_class(self.queryset, many=True).data # I want to memoize calculations below groupped_services = defaultdict(list) for service in service_list: category_model = service.get('category_m', None) if category_model: groupper = category_model.get('category_title') groupped_services[groupper].append(service) return Response(groupped_services) Maybe it would be even more useful to memoize serialization as well? But I don't know how to do that. -
Using Django celery/Celery to send emails at a particular time
I want to use celery to handle sending of mails at a particular minute, hour or day. I set up CELERYBEAT_SCHEDULE to send the mails every 30 minutes but it doesn't work, rather it sends in less than 30seconds. I also set up crontabs and periodic tasks in my django admin but it doesn't work. I really don't know what I am doing wrong. It's my first time working with celery. Here are my codes: settings.py from __future__ import absolute_import from celery.schedules import crontab INSTALLED_APPS = [ 'djcelery', ........, ] BROKER_URL = 'redis://h:pa318d80536cde1a525616ac73eeb981a1b57cab3b72d4@ec2-107-21-8-30.compute-1.amazonaws.com:25389' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' import djcelery djcelery.setup_loader() CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" CELERYBEAT_SCHEDULE = { 'add-every-30-minutes': { 'task': 'nueoffshore.tasks.SendEmailTask', 'schedule': crontab(minute='*/15'), 'args': (16, 16), }, } celery.py from __future__ import absolute_import from django.conf import settings import os from celery import Celery, signals # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mycareer.settings') os.environ.setdefault('FORKED_BY_MULTIPROCESSING', '1') app = Celery('mycareer') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py from celery import task from celery.task import Task from django.core.mail import EmailMessage class SendEmailTask(Task): def run(self, content): … -
Send email to address getting from HTML input via Django
I'm searching for solution to this problem for many hours but can't find anything related. I want to get user's email from input and send mail from admin to that email address. Here are my codes: views.py: def index(request): context = { 'questions': Question.objects.all(), 'applicants': Applicant.objects.filter(status=1), 'empty_cards': range(4 - Applicant.objects.filter(status=1).count()) } if request.method == "POST": if request.POST.get('message_text'): Message.objects.create( sender_name = request.POST.get('sender_name'), sender_email = request.POST.get('sender_email'), message_text = request.POST.get('message_text')) if request.method == 'POST': subject = 'Welcome !' message = 'We will back to you.' from_email = settings.EMAIL_HOST_USER recipient_list = 'don't know how to get email' send_mail(subject, message, from_email, recipient_list) return render(request, 'index.html', context) -
What kind of view is best for handling a form posted 'message' from a DetailView template in django
I have a Model 'Vacancy' and I have a DetailView that shows an instance of vacancy in the template 'vacancy_view.html'. This works fine Also in this template 'vacancy_view.html' I added a small form. So a user can write a message for this vacancy. <form action="{% url 'message_create' %}" method="post" > {% csrf_token %} <input type="hidden" name="vacancy_id" value="{{ vacancy.id }}"> <textarea name="message" cols="10" rows="4"></textarea> <button class=" btn btn-primary mt-3">Verstuur</button> </form> This form posts th 'id' of the current vacancy in a hidden field and the message is a large textfield as you can see. I have set up the urls.py so it can find the right view. The message should be saved in a new instance on a ManyToMany model that I have set up between 'Vacancy' and 'User'. In the View I have to : -1- compute the form-data, -2- create a new instance of Message and save it and -3- create the right succes url. I want to do this with a Class based View. Can this be done with a FormView? After half a day trying to get this to work I am totally lost. It seems like a standard problem. How is this best done. All the … -
Django model error. `no such table: django_session`
Making a simple Django model and showing the data on one page. After messing up my model, I commented the bad code out, removed all migration files except the __init__.py file, and deleted the db.sqlite3 (as described here: https://simpleisbetterthancomplex.com/tutorial/2016/07/26/how-to-reset-migrations.html). However, I started getting this Error no such table: django_session on my admin page. I still have 17 unapplied migration(s) How I messed up the model? I put in DecimalType without a default, the CLI gave me three options: they assign a value, I assign a value, or leave it blank. I chose the first option and ever since I've gone down the rabbit hole 🐇HELP It has been suggested that the route to my db.sqlite3 is wrong so here's my file tree and settings code: Model from django.db import models from django.conf import settings from django.utils import timezone from multiselectfield import MultiSelectField from decimal import Decimal class BuildingProduct(models.Model): # CHOICES SCHOOL_CHOICES = [ ('MBO', 'MBO'), ('VMBO', 'VMBO'), ('HBO', 'HBO'), ('OPLEIDINGSBEDRIJF', 'Opleidingsbedrijf'), ] CATEGORY_CHOICES = [ ('MATERIALS', 'Materials'), ('COURSE', 'Course'), ] # DATABASE FIELDS name = models.CharField(max_length=200) description = models.TextField() categories = MultiSelectField(choices=CATEGORY_CHOICES, blank=True) schooltype = models.CharField( max_length=20, choices=SCHOOL_CHOICES, default='MBO', ) # price = models.DecimalField( # max_digits=10, decimal_places=2, default=Decimal('0.0000') # ) … -
how to install msodbcsql17_17.4.2.1-1.deb driver for django mssql connection?
i am trying to connect django with MSSql server database using pip3 install django-pyodbc-azure but when i install driver msodbcsql17_17.4.2.1-1.deb it produce following error : Selecting previously unselected package msodbcsql17. (Reading database ... 340765 files and directories currently installed.) Preparing to unpack msodbcsql17_17.4.2.1-1.deb ... Unpacking msodbcsql17 (17.4.2.1-1) ... dpkg: dependency problems prevent configuration of msodbcsql17: msodbcsql17 depends on unixodbc (>= 2.3.1); however: Package unixodbc is not installed. dpkg: error processing package msodbcsql17 (--install): dependency problems - leaving unconfigured Errors were encountered while processing: msodbcsql17 any possiblity to connect django with mssql-server ? -
VS Code Python Django debugging in a dev container
I am developing a Python Django app in a Dockerized container. I have successfully setup remote debugging to attach to my Django server inside of a container. Me configuration is as follows. launch.json { "name": "Remote Django App", "type": "python", "request": "attach", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/app" } ], "port": 9001, "host": "localhost" } manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'llf_api.settings') try: from django.core.management import execute_from_command_line from django.conf import settings if settings.DEBUG: if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'): import ptvsd ptvsd.enable_attach(address=('0.0.0.0', 8001)) print("Attached remote debugger") except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() docker-compose.yml services: api: image: ${DOCKER_IMAGE_BASE}:${DOCKER_TAG} build: context: . dockerfile: ./Dockerfile.development env_file: - .env environment: - DATABASE_URL=postgres://username:password@db/db_name volumes: - .:/app command: > bash -c "wait-for-it --service db:5432 && python3 manage.py runserver 0.0.0.0:8000" ports: - "9000:8000" - "9001:8001" depends_on: - db tty: true stdin_open: true The problem is that I run VS Code inside of a dev container (the Dockerfile.development above). So VS Code is essentially running … -
Resolving Missing Variable on Django Form
I'm restructuring an e-commerce that is using saleor 1.0. What I'm trying to achieve is reducing the redundancy in the steps to make a payment on an item. The architecture for checkout/payment for saleor 1.0 requires the customer from the payment page to go to a separate page to select payment a type (e.g. stripe, braintree, razor etc) using a radio button and then submit that selection which then processes the order and goes to the confirmation page. OBJECTIVE: What I'm trying to do is remove the step of sending the customer to a page to select their payment type, but rather include that option on the payment page, which i feel makes the experience more seamless. ISSUE: When including stripe to the payment page, I am receiving an error message which is displayed on the page: << MISSING VARIABLE "form.payment_method_id.as_hidden" >> Also, stripe appears to be functioning, but when i submit credit card information i'm not redirected to the confirmation page. Payment.html - the syntax commented is what shipped with saleor: {% block paymentcontent %} <div class="row checkout"> <div class="col-lg-10 m-auto checkout__payment"> {% if order.user == user or not order.is_fully_paid %} {% if not order.is_fully_paid and order.billing_address %} {% … -
How can I create a (select image) like field inside django form?
I am creating an order-app which enables the user to order custom name tags. I need to create a field that enables the user to select his/her desired background. Every background will have a key or id. I am currently representing this field using a PositiveIntegerField because there is going to be a 100 plus backgrounds so it is time-consuming to import them as choices inside a list. from django.db import models class Sticker(models.Model): Lan = [ ('ar', 'عربي'), ('en', 'English'), ] name_field = models.CharField(max_length=40) school_field = models.CharField(max_length=40) grade_field = models.CharField(max_length=40) quantity = models.PositiveSmallIntegerField() language = models.CharField(choices=Lan, max_length=2) sticker_number = models.PositiveIntegerField() #image = models.ImageField(max_length=1, null= True) status = models.BooleanField(default=False) and this is how the form looks like, just used a simple ModelForm class to pass the fields. from .models import Sticker, CustomerDetails, DeliveryDetails class Meta: model = Sticker fields = ('name_field', 'school_field', 'grade_field', 'quantity', 'language', 'sticker_number') So I need a way to show the user images and to be able to select an image. I am trying to build this project without using previously build templates or forms and I am still a beginner in python and django. -
Django global camera device object
I'm using a camera device to capture images and display them on in my django web app. I can only create one instance of this device or else it will give an error saying the device is already attached to another client. My understanding is if django spawns multiple processes, the same code will be executed multiple times, which is what I don't want to happen. What is the best way to set this up so I can get images from the device, but without django attempting to create multiple instances of the device object? -
Django Crispy Forms CustomLayout with Fieldset
So I want to build a custom layout, that extends LayoutObject for a form that I have. class NewBookForm(LayoutObject): template = 'library/layouts/new_book_layout.html' def __init__(self, fields, template=None, *args, **kwargs): self.fields = fields # Overrides class variable with an instance level variable if template: self.template = template def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): fields = self.get_rendered_fields(form, form_style, context, template_pack, **kwargs) template = self.get_template_name(template_pack) return render_to_string(template, {'fields': fields}) And I'm calling it using self.helper.layout = Layout( NewBookForm(Fieldset('book_id', 'name', 'author)) ) Right now Django is saying "template does not exist." However, this is not getting me the result I'm looking for.