Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DRF change serializer data with CreateListModelMixin
I have this class view, but I am unable to modify the serializer data to insert more data (which is needed and needs to be populated automatically). Because I am creating many instances at once, the serializer is based on kwargs['many'] = True. Any idea on how I can add another field to each serializer data? Thanks, : class ReservedServiceView(CreateListModelMixin, ModelViewSet): queryset = ReservedService.objects.all() serializer_class = ReservedServiceSerializer authentication_classes = (authentication.TokenAuthentication,) def perform_create(self, serializer): # Create an event that is a Reflection of the Reserved Service serializer_data = self.request.data for reserved_service in serializer_data: print("--------",reserved_service, flush=True) service_id = reserved_service['original_service'] original_service = Service.objects.get(pk=service_id) calendar_event = CalendarEvent() calendar_event.name = original_service.name calendar_event.description = original_service.description calendar_event.date = reserved_service['date'] calendar_event.type_id = 1 calendar_event.start_time = reserved_service['start_time'] calendar_event.end_time = reserved_service['end_time'] calendar_event.location_id = original_service.location.id calendar_event.save() reserved_service['associated_event'] = calendar_event.id print("**********1", serializer_data) print("**********2", self.request.data) serializer.save() Based in: class CreateListModelMixin(object): def get_serializer(self, *args, **kwargs): """ if an array is passed, set serializer to many """ if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super(CreateListModelMixin, self).get_serializer(*args, **kwargs) -
Change POST method from Flask to Django
I have this code from a Flask application: def getExchangeRates(): """ Here we have the function that will retrieve the latest rates from fixer.io """ rates = [] response = urlopen('http://data.fixer.io/api/latest?access_key=c2f5070ad78b0748111281f6475c0bdd') data = response.read() rdata = json.loads(data.decode(), parse_float=float) rates_from_rdata = rdata.get('rates', {}) for rate_symbol in ['USD', 'GBP', 'HKD', 'AUD', 'JPY', 'SEK', 'NOK']: try: rates.append(rates_from_rdata[rate_symbol]) except KeyError: logging.warning('rate for {} not found in rdata'.format(rate_symbol)) pass return rates @app.route("/" , methods=['GET', 'POST']) def index(): rates = getExchangeRates() return render_template('index.html',**locals()) For example, the @app.route decorator is substituted by the urls.py file, in which you specify the routes, but now, how can I adapt the methods=['GET', 'POST'] line to a Django way? I'm a little bit confused on that, any ideas? -
Django - Form not updating in Django admin
I’m creating a profile page in my web application & I have a form to when the user makes a form submission I need the data from the form to update in django admin from the current logged in user. My Problem: The data populates in the django admin after a form submisstion however I need the data updating only and not to keep repeating listings per form submission. How do I execute this correctly with my current code? The Custom User Model I’m using is located in from users.models import CustomUser if that helps. Any help i gladly appreciated, Cheers Screenshot user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from user_profile.forms import HomeForm from users.forms import CustomUserCreationForm, CustomUserChangeForm from user_profile.models import Listing from users.models import CustomUser # Register models here. class UserProfileAdmin(admin.ModelAdmin): list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'user'] list_filter = ['name', 'zip_code', 'created', 'updated', 'user'] admin.site.register(Listing, UserProfileAdmin) user_profile/models from django.contrib import auth from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.forms import CustomUserCreationForm, CustomUserChangeForm from … -
mongoengine isn't an available database backend for Django
I am trying to use mongoengine as my database I can't address the problem I downloaded mongoengine but it seems like django isn't accepting it. I get this error when I runserver django.core.exceptions.ImproperlyConfigured: 'django_mongodb_engine' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' I have seen some people upgrading or downgrading their version of django and it get solved like that I am using the latest version of django This as the DATABASE in the setting.py file DATABASES = { 'default': { 'ENGINE': 'django_mongodb_engine', 'NAME': 'mydatabase', } } -
How to filter django queryset for a current week
I am writing this customer admin filter that required to filter the queryset for this/current week only. How can I achieve this class WeekFilter(admin.SimpleListFilter): title = _("Week") parameter_name = "week" def lookups(self, request, model_admin): return ( ('1', 'This week'), ) def queryset(self, request, queryset): if self.value() == '1': return queryset.filter() # HERE I have tried this queryset.filter(created_at__week__gte=1, created-at__week__lte=7) but it doesnt work as expected -
related_name works the first time but not the second
I have a somewhat deep hierarchy of models: models.py: class Individual(models.Model): gedcom = models.ForeignKey(Gedcom, on_delete=models.CASCADE) pointer = models.CharField(max_length=22, default="") given = models.CharField(max_length=255, default="") surname = models.CharField(max_length=255, default="") birth_date = models.CharField(max_length=255, default="") birth_location = models.CharField(max_length=255, default="") death_date = models.CharField(max_length=255, default="") death_location = models.CharField(max_length=255, default="") class Fact(models.Model): individual = models.ForeignKey(Individual, on_delete=models.CASCADE, blank=True) tag = models.CharField(max_length=4, default="") value = models.CharField(max_length=255, default="") priority = models.IntegerField(default=0) class FactDetail(models.Model): fact = models.ForeignKey(Fact, on_delete=models.CASCADE, blank=True) tag = models.CharField(max_length=4, default="") value = models.CharField(max_length=255, default="") priority = models.IntegerField(default=0) In my code I start creating individuals, their associated facts, and the fact_details. The related_name "fact_set" gets created automatically and works, but why doesn't this automatically work for factdetails too? should there not be a factdetail_set related name created? curr_individual = self.individual_set.create( pointer = curr_pointer, given = given, surname = surname, ) elements = record.get_child_elements() for element in elements: fact_details = element.get_child_elements() fact_priority = 0 curr_fact_tag = element.get_tag() curr_individual.fact_set.create( tag = curr_fact_tag, value = element.get_value(), priority = fact_priority, ) fact_priority += 1 fact_detail_priority = 0 for fact_detail in fact_details: curr_fact_detail_tag = fact_detail.get_tag() curr_fact_detail_value = fact_detail.get_value() if not done_birth and curr_fact_tag == 'BIRT': done_birth = True if curr_fact_detail_tag == 'DATE': curr_individual.birth_date = curr_fact_detail_value if curr_fact_detail_tag == 'PLAC': curr_individual.birth_location = curr_fact_detail_value if not … -
What is the use of "psycopg2" in Django while connecting to PostgreSQL
What is the use of the "psycopg2" PostgreSQL database adapter; or what is the difference between using postgresql vs postgresql_psycopg2 while establishing connection in the settings.py file in a Django project? 'ENGINE': 'django.db.backends.postgresql', 'ENGINE': 'django.db.backends.postgresql_psycopg2', -
Apache config on a Synology DS for use with mod_wsgi / Django
I'm started developing a new site using Django. For realistic testing I wanted to run it on a Synology DS212J NAS. Following the official Synology guides I installed ipkg and with it the mod_wsgi package. As Next step: Following the standard tutorial I made a virtualenv and installed Django in it. Opening a new project and adjust the settings following to: https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-16-04 I'm able to reach the "Hello World" Site from Django by use of manage.py As suggested I want to exchange the manage.py through the apache server on the NAS. So I think I should go and edit the apache config files for e.g. define a virtual host... However I can't localize the files for it, as it seems they where moved at DSM6 (which I use) in comparison too other guides. Where need I to enter the values following the Tutorial on the Synology? As I'm quite new into the topic do I need to especially load the mod_wsgi module for Apache and if where? Is it a good idea to use the basic mode of wsgi instead of the daemon mode? I'm not sure which Django modules will be used later on in development... Thanks for the … -
Passing value and ID from Request.POST
I am trying to have a website with multiple input type ="text" fields which as a default have values from database in them. Goal is to have X input types where X=number of entries in database and one extra input type box to add a new entry. The problem is that if user edits a textfield and hits submit, Request.POST['event'] returns only the new value, not the id of the box that has been edited, This is my current code: <form method="post"> {% csrf_token %} {% for choice in event %} <form method ='POST'> {% csrf_token%} <input type="text" name = "event" id="event{{ forloop.counter }}" value="{{choice.txt}}"><br> <input type = 'submit' value = 'Zapisz'/> </form> {% endfor %} <form method ='POST'> {% csrf_token%} {{form.as_p}}<br> <input type = 'submit' value = 'Zapisz'/> </form> and views.py: def rpg_create(request): try: event = get_list_or_404(Event) except: event = "" if request.method == 'POST': try: Adjusted_event = request.POST['event'] print (Adjusted_event) except: pass form = RpgForm(request.POST or None) if form.is_valid(): print(form) form.save() context = { 'form': form, 'event': event } return redirect('/rpgmaker', context) else: form = RpgForm() context = { 'form': form, 'event': event } return render(request,"rpgmaker/rpg.html",context) -
Do I need to copy the templates for third party apps (specifically Django-schedule)?
I am a Django newbie trying to use a third party app (Django scheduler) to display a calendar for event scheduling. I followed the installation instructions on the github and have successfully installed the app into my environment. I know it is working because it migrated successfully and I was able to create test instances of the Event and Calendar models using the API shell (python manage.py shell). But I am really confused about how to use django-scheduler to augment my current app (i.e. how to make a calendar show up when users are inputting events). Specifically, my question is; do I need to copy all of the templates folders, or should they be automatically included during the installation and I just need to link to them somehow? There is an example project but it does not integrate the scheduler into an existing app so I could not glean the answer from this. -
Django: DoesNotExist at /admin
I've a view that receives an arugment to make a Query filter and show some results. The URL for this view is: views.ProdCatDetail urlpatterns = [ path('', views.allCat, name = 'allCat'), path('<slug:c_slug>', views.ProdCatDetail, name = 'ProdCatDetail'), ] the problem is that if I want to access the admin panel, through: http://127.0.0.1:8000/admin I cannot becuase the view: views.ProdCatDetail gets called, and since there is no Category "admin" I get an error. How can avoid this, without using another URL for the views.ProdCatDetail view??? -
how to filter queryset based on Datefield in django?
I need to filter queryset based on today/tommorows date and the field available is a date field not datetime field I am using custom manager for providing filtered result class CallbackReqManager(models.Manager): def get_queryset(self): return super().get_queryset().filter() def callbacktoday(self): today=date.today print(today) return self.filter(prefereddate=today) class CallbackReq(models.Model): name = models.CharField(max_length=50) email = models.EmailField(max_length=254) query = models.CharField(max_length=150) preferedtime = models.TimeField(auto_now=False, auto_now_add=False) prefereddate = models.DateField(auto_now=False, auto_now_add=False) requestedon = models.DateTimeField(auto_now_add=True) attended = models.BooleanField(default=False) # whether call back is met objects = CallbackReqManager() but I am getting TypeError: match = date_re.match(value) TypeError: expected string or bytes-like object -
Append to QuerySet Item
I have 2 models, Item which represents a product, and OnHand which represents each individual serialized product. They are bound by a ForeignKey of product_id. Item Model: class Item(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) manufacturer = models.ForeignKey('Manufacturer', blank=True, null=True, on_delete=models.SET_NULL) introduction = models.DateField(auto_now=True) is_retired = models.BooleanField(default=False) tags = models.ManyToManyField(Tag) def __str__(self): return self.name OnHand Model: class OnHand(models.Model): name = models.CharField(max_length=100) serial = models.CharField(max_length=80) asset = models.CharField(max_length=20) product = models.ForeignKey(Item, blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.serial On my Index view, I have a table which shows these products and counts quanity. In order to do this, i need to count the amount of OnHand objects exist with a matching product_id. Index: def index(request): items = Item.objects.all() quanity = count_onhand(items) context = { 'items':items, } print(items) return render(request, 'index.html', context) count_onhand: def count_onhand(items): for item in items: count = OnHand.objects \ .filter(product_id=item.product_id) \ .count() Because these are going to the same view and need to maintain their order, I figured the best direction would be to append to the Item queryset then appending to a list I'll send back with the original Item, with the quanity appended. How do I do this in Django properly? I've seen some hacky ways, … -
How do I add a css property in a for loop only once?
I have a my table body in a for loop in my Django app and I want to add a CSS property only to the contacts of a specific company but now my code is applying the CSS properties to all contancts. table body {% for company in company_list %} <tr id="company-row"> <th id="company-name" scope="row">{{ company.name }}</th> <td>{{ company.order_count }}</td> <td id="order-sum">{{ company.order_sum|floatformat:2 }}</td> <td class="text-center"><input type="checkbox" name="select{{company.pk}}" id=""></td> </tr> {% for contact in company.contacts.all %} <tr id="contact-row"> <td>{{ contact.first_name }} {{ contact.last_name }}</td> <td id="contact-orders">Orders: {{ contact.order_count }}</td> <th>&nbsp;</th> <td></td> </tr> {% endfor %} {% endfor %} jquery $(document).ready(function(){ $("table tr#company-row").hover(function(){ sum = $(this).find("#order-sum").html() // get value of total sales if (sum > 50000) { $(this).addClass("company-row-over") // green $("tbody #contact-row").each(function(){ orders = $(this).find("#contact-orders").html() // get orders from each contact orders = orders.split(':') orders = orders[1] orders = parseInt(orders) if (orders > 3) { $(this).addClass("contacts") // yellow } }) } else { $(this).addClass("company-row-under") // orange } }, // clear highlighting on mouse out function() { $(this).removeClass() $("table tr#contact-row").removeClass() }) }) -
How to check if model a has a User in it?
I have two models class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,) name = models.CharField(max_length=128) #actual creator's name In a html page I want to check if Profile model has current logged in user in it? I am using this line {% if Profile.objects.filter(user=user).exists() %} I know this is wrong, I am beginner to Django and web development. Could some one help with this? Thanks. -
django failing on LiveServerTestCases
My other tests pass fine, but when I use selenium to test, the tests run fine but when a test ends it always produces the following error after completing the tearDown function: File "C:\Users\Win7\.virtualenvs\lang-QbOXb8q_\lib\site-packages\django\db\backends\base\base.py", line 239, in _commit return self.connection.commit() django.db.utils.IntegrityError: FOREIGN KEY constraint failed It doesn't appear to be related to my database as the error only occurs for LiveServerTestCases. -
Django - User should only able to vote once
i want that a user is only able to vote once for a category-request but somehow i get the following error and i dont know how to "properly" call the instance at that point: Cannot assign "1": "CategoryRequests_Voter.voted" must be a "CategoryRequests" instance. models.py # Category Requests Model class CategoryRequests(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) .... # Vote(s) of Category Requests Model class CategoryRequests_Voter(models.Model): voter = models.ForeignKey(User, on_delete=models.CASCADE) voted = models.ForeignKey(CategoryRequests, on_delete=models.CASCADE) published_date = models.DateField(auto_now_add=True, null=True) def publish(self): self.published_date = timezone.now() self.save() views.py def category_request_up_vote (request, pk): category_request = get_object_or_404(CategoryRequests, pk=pk) if request.method == 'GET': if CategoryRequests_Voter.objects.filter(voter=request.user, voted=category_request.pk).exists(): messages.error(request, 'You already voted for this request.') else: category_request.up_vote = F('up_vote') + 1 category_request.save() CategoryRequests_Voter.objects.create(voter=request.user, voted=category_request.pk) messages.success(request, 'You have successfully Provided an Up-Vote for this Request') return redirect('category_request_detail', pk=category_request.pk) else: messages.error(request, 'Uuups, something went wrong, please try again.') return redirect('category_request_detail', pk=category_request.pk) Thanks in advance -
Django - How to change current form to update on submit?
I’m creating a profile page in my web application & I have a form to when the user makes a form submission I need the data from the form to update in the django admin from the current logged in user. The data populates in the admin however new listings keep getting added every time the user submits this form. I need the the data to update only in 1 field per logged in user and not repeat. Screenshot attached. How do I execute this correctly with my current code? The Custom User Model I’m using is located in from users.models import CustomUser if that helps. Any help i gladly appreciated, Cheers user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from user_profile.forms import HomeForm from users.forms import CustomUserCreationForm, CustomUserChangeForm from user_profile.models import Listing from users.models import CustomUser # Register models here. class UserProfileAdmin(admin.ModelAdmin): list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'user'] list_filter = ['name', 'zip_code', 'created', 'updated', 'user'] admin.site.register(Listing, UserProfileAdmin) user_profile/models from django.contrib import auth from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver … -
Django urlpatterns - too many values to unpack
I am a beginner in Python and Django working on a simple IoT tutorial found in a book. The project is to control a led circuit from a Django app. After I copied of the code, few errors popped up because of the Python and Django version in the book as they are old versions. I am working on Python 3.7.2 and Django 2.1.4 and upon searching, I couldn't find the way to fix my code. Hopefully someone can direct me to the direction to fix it. the directory of my project is as follows Project1 Project1 __init__.py settings.py urls.py wsgi.py FirstApp admin.py apps.py controller.py index.html models.py serializers.py tests.py views.py The problem that I am facing is in the urls.py which the code for it is: from django.conf.urls import * from django.contrib import admin from rest_framework import routers from FirstApp import views admin.autodiscover() router = routers.DefaultRouter() router.register(r'mode',views.ModeViewSet) router.register(r'state',views.StateViewSet) urlpatterns = [ url(r'^', router.urls), url(r'^api-auth/', 'rest_framework.urls',namespace='rest_framework'), url(r'^admin/', admin.site.urls), url(r'^home/', 'FirstApp.views.home') ] The error traceback is this Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7593e6a8> Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 379, in … -
django rest framework serializers correct way to display date time fields in the user timezone
I have many models with a created field of type DateTimeField with auto_now_add=True. My purpose is to display the user the 'created' field in his local timezone. I have the settings: USE_TZ = True TIME_ZONE = 'UTC' I use PostgreSQL. Is it possible for the serialization output to convert the UTC timezone to the user timezone? Just like DRF does content negotiation to determine the output format (xml/json/browser), I wonder if it is possible to do the same to infer the user timezone. Or maybe doing the same at the queryset level. I'm not sure what's the better way. If it is not possible to detect the user timezone from the request, I could provide the user timezone in a custom HTTP header or parameter, with some javascript setup. But even then, how can I hook that to DRF? -
Send items from forloop populated data in django template through ajax to django view
I have been trying to create a click and populate div with ajax in my django e-commerce application. The project works in such a way that when a customer clicks on a category in men's page it populates another div gender.html {%for cate in cat%} <a href="javascript:getcat()" id="catgend" cats-data="{{cate.catname}}" gen-data="{{gens.gender}}" data-sort-url="{% url 'Home:sortcat' cpk=cate.pk %}" >{{cate.catname}}</a> {% endfor %} <div id="products"> <div class="progress"> <img src="{% static 'img/load.gif'%}"> </div> </div> This sends the data to my django view through the ajax function called getcat but the data sent through is that of the first item in the loop in-respective of the loop item clicked on. below is my ajax function: getcat() function getcat() { $(".progress").show() var cat = $("#catgend").attr("cats-data"); var gender= $("#catgend").attr("gen-data"); var url = $("#catgend").attr("data-sort-url"); $.ajax({ url: url, data: { 'cat': cat, 'gender':gender, }, success: function (data) { $("#products").html(data); } }); $(".progress").hide() } enter code here From my research i discovered its because they have same ID. How do i solve the issue of dynamically changing the id over the same loop. Thanks -
Django Passing Newly Created ID from Models.Manager to Views
I'm trying to pass the newly created id for a new entry from Models.Manager to views, so I can save it as a variable. views.py def save_form(request): item_a = request.POST['item_a'] item_b = request.POST['item_b'] Items.objects.save(item_a, item_b) print (saved.id) return redirect ((reverse('project:index'))) models.py class ItemsManager(models.Manager): def save(self, item_a, item_b) item_a = item_a item_b = item_b saved= Items.objects,create( item_a = item_a, item_b = item_b) return (True, saved) class Items(models.Model): item_a=models.CharField(max_length=255) item_b=models.CharField(max_length=255) objects = ItemsManager() What I'm trying to do is get the id of the saved entry and send it to the views. I tried using return saved, return saved.id and return save.id on the Models Manager to pass it to the views. Right now I have it as True, saved because it's what I've gather is the correct way after reading a few posts. However when I come to the views I'm not getting the id I want. When I try print (saved.id) in views I get: NameError: name 'result' is not defined I also tried in views if save = [0]: print(saved.id) and I get: if saved = [0] ^ SyntaxError: invalid syntax Right now I'm just trying to print, but once I know the value is making it to the … -
How to implement update_or_create inside create method of ModelSerializer
The code: class OTP(AppModel): phone_regex = RegexValidator(regex=r'^[6789]\d{9}$', message="phone no. is invalid.") phone_number = models.CharField(validators=[phone_regex], max_length=10, unique=True) code = models.CharField(max_length=255) def __str__(self): return str(self.phone_number) + ": "+str(self.code) class OTPSerializer(serializers.ModelSerializer): code = serializers.CharField(max_length=None, required=False) class Meta: model = OTP fields = ('id', 'code', 'phone_number') read_only_fields=('id', 'code') @transaction.atomic def create(self, validated_data): phone_number = validated_data.pop("phone_number") otp, created = OTP.objects.update_or_create( phone_number=phone_number, defaults={"code": generate_otp()}) return otp I am trying to do update_or_create inside the create method of the django-rest-framework's ModelSerializer. But, the field phone_number inside the model OTP must be unique. Hence the unique=True. I was able to post a phone_number and create the object. But, posting the same phone_number again throws error otp with this phone number already exists, instead of updating it if it already exists as I have overridden the create method. Please help! -
Django all-auth, thoughts on creating guest account without login
So I've used django-allauth before and it is great for user registration and login features. I'm currently working on a small app that requires some sort of "Guest Check-out", an employee should be able to create a user without the requirement of signing up (creating a password or signin possibility) I could create a separate model for guestaccounts, using the same information used in the user model, this would be the simplest solution but violates the dry principle. Since I inherit from "AbstractBaseUser" to create an useraccount with the email field as the unique identifier, I thought we could split the model into an "CustomAccount" model, requiring an emailadres and setting up a separate model to store all user info and set a guest_flag. We could now create an order with a guest_user, but then we could not register the guests email address or convert them to a registered user later on. On the other hand we could not create a "guest order" twice since we use the email address as a unqiue identifier, or we should not register the emailaddress for guest orders, but then we cannot inform them on order updates... Does anyone have a direction, suggestion about … -
Django - model constructor with reference to another model passed to set(with working ASP.NET example)
I'm moving project from asp.net to django. I got following simple models. Models/File.cs public partial class File { public File() { this.Sheet = new HashSet<Sheet>(); // what I need in Django. } // Model passed to set, set passed to // another model public virtual ICollection<Sheet> Sheet { get; set; } //ForeignKey } Models/Sheet.cs public partial class Sheet { public virtual File File { get; set; } //ForeignKey } My Django equivalent: models.py class File(models.Model): # @classmethod # working on a constructor here # def create(cls): # sheet = cls() # return sheet class Sheet(models.Model): data = models.ForeignKey(File, on_delete=models.CASCADE) So I need a model constructor with reference to another model wrapped in a set method. I know that I can't use __init__. Any thoughts will help.