Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing data with CreateView in django
I am getting the error: NOT NULL constraint failed: films_comment.film_id On the comments page there is a form field called body for the comment itself, I also need it to store this comment against the user and the film. Models: from django.db import models from django.urls import reverse class Film(models.Model): title = models.CharField(max_length=200) director = models.CharField(max_length=200) description = models.CharField(max_length=200) pub_date = models.DateField('date published') def get_absolute_url(self): return reverse('films:detail', kwargs={'pk' : self.pk}) class Comment(models.Model): # user = models.ForeignKey(User, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) film = models.ForeignKey(Film, on_delete=models.CASCADE) body = models.CharField(max_length=200) Urls: app_name = 'films' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), # path('<int:film_id>/comment', views.add_comment, name='add_comment'), path('<int:pk>', views.DetailView.as_view(), name='detail'), path('<int:film_id>/comment/', views.CommentCreate.as_view(), name='add_comment'), ] Link on details page for adding a comment: <a href="{% url 'films:add_comment' film_id=film.id %}">Leave a comment</a> comment_form.py: <form action="" method="post"> {% csrf_token %} {% include 'films/form-template.html' %} <button type="submit">Submit</button> </form> Form template: {% for field in form %} {{field.errors}} <label>{{ field.label_tag }}</label> {{ field }} {% endfor %} forms.py from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) -
LINE 1: SELECT (1) AS "a" FROM "django_session"
I've created an environment in MacOS. Django version 1.10.6. In Linux every thing is okay, but in MacOS I got this error: ProgrammingError at / relation "django_session" does not exist LINE 1: SELECT (1) AS "a" FROM "django_session" WHERE "django_sessio... ^ Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.10.6 Exception Type: ProgrammingError Exception Value: relation "django_session" does not exist LINE 1: SELECT (1) AS "a" FROM "django_session" WHERE "django_sessio... An important thing is that I can't run migrates in "sites", only in each app. -
A DRYer solution to processing responsive thumbnails in Django template file
In order to display the appropriate image for a set of responsive breakpoints, I have put built a Context Processor that simply passes some Dicts with breakpoint and image resolution information. I then loop through these Dicts in order to generate responsive thumbnails as well as build the relevant CSS media queries. This solution works well for me now, but as I repeat this code on all template pages that need responsive imagery it becomes less and less DRY, yet I am not quite sure how I would abstract this functionality further. How can I make this thumbnail/responsive breakpoint-generating functionality more DRY? context_processors.py def thumbsizes(request): thumbsizes = { 'screensizes': [{ 'xs': '', 'sm': '796px', 'md': '1024px', 'lg': '1216px', 'xl': '1408px', }], 'hero': [{ 'xs': '600x827', 'sm': '900x400', 'md': '1200x400', 'lg': '1800x400', 'xl': '2400x400', }], 'main': [{ ... }], ... } return {"thumbsizes": thumbsizes} _hero.html {% with object.image as image %} {% with class_name=".c-hero" %} <style type="text/css"> {% for size in thumbsizes.hero %} {% for key, value in size.items %} {# Build thumbnail with value from size Dict #} {% thumbnail image value crop upscale subject_location=image.subject_location as thumb %} {# Do not apply media query for extra-small devices #} {% if … -
Conditional Django Model Creation
I am writing a app for django which i am planning to publish. This app requires a Bolean Setting variable CONSUMER_REGISTRATION. Aim of getting this variable is to decide whether to define ConsumerRegistrationModel or not. This is what I did. from django.db import models from django.conf import settings if getattr(settings, 'CONSUMER_REGISTRATION', False): class ConsumerRegistration(models.Model): ... Its working fine. The only Issue i am facing that developers will need to run makemigrations and migrate commands each time they change the variable in settings. 1- Can this work be automated ?. So if they change the variable then some code in django auto run the makemigrations and migrate commands. 2- Or is it perfectly fine to leave this work on developers ?? 3- Also I want to ask that is it a good aproach to do this in django ? -
Unclosed for tag in django. Looking for one of: empty, endfor
The error references {% for film in form %} not being closed in: form-template.html: {% for field in form %} {{field.errors}} <label>{{ field.label_tag }}</label> {{ field }} {$ endfor %} My comment_form.html: <form action="" method="post"> {$ csrf_token %} {% include 'films/form-template.html' %} <button type="submit">Submit</button> </form> urls.py: app_name = 'films' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), # path('<int:film_id>/comment', views.add_comment, name='add_comment'), path('<int:pk>', views.DetailView.as_view(), name='detail'), path('<int:film_id>/add/$', views.CommentCreate.as_view(), name='add_comment'), ] -
Django error noneType
I need some help. I don't know why i got this error. What does it mean? I have this site into a virtual machine and is running inside a webserver platform. Is this maybe due to the fact that the site is not hosted directly? [26/Jan/2018 16:28:52] "GET /static/css/custom.css HTTP/1.1" 200 7346 Traceback (most recent call last): File "/usr/lib/python3.4/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/usr/local/lib/python3.4/dist-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__ return super().__call__(environ, start_response) File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/wsgi.py", line 146, in __call__ response = self.get_response(request) File "/usr/local/lib/python3.4/dist-packages/django/contrib/staticfiles/handlers.py", line 62, in get_response return super().get_response(request) File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py", line 81, in get_response response = self._middleware_chain(request) TypeError: 'NoneType' object is not callable [26/Jan/2018 16:28:52] "GET /static/css/bootstrap.min.css.map HTTP/1.1" 500 59 Traceback (most recent call last): File "/usr/lib/python3.4/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/usr/local/lib/python3.4/dist-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__ return super().__call__(environ, start_response) File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/wsgi.py", line 146, in __call__ response = self.get_response(request) File "/usr/local/lib/python3.4/dist-packages/django/contrib/staticfiles/handlers.py", line 62, in get_response return super().get_response(request) File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py", line 81, in get_response response = self._middleware_chain(request) TypeError: 'NoneType' object is not callable Thank you! -
Django - retrieve information if only it's needed
I'm looking at building a site where you have a detail view of an object, and more data about that object can be shown to the user by clicking to open a modal pop up box. I was wondering how, in Django, this data can only be loaded if the user chooses to open the modal box - otherwise there's no point in it being there. def detail_view(request): ... extra_data = Object.objects.all().values_list('rating', flat=True) # Only required if a user open the modal box return render(request, 'detail.html', {'extra_data':extra_data}) Any ideas on how this might be achieved whilst using as little JavaScript as possible? -
How to get the JSON on url the DJANGO REST API framework?
How to display the result json at URL https://api.vk.com/method/friends.get?user_id=2183659&count=10&fields=nickname,photo_100 As in the picture: P.S. Google Translate. -
Django 2.0 haystack whoosh update index, rebuild index throw error
I am using django 2.0 with haystack+whoosh as a search. I configured as it is said in the documentation. Occurred problem is when i run ./manage.py rebuild_index it shows this error: Traceback (most recent call last): File "./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/zorig/.virtualenvs/ftm/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/zorig/.virtualenvs/ftm/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/zorig/.virtualenvs/ftm/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/zorig/.virtualenvs/ftm/lib/python3.5/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/zorig/.virtualenvs/ftm/lib/python3.5/site-packages/haystack/management/commands/rebuild_index.py", line 36, in handle call_command('clear_index', **options) File "/home/zorig/.virtualenvs/ftm/lib/python3.5/site-packages/django/core/management/__init__.py", line 133, in call_command ', '.join(sorted(valid_options)), TypeError: Unknown option(s) for clear_index command: batchsize, workers. Valid options are: commit, help, interactive, no_color, nocommit, noinput, pythonpath, settings, skip_checks, stderr, stdout, traceback, using, verbosity, version. after that i tried update_index it shows me this error: File "/home/zorig/.virtualenvs/ftm/lib/python3.5/site-packages/haystack/management/commands/update_index.py", line 214, in handle self.update_backend(label, using) File "/home/zorig/.virtualenvs/ftm/lib/python3.5/site-packages/haystack/management/commands/update_index.py", line 257, in update_backend commit=self.commit, max_retries=self.max_retries) File "/home/zorig/.virtualenvs/ftm/lib/python3.5/site-packages/haystack/management/commands/update_index.py", line 84, in do_update backend.update(index, current_qs, commit=commit) File "/home/zorig/.virtualenvs/ftm/lib/python3.5/site-packages/haystack/backends/whoosh_backend.py", line 185, in update doc = index.full_prepare(obj) File "/home/zorig/.virtualenvs/ftm/lib/python3.5/site-packages/haystack/indexes.py", line 208, in full_prepare self.prepared_data = self.prepare(obj) File "/home/zorig/.virtualenvs/ftm/lib/python3.5/site-packages/haystack/indexes.py", line 199, in prepare self.prepared_data[field.index_fieldname] = field.prepare(obj) File "/home/zorig/.virtualenvs/ftm/lib/python3.5/site-packages/haystack/fields.py", line 205, in prepare return self.convert(super(CharField, self).prepare(obj)) File "/home/zorig/.virtualenvs/ftm/lib/python3.5/site-packages/haystack/fields.py", line 88, in prepare values = self.resolve_attributes_lookup(current_objects, attrs) File "/home/zorig/.virtualenvs/ftm/lib/python3.5/site-packages/haystack/fields.py", … -
How can I get current user id in django views.py? (CBV)
I wanna get current user id in views.py (CBV) and pass it to forms.py. I didn't find any good answer. -
Storing Base64 instead of UUID in Postgres
Can I store it in a string field. Basically, I will generate a unique id using uuid function and then convert it to base64 that looks like in google then store that in the database. I'm planning to use cassandra in the future so I'm not sure if there's a performance hit if I'll use string as primary key there. I just want to know what's the best practice for this. Thank you. -
Not able to insert data into database
This is an excerpt of my view.py def routineInput(request): if request.method == 'POST': today = datetime.now form = CreateRoutine(request.POST) if form.is_valid(): return HttpResponseRedirect('/todo/saved/') else: form = CreateRoutine() return render(request, 'todo/croutine.html', {'form': form}) So the idea is that I have a simple input form where I put a name into it and it should push this name into a table in my database. My code is coming thorough and it shows my /todo/saved page but my POST request doesn't seem to get sent to my table or my table is rejecting it or something. -
'User' object is not iterable in Django 1.11.8
I have a model that have a ManyToManyField for users, and I want to record logged in user when he/she submits the form in Choice model, but this code is stopping me from doing so. I used the login_required decorator to force user to login first (that's what I want actually). models.py: from django.db import models from django.contrib.auth.models import User QUESTION_CHOICES = ( ("choice_1", "Choice 1"), ("choice_2", "Choice 2"), ("choice_3", "Choice 3"), ) class Choice(models.Model): users = models.ManyToManyField(User) choices = models.CharField(max_length=256, choices=QUESTION_CHOICES, unique=True) vote = models.IntegerField(default=0) def __str__(self): return self.choices + " " + "-" + " " + str(self.vote) views.py: from django.shortcuts import render from django.contrib.auth.decorators import login_required from .models import Choice @login_required def index(request): food = request.POST.get('sunday') user_v = None get_choices = Choice.objects.values('choices', 'vote') new_choices = list(get_choices) for q in new_choices: choice = q['choices'] vote_v = q['vote'] if food: if food == choice: if request.user.is_authenticated(): user_v = request.user print(user_v) # it prints out correctly after sucessful form submit vote_v += 1 model_conn = Choice.objects.get(choices=choice) model_conn.vote = vote_v model_conn.users = user_v # this is where I get an error model_conn.save() return render(request, 'index.html', {}) -
Django RF update_or_create
I am trying to update or create the following model: class Profile(models.Model): user = models.OneToOneField(AUTH_USER_MODEL, on_delete=models.CASCADE) canMakeEvent = models.BooleanField(default=False) with the serializer: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' and view: def post(self, request): answer, created = Profile.objects.update_or_create( user=request.user, canMakeEvent = request.data['canMakeEvent']) return Response() I understand the response isn't correct but the code to update_or_create is what I'm worried about primarily. The console outputs the following: UNIQUE constraint failed: event_profile.user_id -
How can I apply for loop in django template for creating array of same images?
I am in need of code in django template without javascript to display the length of same images based on number of votes. My current code is this: <div id="Results"> <h1>{{question.question_text}}</h1> {% for choice in question.choice_set.all %} <div id="votes"><img style="border-radius: 2px; border-width: 2px; border-style: none solid solid none; border-color: darkblue;" src='{{choice.image2.url}}'/> <div style=" float: right; width: 88%;"> <b>{{choice.choice_text}}</b> {{choice.votes}} vote{{choice.votes|pluralize}} </div> </div> {% endfor %} </ul> <p id="info">Your Vote Has Been Stored!!</p> <br> </div> Help me generate code with algorithm: increment for loop based on choice.votes. //for loop from i=0; i<{{choice.votes}}; i++ display of some image in array. // some image -
How to use models app in another app in django?
I'am looking a solution in my case. I have a website witch contains the main app calling 'bajki'. I've create a 2nd app calls 'ustawienia'. In 'ustawienia' I want to changing the thinks in <head> and footer section like: title, meta description, name of footer(like standard settings in populars cms). So I've create a class in models.py in 'ustawienia' app: # -*- coding: utf-8 -*- from django.db import models class Ustawienia(models.Model): title = models.CharField(max_length=75, verbose_name="Tytuł strony(title)") description = models.TextField(max_length=280, verbose_name="Opis META(description)") logo = models.CharField(max_length=150, verbose_name="Nazwa LOGO") footer = models.TextField(verbose_name="Opis stopki") class Meta: verbose_name = "Ustawienia Strony" verbose_name_plural = "Ustawienia Strony" def __str__(self): return self.title After I want to import models to main app calls 'bajki' In app 'bajki' views.py I've create: from ustawienia.models import Ustawienia def ustawienia(request): ustawienia = Ustawienia.objects.all() context ={'ustawienia': ustawienia,} return render(request, 'bajki/index.html', context=context) And in main app 'bajki' I created a url in urls.py from django.urls import path from bajki import views urlpatterns = [ path('', views.ustawienia, name="ustawienia"), ] In project url I've create something like : from django.contrib import admin from django.urls import path, include urlpatterns = [ ... path('', include('ustawienia.urls')), ] On the end I want to show in <head> section the site title … -
perform_destroy() in ManyToMany for selected models to remove() _ Django Restframework
suppose we have Model A. Model A has ManyToMany relation with model B.I need to delete selected object deleted in ManyToMany. models.py class B(models.Model): ...... class A(models.Model): title = models.Charfield(....) subscription = Models.ManyToManyField(B, related_name="subscribers", blank=True) Views.py class SubscribeAView(RetrieveUpdateDestroyAPIView): queryset = A.objects.all() serializer_class = ASerializer def perform_destroy(self, instance): subscribe = instance.subscription subscribe.remove() this method will delete all relations.but I need to tell delete the selected subscription from request.user -
Django: Pass GET argument to password rest email
I'm fairly new to django and I'm currently rewriting the django login views so I can move all the authentication process to a dedicated django app where I can redefine the templates. So currently I have an accounts app which url.py looks like that: from django.contrib.auth import views as auth_views from django.urls import path from . import views app_name = 'accounts' urlpatterns = [ path('login/', auth_views.login, {'template_name': 'accounts/login.html'}, name='login'), path('logout/', auth_views.logout, name='logout'), path('password_reset/', auth_views.password_reset, {'template_name': 'accounts/password_reset_form.html', 'email_template_name': 'accounts/password_reset_email.html', 'subject_template_name': 'accounts/password_reset_subject.txt', 'post_reset_redirect': 'done/'}, name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='accounts/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.password_reset_confirm, {'template_name': 'accounts/password_reset_confirm.html', 'post_reset_redirect': '/accounts/reset/done/'}, name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view( template_name='accounts/password_reset_complete.html'), name='password_reset_complete') ] And a accounts/password_reset_email.html which looks like this: {% autoescape off %} To initiate the password reset process for your {{ user.get_username }} account, click the link below: {{ protocol }}://{{ domain }}{% url 'accounts:password_reset_confirm' uidb64=uid token=token %}?origin_page={{ origin_page }}" ... Sincerely, The Team {% endautoescape %} What I want to do is to recover the origin_page argument so when the user click on the reset link from the email he get redirected to the right webpage after his password is reset. So far I tried to do this in password_reset_form.html: {% block content %} <p>Forgotten your password? Enter your email address … -
Django Rest Framework: Angular (Ionic) vs Postman requests validation error
I'm writing an app with Ionic and a server API with DRF. I want to create objects but make sure the user has one active instance of this object (in the model there is a boolean: done; see the serializer, it will make sense :) ). I have a postroute setup to create objects using generic views (Don't mind the custom permission). class WaitercallCreate(CreateAPIView): serializer_class = WaitercallCreateSerializer permission_classes = (IsAuthenticated, IsOrderOwnerAndFresh) In the serializer of the object there is a validate method: class WaitercallCreateSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.email') waitercall_id = serializers.ReadOnlyField(source='pk') class Meta: model = Waitercall fields = ('waitercall_id', 'order', 'user', 'done') read_only_fields = ('waitercall_id', 'user', 'done') def validate_done(self, value): qs = self.context['request'].user.waitercalls.exclude(done=True) if qs.exists(): raise serializers.ValidationError("There is already a pending waitercall for this user!") return value Now when I call the route using Postman, everything works as expected. The first creation comes through. If I hit the route and the done boolean hasn't been set to true by the other operations of the server, I get the correct validation error message. But, when I implemented the function in my app and called the route multiple times, the server creates an object for each call. Here is my function: makeWaitercall(type) { … -
Basic Entity Management System
How can I design an Entity Management system in Django which can be able to adapt to any kind of entity with minimal code changes (e.g. a product in a catalog, patient information in healthcare etc.). Adding, removing, modifying the attributes of an entity should be simple It should allow for nested attributes (sub-entities) e.g Patient -> Consulting doctor Each attribute or sub-entity in the entity can have a set of business rules -
Django rest framework - DefaultRouter - One-to-One Nested Relationship
I need to represent a nested RESTful resource via Django Rest Framework. I have a two Django models: User and Profile, with a 1 to 1 relationship between them. I want to expose the following API structure: GET /api/users/<user_pk>/ PATCH /api/users/<user_pk>/ And also endpoints that deal with the user's profile, such as: GET /api/users/<user_pk>/profile/ PATCH /api/users/<user_pk>/profile/ Another constraint, is that I would like to use drf DefaultRouters, in order to keep the overall project implementation homogeneous, but I got aware that DefaultRouters only provides not satisfactory approaches, for instance: GET profile-list not needed, since I need only one object, not a list; GET profile-detail /api/users/<user_pk>/profile/<profile_id>/ is non-sense to introduce the profile_id. So, what's the drf's DefaultRouter Best Practice, or better approach, for this 1to1 nested relationship? -
django(v2.0.1) -- _str_() method shows Object but not notes in self.text(python3.5)
My models.py is like this: enter image description here My python's version is 3.5.x and django's version is 2.0.1, and when I went to admin's page, I got this page: enter image description here -
How to update user profile in Django
I want to let my student to update his profile after he logged in, but I don't seem to be able to code the profile update properly. This is my code: class User(AbstractUser): pass class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=30, null=True, blank=True, default=None) surname = models.CharField(max_length=50, null=True, blank=True, default=None) <form method="POST" action="{% url 'profile_edit' %}" class="" > {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button>q </form> def profile_edit(request): user = request.student form = StudentForm(request.POST or None, initial={'name': user.name, 'surname': user.surname}) if request.method == 'POST': if form.is_valid(): user.student.name = request.POST['name'] user.student.surname = request.POST['surname'] user.save() return HttpResponseRedirect('index') context = { "form": form } return render(request, "registration/profile_edit.html", context) -
Iterate over all Django App models if Meta.managed = True
I want a script that iterates over all models for a given app that are managed=True and deletes the data. My non-managed models are views, etc that I don't want to touch. I am doing the following. It works. I want to know if there is a better or more pythonic way to do the same thing. Would it be sensible to define other Meta options in each model if I want to include or exclude them in such a method? from django.apps import apps def deletedata(): if app.upper() in [x.verbose_name.upper() for x in apps.get_app_configs()]: appmodels = apps.get_app_config(app).get_models() for appmodel in appmodels: if appmodel._meta.managed: appmodel.objects.all().delete() def main(): deletedata("foo") if __name__ == "__main__": main() -
Cannot find which model is getting error in Django
I have following model and after Migrate, I tried to add data through Admin page. However, I got the error NOT NULL constraint failed: HVAC_chiller.basicinfo_ptr_id. Referring to other stackoverflow, I understood problem. However, I cannot find any model which has attribute ptr. Does anyone know which attribute I should revise? models.py class BasicInfo(models.Model): title = models.CharField(max_length=100) manufacturer = models.CharField(max_length=50, blank = True) used_project = models.CharField(max_length=50, null=True,blank=True) cost=models.IntegerField(null = True, blank = True) url=models.URLField(null=True,blank=True) comment=models.TextField(null=True,blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class VRV(BasicInfo): InletT = models.FloatField(blank=True) OutletT = models.FloatField(blank=True) Capacity = models.IntegerField(blank=True) # Reference capacity COP = models.FloatField(blank=True) # Reference COP class CapacityFunction(models.Model): name=models.CharField(max_length=100, blank = True) c1=models.FloatField() c2=models.FloatField() c3 = models.FloatField() c4 = models.FloatField() c5 = models.FloatField() c6 = models.FloatField() minX= models.FloatField(blank=True) maxX = models.FloatField(blank=True) minY = models.FloatField(blank=True) maxY = models.FloatField(blank=True) def __str__(self): return self.name class EIRofTemp(CapacityFunction): pass class EIRofPLR(models.Model): name = models.CharField(max_length=100, blank=True) c1=models.FloatField() c2= models.FloatField() c3 = models.FloatField() c4 = models.FloatField(blank=True,null=True) minX = models.FloatField(blank=True) maxX = models.FloatField(blank=True) def __str__(self): return self.name class Chiller(VRV): CONDENSER_CHOICES = ( ('WaterCooled','WaterCooled'), ('AirCooled', 'AirCooled'), ('EvaporativelyCooled','EvaporativelyCooled') ) Condenser=models.CharField(max_length=15,choices=CONDENSER_CHOICES,default='Water') CHWFlowRate=models.FloatField(blank=True,null=True) CWFlowRate=models.FloatField(blank=True,null=True) minPLR=models.FloatField(blank=True,null=True) maxPLR=models.FloatField(blank=True,null=True) optimumPLR=models.FloatField(blank=True,null=True) minUnloadRatio=models.FloatField(blank=True,null=True) CapacityFunction=models.OneToOneField(CapacityFunction,blank=True,null=True,on_delete=models.CASCADE,related_name='cap') EIRofTemp=models.OneToOneField(EIRofTemp,blank=True,null=True,on_delete=models.CASCADE,related_name='eirtemp') EIRofPLR = models.OneToOneField(EIRofPLR, blank=True,null=True, on_delete=models.CASCADE,related_name='eirplr')