Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python manage.py dumpdata Access is denied
I got the error message - (ECOMME~1) C:\Users\HP\Django Projects\EcommerceProject>python manage.py dumpdata products --format json --indent 4 > products/fixtures Access is denied. I assumed it was because I had changed my databases because the default databases are not sufficient if you want mapping functionality. I read the post Django loaddata returns a permission denied for relation and asked GRANT ALL PRIVILEGES ON DATABASE Blog&Cart for user postgres. -
My very simple Django Form not passing value to another View
I'm new to Django with a background in Database design. I spent most of my IT career developing prototypes in MS Access so this Web stuff is new to me. Now I'm trying to develop prototype reports in Django for a reporting wing of a SAAS offering. I've got a rough report developed, and if I hard-code the values to pass into some raw queries, it renders a report. Now I'm trying to make a simple form to enter a value into and pass it into the view that renders the report. (Pardon me if I'm using the correct lingo.) Here's the form for the data entry: product_batch.py from django import forms class PrdBtchSelect(forms.Form): prd_btch_nbr = forms.CharField(max_length=20) Here is the data entry HTML: prd_btch_select.html {% extends "base.html" %} {% block title %}Product Batch Select{% endblock %} {% block content %} <form action={% url 'prd_btch_dtl' form.prd_btch_nbr %} method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% endblock %} Here are the views for the data entry form and for rendering the report: view\product_batch.py from django.shortcuts import render from reports.views import sql from reports.models import Accounts from reports.forms import PrdBtchSelect # import datetime def prd_btch_dtl(request, prd_btch_nbr): """View function for … -
Where do I keep ORM in a distributed app?
I am designing a scalable web app. I have APIs (Django Rest Framework) in one container instance, Web App (Django) in another, Database (Postgreql) in another and finally CDN in another (Azurite). I wanted to decouple API since mobile apps will use the same - eventually. Question: Where do I keep ORM in this scenario? If I keep it part of Web apps, then how do the APIs recognize and use the objects? Or, if I keep them part of the API services, how do the front end (web apps) understand the objects? -
Reloading the data automatically in django
im new to this Here in this program when i clicking the refresh button the entire page is being reloaded and then only the data is being updated so i was thinking you could automatically update the data after some time or when clicking the refresh button get the data without loading the page entirely again The link is here for the github issue https://github.com/ALDRIN121/Covid-19_live_tarcker/issues/1 And thanks in advance -
2 pages in URL in python
my question is why i cannot get property.html when the server is run let me explain you how th project go one : the 1st page which is content list of cities one of them choosen then th next page i get it's property_name the 3rd page should give me all it's properties (name,area) i hope u understand me models.py: from django.db import models class location(models.Model): location_name = models.CharField(max_length=500) location_type = models.CharField(max_length=500) def __str__(self): return self.location_name class property(models.Model): location = models.ForeignKey(location, on_delete=models.CASCADE) property_name = models.CharField(max_length=500) property_area = models.CharField(max_length=500) def __str__(self): return self.property_name views.py: from django.shortcuts import render from django.views import generic from .models import location,property class indexview(generic.ListView): template_name = "homsapp/index.html" def get_queryset(self): return location.objects.all() class locationview(generic.DetailView): model = location template_name = "homsapp/location.html" class propertyview(generic.DetailView): model = property template_name = "homsapp/property.html" urls.py: from django.contrib import admin from django.urls import path,include, re_path from homsapp import views app_name = 'homsapp' urlpatterns = [ #path('admin/', admin.site.urls), path(r'', views.indexview.as_view(), name=('index')), re_path(r'(?P<pk>[0-9]+)/$',views.locationview.as_view(),name=('property')), re_path(r'([0-9]+)/(?P<pk>[0-9]+)/$',views.propertyview.as_view(),name=('propertyview')), ] index.html: {% for locat in object_list %} <a href="/homsapp/{{locat.id}}">{{locat.location_name}}</a><br> {% endfor %} location.html: {% for i in location.property_set.all %} <a href="/homsapp/{{locat.id}}/{{i.id}}">{{i.property_name}}</a> {% endfor %} property.html: {{property.property_name}}<br> {{ property.property_area}} -
Using django without models
Is it possible to use Django but without models? Instead of models I want to use raw sql queries with help of mysql cursor. I want to implement Car Rental site to rent a car. There will be three tables: Cars, Users, Orders. Anyone can sign up on the webpage, sign in and make orders. The only limitation is that a have to do this using raw sql queries so I think that I have to avoid using models. Is this even possible? I'm new to Django and this might be dump question but need to know cause this is my academic project. -
Failing django migrate from ProcessedImageField to FilerImageField
I currently have a model for reusable images: class Image(models.Model): class Meta: verbose_name = _('Image') verbose_name_plural = _('Images') name = models.CharField( max_length=200, unique=False, blank=False, null=False, verbose_name=_('Image name') ) full_size = ProcessedImageField( upload_to='images/', processors=[ResizeToFit(height=450, upscale=False)], format='JPEG', options={'quality': 90}, ) thumbnail = ImageSpecField( source='full_size', processors=[Thumbnail(width=200, height=115, crop=True, upscale=False)], format='JPEG', options={'quality': 60} ) def __str__(self): return self.name Now I'm trying to move over to the FilerImageField from django-filer. I have added the field with a different name, here's the relevant code section: image = models.ForeignKey( Image, on_delete=models.SET_NULL, verbose_name=_('Unit image'), null=True, blank=True ) img = FilerImageField( null=True, blank=True, related_name="unit_img", verbose_name=_('Unit image'), on_delete=models.DO_NOTHING, ) I have the following migration: # Generated by Django 3.1.2 on 2020-11-02 20:09 from django.db import migrations from filer.models import Image def migrate_unit_images(apps, schema_editor): Units = apps.get_model('tageler', 'Unit') for unit in Units.objects.all(): if unit.image: img, created = Image.objects.get_or_create( file=unit.image.full_size.file, defaults={ 'name': unit.name, 'description': unit.image.name, } ) unit.img = img unit.save() class Migration(migrations.Migration): dependencies = [ ('tageler', '0008_filer_create'), ] operations = [ migrations.RunPython(migrate_unit_images), ] My problem is that I get the following error: ValueError: Cannot assign "<Image: This is a test image>": "Unit.img" must be a "Image" instance. I thought that I just created or gotten the Image. What am I missing … -
Can I nest similar model relationships under a custom type in Graphene Django?
Assuming I have a Django model with a number of relationships that are related, is it possible to nest them through a non-model type for querying purposes? A specific example: Assume I have a model Organization with relationships that include X_projects, X_accounts, etc which are also Django models. It is pretty easy to allow queries like: query fetchOrganization($id: Int!) { organization(id: $id) { id, ... other fields ... X_accounts { ... } X_projects { ... } } } but I would prefer to support queries like: query fetchOrganization($id: Int!) { organization(id: $id) { id, ... other fields ... X { accounts { ... } projects { ... } } } } Given that X doesn't actually make sense to be a Django model / relation on the backend, is there a way to achieve this? -
getting error when manage.py makemigrations with mongodb
enter image description hereenter image description here enter image description hereur.com/fPD9B.png -
Django group and sum QuerySet for template
Hoping someone can help! Apologies if the question isn't well written, this is my first post. I am trying to pass a queryset through to a template - I get an error if I do not pass the id through (ID1 in example output below) but I do not want to do that as it interferes with a group by: ID1 Staff No. Week Start Hours Staff ID 1 12345 2020-10-24 15 1 2 12345 2020-10-17 7.5 1 4 12345 2020-10-17 10.0 1 Basically, I want the output to grouped to display only TWO rows (2020-10-17 should be one row with 17.5 hours in total). My model is: from django.db import models from django.contrib.auth.models import User class Contractor(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) staff_number = models.CharField(max_length=9, null=True) contractor_name = models.CharField(max_length=100, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) objects = models.Manager() def __str__(self): return f"{self.staff_number}: {self.contractor_name}" class WeekList(models.Model): week_number = models.SmallIntegerField(null=True) week_start = models.DateField(null=True) objects = models.Manager() def __str__(self): return f"{self.week_number}: ({self.week_start})" class Timesheet(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.PROTECT) contractor = models.ForeignKey(to='timesheet.Contractor', null=True, on_delete=models.PROTECT) week_list = models.ForeignKey(to='timesheet.WeekList', null=True, on_delete=models.PROTECT) job_number = models.CharField(max_length=16, null=True) sat_hours = models.FloatField(default=0, null=True, blank=True) sun_hours = models.FloatField(default=0, null=True, blank=True) mon_hours = models.FloatField(default=0, null=True, blank=True) tue_hours = models.FloatField(default=0, null=True, blank=True) … -
Timestamp keeps updating in admin
class Transaction(models.Model): id_str = models.CharField(verbose_name="Transaction ID", max_length=200) created = models.DateTimeField(verbose_name="Date of creation", auto_now_add=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.set_transaction_id() def set_transaction_id(self): dt = datetime.datetime.now() self.id_str = str(dt.year) + str(dt.month) + str(dt.day).zfill(2) + \ str(dt.hour) + str(dt.minute).zfill(2) + str(dt.second).zfill(2) I want to use the the timestamp of point where the model instance is created to assign id_str. I can't use model field created because __init__ runs first. But in the above code, after creating the model instance and id_str assigned, when I refresh the admin page, id_str also gets refreshed to an updated timestamp. Why does datetime.now() refreshes itself in admin? -
How to get data from another table by using foreign key and JOIN in django and display it in angular using restapi
I want to get course title and course code using the foreign key courseID and JOIN.Then using django restapi I want to show the courseOffered table to display the course title and course code instead of courseID class Course(models.Model): courseID = models.AutoField(default = None, max_length=20, primary_key = True, verbose_name='course ID') courseCode = models.CharField(max_length=8, verbose_name='course Code', unique = True) crs_title = models.CharField(max_length=50, verbose_name='title') crs_shortName = models.CharField(max_length=9, verbose_name='short Name', unique = True) CATEGORY_CHOICES = ( ('major', 'major'), ('core', 'core'), ('science & mathematics', 'science & mathematics'), ('general education', 'general education'), ('optional', 'optional'), ) crs_category = models.CharField(max_length=25, choices=CATEGORY_CHOICES, verbose_name='category') programCode = models.ForeignKey('Program',on_delete=models.CASCADE, verbose_name='program', db_column="programCode") class Meta: db_table = '"tbl_course"' verbose_name_plural = "Course" def __str__(self): return '%s %s' % (self.courseCode, self.crs_shortName) `class CourseOffered(models.Model): courseOfferedID = models.AutoField(default = None, max_length=20, primary_key = True, verbose_name='courseOffer ID') TERM_CHOICES = ( ('Spring', 'Spring'), ('Summer', 'Summer'), ('Autumn', 'Autumn'), ) ofr_term = models.CharField(max_length=6, choices=TERM_CHOICES, verbose_name='term') ofr_year = models.IntegerField(verbose_name='year') programCode = models.ForeignKey('Program',default='115', on_delete=models.CASCADE,verbose_name='program',db_column="programCode") batchCode = models.ForeignKey('Batch',blank = True, null = True, on_delete=models.CASCADE, to_field='batchCode', related_name='batch_Code', verbose_name='batch Code', db_column="batchCode") courseID = models.ForeignKey('Course',default=None,on_delete=models.CASCADE, to_field='courseCode', verbose_name='course', db_column="courseID") facultyID = models.ForeignKey('Faculty',default=None,on_delete=models.CASCADE, verbose_name='faculty', db_column="facultyID") fac_shortName = models.ForeignKey('Faculty',default=None, on_delete=models.CASCADE, related_name='Faculty_Short_Name', to_field='fac_shortName', verbose_name='Faculty Short Name', db_column="fac_shortName") class Meta: db_table = 'tbl_courseOffered' verbose_name_plural = "CourseOffered" def __str__(self): return '%s' % (self.courseOfferedID) -
Error in parsing django variable in javascript
I have a django app. I am using the below code to use access a django variable in javascript. var pd_info = {{pd_inf|safe}}; This is giving Uncaught SyntaxError: missing ] after element list note: [ opened at line 327, column 15 The variable works perfectly fine in django template. How to resolve this? -
How do you turn a new-style middleware class into a decorator for generic DRF views?
I have middleware that I need for certain views. I don't want the middleware to run globally, so I would like to decorate some generic DRF views with it instead. I'm guessing that this should be simple to do, but I haven't had much luck. I was trying to use the decorator_from_middleware decorator with the middleware, but that appears to only work with old-style middleware. Below is a simplified example of what I am trying to do. class LoggerMiddleware: """ Middleware that logs Request and Response context """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) # capture the data I need here return response This decorator fails with the middleware, but I do not know what to replace it with. @decorator_from_middleware(LoggerMiddleware) class TestView(CreateAPIView): def post(self, request): return Response({'detail': 'attempting this'}) -
How to get response parameters in Django?
I want to implement login with twitter without using any library for my django app. I am sending the user to login page using a request function in views by passing the tokens which is successfully going to the twitter login page. Twitter redirects user to a url which I have configured as login/twitter/callback How do I access the parameters sent by twitter on this url using a view ? -
How to create a User object when creating another object with OneToOne relationship in Wagtail
Not sure if the title is descriptive enough, sorry for that. I have added a model called 'Client' to Wagtail's ModelAdmin. In client/models.py: class Client(models.Model): # Every client is a user user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_("Pessoa") ) phone_number = PhoneNumberField( _("Número telemóvel"), null=False, blank=False, unique=True ) company = models.CharField(_("Empresa"), null=True, blank=True, max_length=20) NIF = models.CharField(max_length=9, validators=[validate_nif]) def __str__(self) -> str: return self.user.get_full_name() In client/admin.py: class ClientAdmin(ModelAdmin): """ Client Admin """ model = Client menu_label = "Clientes" menu_icon = "fa-users" menu_order = 290 add_to_settings_menu = False exclude_from_explorer = False list_display = ( "NIF", ) search_fields = ( "NIF", ) modeladmin_register(ClientAdmin) When I go to Clientes admin page, and try to create a new one, I have the following: Is it possible to have the corresponding fields to create a 'Person', instead of selecting a new one? Thanks in advance -
Can't configure django TinyMCE in settings.py while it's possible in html script
I used TinyMCE for django for a prior project and as far as I remember, it was possible to configure in django settings.py file. Now, I'm working on another project but couldn't find any solution to make it done except adding the TinyMCE configuration js script to the template I want to use it on. It's not a big deal to configure from HTML but looks like it's having some performance issues while getting static requests. And, I haven't had any loading problem while I was configuring in settings.py. Here you can check my project files here. Hope to find a solution. models.py from tinymce.models import HTMLField class Article(models.Model): ... message = HTMLField() ... forms.py from django import forms from tinymce.widgets import TinyMCE from . import models class ArticleForm(forms.ModelForm): class Meta(): abstract = True model = models.Article fields = ('title', 'message', 'tags') widgets = { 'title': forms.Textarea(attrs={'placeholder': 'Başlık'}), 'message': TinyMCE(attrs={'class': 'tinymce', 'id': 'myeditablediv', 'contenteditable': 'true', 'style': 'position: relative;'}), } def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super().__init__(*args, **kwargs) form.html {% extends "articles/article_base.html" %} {% load bootstrap4 %} {% load static %} {% load widget_tweaks %} {% block article_content %} <div class="container"> <div class="articleForm"> <form method="POST" action="{% url 'articles:create' %}" … -
Pass Django template variable in url template tag
I'm still a bit new to Django and have been stuck on trying to figure out a way to add a template variable to a Django url template tag. I can better explain with an example... I have a help center/knowledge base that currently has articles along with tags associated with that article. The goal is to allow users to click on those associated tags to perform a search on the help center using the tag that was clicked on and return a new set of articles in the search. This is my url pattern: urlpatterns = [ ... path('search/', views.search, name='search'), ... ] My html: <div id="tags uk-margin-bottom"> {% for tag in article.tags.all %} <a href="{% url 'search' %}" class="badge badge-pill badge-primary">#{{ tag }}</a> {% endfor %} </div> My search view function: def search(request): if request.user.is_authenticated: # get all articles queryset_list = Article.objects.all() if 'search' in request.GET: search = request.GET['search'] if search: tags = [] queryset_list_tags = queryset_list.filter(tags__name__icontains=search).distinct() try: queryset_list_title = queryset_list.filter(title__icontains=search).distinct() except: print("Testing - Couldn't grab titles.") search_results = queryset_list_tags | queryset_list_title # get all tags from query_list_title search for title in queryset_list_title: article = Article.objects.get(title=title) queryset_tags = article.tags.all().values_list('name') for tag in queryset_tags: # add all tags in … -
Get serialized response of all models related to base model instance using Django REST framework
I have 3 models class Project(models.Model): project_name=models.CharField(_("Project Name"), max_length=50) ............................................................... class Calculations(models.Model): project = models.ForeignKey("address.Project", verbose_name=_("Project"), on_delete=models.CASCADE) ................................................................................................... class Finances(models.Model): project = models.ForeignKey("address.Project", verbose_name=_("Project"), on_delete=models.CASCADE) ................................................................................................... each entry in model Project is connected to 2 entries in Calculation model. Also, each entry of Calculation is connected to 4 entries of Finance model Is there any way to get serialized response by using only the primary_key of the base Project model -
{% include %} doesn't pass " for loop " data in other html pages - Django
i want pass data from an html page that i use for loop inside this page and show all data in other html pages so i tried this but it doesn't pass for loop data from my model why side_bar_good_posts.html : {% for post in best_posts %} <div class="card rounded mx-auto d-block" style="width: 18rem;margin-bottom:50px;border-color:#7952b3"> <div class="card-body" id="mobile_design_card"> <a href="{{post.url}}"><p class="card-text" id="mobile_design_card_name">{{ post.name }}</p></a> </div> <a href="{{post.url}}"><img src="{{ post.get_image }}" class="card-img-top" alt="..." height="290px" width="300px"></a> </div> &nbsp; &nbsp; {% endfor %} views.py : from .models import BestArticals def Best_Articals(request): best_posts = BestArticals.objects.all() context = {'best_posts' : best_posts} return render(request,'android/side_bar_good_posts.html',context=context) in other html pages : {% include "android/side_bar_good_posts.html" with best_posts=best_posts %} it show just html tags , but data from for loop doesn't appear why -
Django views show same content. Where are django views controlled?
I have a django application with two views that display the same content, but they shouldn't. I created the second by duplicating the code from the first and cannot figure out how to unhook these from each other. I am pretty sure the problem is in the views.py file of my app. I have two views, 'journals-by-discipline' and 'journals-by-discipline-elsevier' Here is the urls.py file: from django.urls import path, include from django.contrib.auth import views as auth_views from django.views.generic.base import RedirectView from . import views app_name = 'app' urlpatterns = [ # Journals by Discipline path('journals-by-discipline/', views.journals_by_discipline, name='journalsByDiscipline'), path('journals-by-discipline/chart-data/<str:discipline>/', views.journals_by_discipline_chart_data), path('journals-by-discipline/journals-and-disciplines-map/', views.get_journals_and_disciplines_map), path('journals-by-discipline/disciplines-list/', views.disciplines_list), # Journals By Discipline (Elsevier) path('journals-by-discipline-elsevier/', views.journals_by_discipline_elsevier, name='journalsByDisciplineElsevier'), path('journals-by-discipline-elsevier/chart-data/<str:discipline>/', views.journals_by_discipline_chart_data_elsevier), path('journals-by-discipline-elsevier/journals-and-disciplines-map/', views.get_journals_and_disciplines_map), path('journals-by-discipline-elsevier/disciplines-list/', views.disciplines_list), ] Here is the views.py file from django.shortcuts import get_object_or_404, render from django.contrib.auth.decorators import login_required from django.http import JsonResponse from rest_framework.decorators import api_view from rest_framework.response import Response import datetime as datetime from dateutil.relativedelta import relativedelta from urllib.parse import unquote import json from .onefigr_analysis import Data # Instantiate Data object to fetch data across all views data = Data() # Journals by Discipline Page def journals_by_discipline(request): template_name = 'app/journals-by-discipline.html' return render(request, template_name) @api_view(['GET']) def journals_by_discipline_chart_data(request, discipline): if request.method == 'GET': query_discipline = unquote(discipline) return Response(data.journals_by_discipline_chart_data(discipline)) … -
Django: Get User profile from User serializer
I have a basic UserProfile model that has a OneToOne relationship with a User model. My User serializer works well, though how do I go about retrieving the related UserProfile model from the same serializer and viewset? Here is my UserProfile Model: class UserProfile(models.Model): bio = models.CharField(max_length=1000) cellphone = PhoneNumberField(null=True) useraccount = models.OneToOneField(User, on_delete=models.CASCADE) My current viewset: class CurrentUserViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = CurrentUserSerializer permission_classes = [IsAuthenticated] def get_queryset(self): user = self.request.user queryset = User.objects.filter(username = user) return queryset My User serializer: class CurrentUserSerializer(serializers.ModelSerializer): groups = GroupSerializer(many=True) class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'groups') def to_representation(self, instance): return { 'username': instance.username, 'email': instance.email, 'first_name': instance.first_name, 'last_name': instance.last_name, 'groups': GroupSerializer(instance.groups.all(), many=True).data, } I attempted the following with my Serializers, but got an attribute error stating that my User model does not have the field profile: class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('dashboards', 'fullname') class CurrentUserSerializer(serializers.ModelSerializer): groups = GroupSerializer(many=True) profile = TeamMemberDashboardSerializer() class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'groups', 'profile') def to_representation(self, instance): return { 'username': instance.username, 'email': instance.email, 'first_name': instance.first_name, 'last_name': instance.last_name, 'groups': GroupSerializer(instance.groups.all(), many=True).data, 'profile: instance.profile } Thanks for your time! -
Path conflict between server and client
I have a client React app (Electron) that is running on http://localhost:3000/ My Django server has this path in the whitelist: CORS_ORIGIN_WHITELIST = [ "http://localhost:3000" ] The problem is that Python doesn't let me add the / at the end of the path. If I'm calling the server like it is right now it won't work. So can I force Django to accept my url with the / at the end? or maybe change it from my React client. -
Devnagiri/Hindi (indic fonts) Font Are Not Rendering Correctly In Pdf
Output Of Pdf original text is: आसिफ शिख पिख text in output pdf : आसफि शखि पखि text is ok in django console but in pdf it's wrong searched everywhere got some answer suggesting harfbuzz but they are not clear ''' from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter, A4 from reportlab.lib import pdfencrypt from django.http import FileResponse from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont def Genrate_pdf(request): data = Voter_detail.objects.last() BASE_DIR = Path(__file__).resolve().parent.parent buffer = io.BytesIO() p = canvas.Canvas(buffer) pdfmetrics.registerFont(TTFont('Noto', 'static/fonts/NotoSans-Regular.ttf')) pdfmetrics.registerFont(TTFont('barcode', 'static/fonts/LibreBarcode128-Regular.ttf')) pdfmetrics.registerFont(TTFont('marathi_test1', 'static/fonts/NotoSans-Bold.ttf')) pdfmetrics.registerFont(TTFont('marathi_test2', 'static/fonts/MROTBimaB_Ship.ttf')) pdfmetrics.registerFont(TTFont('sakal', 'static/fonts/Eczar-Medium.ttf')) p.setPageSize((153, 243)) # EPIC NAME IN REGIONAL p.setFont('sakal', 9) p.drawString(8,78,"मतदाराचे नाव : %s " % data.rname) print(data.rname) ''' -
__init__() takes 1 positional argument but 8 were given
class Transaction(models.Model): slug = models.SlugField(max_length=200, db_index=True) order_type = models.CharField(verbose_name="Order Method", max_length=200, choices=ORDER_METHODS) paid = models.BooleanField(verbose_name="Paid", default=False) closed = models.BooleanField(verbose_name="Closed", default=False) created = models.DateTimeField(verbose_name="Date of creation", auto_now_add=True) id_num = models.IntegerField(verbose_name="Transaction ID", db_index=True) def __init__(self): super().__init__() self.set_transaction_id() def set_transaction_id(self): self.id_num = int(str(self.created.year) + str(self.created.month) + str(self.created.day).zfill(2) +\ str(self.created.hour) + str(self.created.minute).zfill(2) + str(self.created.second).zfill(2)) When I create this model in a view like this: transaction = Transaction(order_type='Choice_1', paid=False, closed=False) transaction.save() I got this error __init__() takes 1 positional argument but 8 were given. The method set_transaction_id() uses the date and time to set the id_num. Is there something wrong with the way I declare __init__ and using super() or calling set_transaction_id()?