Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deal with deeply nested jsons in django being used together with djongo for Mongo
I'm writing my data into a mongo cluster. Basically, I'm getting a json from another serve playing a client and want to save it in my database. I know that djongo makes use of django ORM to add documents into MongoDB, it has a group of fields that allow just that. For example, if I wanted to write the following json: { "h1": "header 1", "content": { "author": "Bruise Lee", "comment": "heart of flint" } } I would craft something like this: from django.db import models from djongo import models as djongomodels from django import forms class BlogContent(djongomodels.Model): comment = djongomodels.CharField(max_length=100) author = djongomodels.CharField(max_length=100) class Meta: abstract = True class BlogContentForm(forms.ModelForm): class Meta: model = BlogContent fields = ( 'comment', 'author' ) class BlogPost(djongomodels.Model): h1 = djongomodels.CharField(max_length=100) content = djongomodels.EmbeddedModelField( model_container=BlogContent, model_form_class=BlogContentForm ) It doesn't look overcomplicated, I'd say it's as simple as mooing but what if I have to deal with a rather complicated json, a monster huge json? How do I go about it? -
adding to a manytomany field in django
I am trying to save a many to many tags field when creating a post. this is my post request to create a new post { "name":"testpost1", "caption":"test caption n", "tags":[{"name":"tag1"}] } Models class Tags(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(max_length=50, unique=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="created_tags") time_created = models.DateTimeField(auto_now_add=True) followers = models.ManyToManyField(User, related_name="following_tags") posts = models.ManyToManyField('Posts', related_name='tags', symmetrical=True) class Posts(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(max_length=50) caption = models.TextField(max_length=1000) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') The serializer for Post and tag class TagsSerializerMini(serializers.ModelSerializer): class Meta: model = Tags fields = ('name', ) class PostsSerializer(QueryFieldsMixin, serializers.ModelSerializer): created_by = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) tags = TagsSerializerMini(many=True, required=False) class Meta: model = Posts fields = ('id', 'name', 'caption', 'tags', 'num_reactions', 'num_comments', 'created_by', 'posted_time', 'updated_time', ) read_only_fields = ('id', 'posted_time', 'updated_time', ) def create(self, validated_data): tags_data = validated_data.pop('tags', []) post = Posts.objects.create(**validated_data) for tag in tags_data: t, _ = Tags.objects.get_or_create(name=tag["name"], created_by=self.context['request'].user) t.posts.add(post) return post Now the issue is, when i am addding a post to tag t.posts.add(post) it is throwing an Error django.db.utils.IntegrityError: FOREIGN KEY constraint failed. I tried adding a post from the shell also, its giving the same error. -
What is form.visible_fields in Django and how do I index into it?
Sometimes I have the need to render a particular Django form field in a particular way. I would like to be able to access this field and only this field in order to customize its rendering in my template. I know, for example, that I can do something like this: <!--Access the form field at index 2--> {% for field in form.visible_fields %} {% if forloop.counter == 2 %} <!--Render my form field the way that I want to--> {% endif %} {% endfor %} Intuitively, I would expect to be able to do something like {{ form.visible_fields[2] }} or perhaps {{ form.visible_fields['field_name'] }}. Unfortunately, my various attempts at the above have all failed and so I'm left wondering if this is possible. Any advice? -
Django Rest framework- getting total number of rows
I would like to output a field that counts the number of Candidat in Candidat Model. I am currently using the following serializer: class CountCSerializer(serializers.ModelSerializer): user_count = serializers.SerializerMethodField() class Meta: model = Candidat fields = ( 'user_count',) def get_user_count(self, obj): return Candidat.objects.count() and the following api: class CountCViewSet(ModelViewSet): queryset = Candidat.objects.all() serializer_class = CountCSerializer But im getting nothing! Any help in the matter would be much appreciated. -
convert a string to integer in django templates
I am getting error when trying to multiply the below in django templates (multiply is a custom tag)- {{ contact.cost|add:"0" |multiply:contact.rate }} cost is of type varchar and rate is of type decimal in models.py. I tried putting in add:"0" for converting the string to integer first and then multiplying but it is still giving an error. can't multiply sequence by non-int of type 'decimal.Decimal' What is wrong? Still very new to django, please help. -
Django Form: Redirect to the page which sent the post request
I have 2 pages which allow to send user a private message. On both of these pages I have a form which is processed by the same view e.g. def send_message(request, pk) # send this user a message return redirect_to_page_which_sent_POST_request So my goal is to use the same method to precess forms on both pages, and redirect back to the page. I know I can do this by adding next parameter to the form but are there any simpler ways? -
Adding to comments to post: Page not found (404)
Hi Djangonauts I am new to Django please forgive me if I have silly mistakes in my code and I am currently trying to add comments to my post model below are my models.py class Post(models.Model): user = models.ForeignKey(User, related_name='posts') title = models.CharField(max_length=250, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) message = models.TextField() def get_absolute_url(self): return reverse('posts:single', kwargs={'username': self.user.username, 'slug': self.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments') author = models.ForeignKey(User, related_name='comments') text = models.TextField() def get_absolute_url(self): return reverse('posts:single', kwargs={'username': self.post.user.username, 'slug': self.post.slug}) below are my views.py for comment create and comment remove @login_required def add_comment_to_post(request, slug): post = get_object_or_404(Post, slug=slug) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.author = request.user comment.save() return redirect('posts:single', username=comment.author.username, slug=post.slug) else: form = CommentForm() return render(request, 'posts/comment_form.html', {'form': form}) @login_required def remove_comment(request, pk): comment = get_object_or_404(Comment, pk=pk) comment.author = request.user post_slug = comment.post.slug comment.delete() return redirect('posts:single', username=request.user.username, slug=post_slug) I get a error as below Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/posts/... Raised by: posts.views.PostDetail -
Django CBV's: Custom mixin's that override the same method of one View
I have the following CBV with custom mixins, AjaxFormMixin_Home and AjaxFormMixin_Production. class BaseView(AjaxFormMixin_Home, AjaxFormMixin_Production, FormMixin, View): Both mixins override def get_context_data(self, **kwargs): as required by FormMixin. They need to update context with custom QuerySets based on certain ajax conditions. However, changing the order of inheritance only returns the context as defined by that particular mixin. For instance, Below will only return context as defined by AjaxFormMixin_Home class BaseView(AjaxFormMixin_Home, AjaxFormMixin_Production, FormMixin, View): Whereas below will only return context as defined by AjaxFormMixin_Production class BaseView(AjaxFormMixin_Production, AjaxFormMixin_Home, FormMixin, View): Lastly, I've noticed the compiler ignores the second mixin altogether (depending on order of inheritance). How can does one get around this type of issue? Thanks! -
ImportError: cannot import name 'add_lazy_relation' while trying to import DictField from djangotoolbox.fields
Here is what I use: django 2.0 djangotoolbox 1.8 Linux OS Seems like it's the case with importing the whole fields module from djangotoolbox, that's to say, from djangotoolbox import fields yields just the same error. Do you have any ideas how to sort it out? -
Empty choice with SelectDateWidget in django 1.11
For the SelectDateWidget, Django documentation states the following: If the DateField is not required, SelectDateWidget will have an empty choice at the top of the list (which is --- by default). You can change the text of this label with the empty_label attribute. empty_label can be a string, list, or tuple. When a string is used, all select boxes will each have an empty choice with this label. If empty_label is a list or tuple of 3 string elements, the select boxes will have their own custom label. The labels should be in this order ('year_label', 'month_label', 'day_label'). However, it is not clear to me how to set empty choice with the required date field? I assume this is not a rare situation: without the empty choices, but with default values preselected, one can easily skip the required date field and save it with the default values without noticing. Does someone knows how to do this? -
Cannot set the expire date of a cookie
I'm developing an web application with ReactJS and a Django web API. My problem is: I send a request to the API, that returns me a token, that I'll use to send requests that needs authentication, and a expire date for the token. The response is something like: { name: "Elliot", id: 1, token: "<the token here>" expires: "2018-04-29T17:00:00.000Z" } Then, when I try to do this: document.cookie = token=${response.token};expires=${response.expires} It sets the expire date to the year of 1969. Does anyone know why? Details: I took a look if the date isn't already expired, but, it's not. It's always 3 hours from now. Edit: The ` around the atribution to document.cookie is not appearing, because of the markdown, but, it haves. -
Why is EC2 taking so long to execute these SQLite queries?
I'm working on a script that a teammate of mine used to build an SQLite3 database locally on his machine. I made some modifications so that we can use it in our Django application to update the database with new data uploaded by the user. The application allows the user to upload a zip file containing multiple well-formatted csv files and adds the information from the csv's to the database. These are the relevant parts of the code: update_db.py import glob, sqlite3, pandas, timeit, re def upload_files(csv_files): conn = sqlite3.connect('/path/to/my_db.db') c = conn.cursor() added_tables = [] for row in c.execute("SELECT name FROM sqlite_master WHERE type='table'"): table_name = re.sub(r'\W+', '', str(row)) added_tables.append(table_name) for csv_filename in csv_files.namelist(): if csv_filename.endswith('.csv'): csv_file = csv_files.open(csv_filename) # extract team name from csv_file string, remove whitespace table_name = csv_filename.rsplit('/',2)[1] table_name = re.sub('[^\w+]', '', table_name) try: df = pandas.read_csv(csv_file, error_bad_lines=False) df.to_sql(table_name, conn, if_exists='append', index=False) if table_name not in added_tables: # add necessary columns c.execute('alter table ' + str(table_name) + ' add team_BASEDOWN integer;') c.execute('alter table ' + str(table_name) + ' add team_FIELDPOSITION integer;') c.execute('alter table ' + str(table_name) + ' add team_HEADCOACH text;') c.execute('alter table ' + str(table_name) + ' add team_OFFCOOR text;') c.execute('alter table ' + str(table_name) … -
Tkinter vs Django for Model View Controller
I am currently studying MVC Patterns and was wondering which has a better implementation of the Model-View-Controller pattern? Why would one be better than the other? I feel like they are basically the same thing. -
Is there a naming convention for Django project/configuration directory?
referring to directory holding settings.py and wsgi.py ('Two Scoops of Django' refers to this as the 'configuration root', for what it's worth) I've seen people name this directory after the actual project name (the official Django tutorial does this) but that leads to a redundant/confusing directory structure like the following: mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py app1/ app2/ seems like it'd be more clear to have something like the following: mysite/ manage.py conf/ __init__.py settings.py urls.py wsgi.py app1/ app2/ so curious to hear if there are some common names for this directory saw that there was already a question about Django app naming convention but couldn't find anything regarding project/conf directory -
Check Database while debuging test in django
I need to check the database during a test. I change the settings to : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'TEST': { 'NAME': os.path.join(BASE_DIR, 'test_db.sqlite3'), } } } So now when i run : python3 manage.py test --keepdb accounts I finish with a test_db.sqlite3 , the problem is that this database after and during the test is empty all the time. I am executing this code : def test_add_members(self): pp_castrillon = GrupoPolitico(nombre_grupo="PP", alcance=self.test_concejo) pp_castrillon.save() print(pp_castrillon.miembros.count()) user_a = User(username="A_test") user_b = User(username="B_test") user_c = User(username="C_test") user_a.save() user_b.save() user_c.save() user_a.residencia.add(self.test_concejo) user_b.residencia.add(self.test_concejo) user_c.residencia.add(self.test_concejo) pp_castrillon.grupo.user_set.add(user_b) pp_castrillon.miembros.add(user_a) pp_castrillon.grupo.grupo_de.add_member(user_c) pp_castrillon.save() for miembro in pp_castrillon.miembros.all(): print(miembro) for miembro in pp_castrillon.grupo.grupo_de.miembros.all(): print(miembro) for miembro in pp_castrillon.grupo.user_set.all(): print(miembro) print(user_a.miembro.all()) print(pp_castrillon.miembros.count()) This function test is inside a class extending django.test.TestCase Someone knows how I could do this ? Thanks all in advance. -
Using Django Signals post_save error "save() prohibited to prevent data loss to do unsave related object ''myModel."
Django 1.11 Pseudo explanation: Two Models, with model2 using model1 as a ForeignKey Admin for Model1 uses an inline for model2 On model1, I want to get a shortened URL and store that in a property when there is a new entry. To do that, I need to have a save model1 because the long URL is based on a slug. So, I am deep into post_save signals and the issue I'm having is that when I save the model1 instance, I get an error save() prohibited to prevent data loss to unsaved related object 'model1' @receiver(post_save, sender=Model1) def shorten_url(sender, instance, created, **kwargs): if created: if not instance.short_url: url_short = url_shorten(instance.get_absolute_url()) instance.short_url = url_short post_save.disconnect(shorten_url, sender=sender) instance.save() post_save.connect(shorten_url, sender=sender) return instance else: post_save.disconnect(shorten_url, sender=sender) instance.save() post_save.connect(shorten_url, sender=sender) return instance The disconnect, connect is to prevent loops, I'm not 100% sure that it is correct yet either, but without it, I see calls to shorten the url over and over... But the issue I'm trying to solve now is that -
Django saving multiple records to multiple database table
I got little bit trouble here, here my database table EmpLoan table +---------+-------------+-----------+----------+ | id | nominal | emp_id | status | +---------+-------------+-----------+----------+ | 1 | 50 | 1 | 1 | | 2 | 50 | 2 | 1 | | 3 | 100 | 3 | 1 | | 4 | 100 | 1 | 0 | | ... | ... | ... | ... | +---------+-------------+-----------+----------+ EmpInstallment table +---------+-------------+-----------+ | id | nominal | loan_id | +---------+-------------+-----------+ | 1 | 10 | 4 | | 2 | 10 | 4 | | 3 | 10 | 4 | | 4 | 10 | 4 | | ... | ... | ... | +---------+-------------+-----------+ and here my view.py 1 class EmployeeCreateView(CreateView): 2 fields = () 3 model = models.EmployeeLoan 4 5 def form_valid(self, form): 6 self.object = form.save(commit=False) 7 try: 8 loan = models.EmpLoan.objects.get(emp_id=1, status=0) 9 installments = models.EmpInstallment.objects.filter(loan_id=loan.id).values_list('id', flat=True) 10 total_installment = 0 11 12 for i in installments: 13 installment = models.EmpInstallment.objects.get(id=i).nominal 14 total_installment = total_installment + installment 15 16 loan_remaining = loan.nominal - total_installment 17 18 if ( 12 - installments.count()) != 0: 19 installment_now = loan_remaining / ( 12 - cicilans.count()) 20 else: 21 … -
Order Relations (ManyToMany) without duplicating records django
For days I've been trying to sort a series of queries by passing as parameter objects.order_by ("relation").distinct() of type "ManyToMany" but always duplicates the query "x" the number of relations, the last being the desired. class Person(models.Model): name = models.CharField(max_length=200) groups = models.ManyToManyField('Group', through='GroupMember', related_name='people') class Meta: ordering = ['name'] def __unicode__(self): return self.name class Group(models.Model): name = models.CharField(max_length=200) class Meta: ordering = ['name'] def __unicode__(self): return self.name class GroupMember(models.Model): person = models.ForeignKey(Person, related_name='membership') group = models.ForeignKey(Group, related_name='membership') type = models.CharField(max_length=100) def __unicode__(self): return "%s is in group %s (as %s)" % (self.person, self.group, self.type) # Not work, recieve multiple queries duplicates. Person.objects.all().order_by("membership__type", "group__name").distinct("id") Note that although adding "distinct ()" is duplicating the values of the query, my question is what is the reason and how to solve it. The database that I am using PostgreSQL. Thank you. -
Django Rest Framework - Can't specify seconds on DateTimeField HTML form
I'm using the Django REST framework and trying to POST a DateTimeField on the HTML form, I can write everything but the seconds. Here is a printscreen that shows what I mean: I've tried to update the serializer to: timestamp = serializers.DateTimeField(input_formats='%Y-%m-%dT%H:%M:%SZ') But it didn't work. -
django static files aren't updating while live
So it's been a while since I made my website go live using django, so I decided to make some changes in some css and js files. After modifying them, none of the new changes have been updated to the website yet. I am aware that the files may have been cached, but I have read that there is a technique to force the server to update the files, by adding ?version=x after the file path. For example: <link rel="stylesheet" type="text/css" href="style.css?version=1"> The problem is that with django, I did not reference the static files exactly like that, instead I had to use some jinja logic. Example: <link rel="stylesheet" type="text/css" href="{% static mainpage/HomePage.css' %}" /> I tried adding ?version=1 to the end of the file path for mine, but after I looked at the website on my browser, some css seemed to have gone missing, so I decided to go back to my original link. Does anyone know how I can apply the solution of adding ?version=1 to my case? I'm pretty knew to css and html, and I would be very grateful for any help! -
Admin inline without foreign key
I am creating a blog and I am a beginner in Django. I have three models Slug, Post, Category. class Slug(models.Model): slugable_type = models.CharField(max_length=32) slugable_id = models.IntegerField() slug = models.CharField(max_length=127) class Category(models.Model): name = models.CharField(max_length=255) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) parent = models.ForeignKey('Category', on_delete=models.CASCADE) def __str__(self): return self.title class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=255) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.title Now In Slug model slugable_type will contain the model name (Post or Category) and slugable_id is the id of that model object. In this way, I want to set up a polymorphic relation (just like I do in Laravel) between Slug, Post and Category Model. Where each object of Category and Post model will have exactly one corresponding Slug Object. Now I want to create a slug while creating a post or category. But don't know how to register these three model in Django administration. As to have an admin inline there must be a Foreign key defined which is not possible in my case. -
Add users to the post
In your thoughts, make sure that when you click on the "Add" button, a list of users from the "Техническая поддержка" group comes out, and by selecting one user, he becomes the "Executor" (owner) of this "Application". Application_detail - this is where the add button is found. I'm probably doing something wrong. Thank you in advance for your cooperation) models.py class Application(models.Model): ... class Meta: permissions = ( ("can_add_change", "Пользователь"), ("can_close", "Техническая поддержка") ) class Executor(models.Model): application = models.ForeignKey('Application', null = True, verbose_name='Заявка', on_delete=models.CASCADE) owner = models.ForeignKey(User, related_name = 'owner', null = True, blank = True, on_delete=models.CASCADE, limit_choices_to={ 'groups__name': 'Техническая поддержка'}, verbose_name = 'Исполнитель') admin.py class ExecutorInline(admin.TabularInline): model = Executor insert_after = 'status' extra = 1 class ApplicationAdmin(admin.ModelAdmin): inlines = [ExecutorInline] views.py def application_detail(request, pk): post = get_object_or_404(Application, pk=pk) helpers = User.objects.filter(groups__name='Техническая поддержка') return render(request, 'helpdesk/application_detail.html', {'post': post, 'helpers': helpers}) def add_owners(request, pk): post = get_object_or_404(Application, pk=pk) helpers = User.objects.filter(groups__name='Техническая поддержка') username = request.user helper = User.objects.get(username=request.GET.get('helper')) post.executor_set.add(owner = helper) post.save() return redirect('application_detail', pk=post.pk) html <a href = '{% url 'helper' pk=post.pk %}'>{{helpers}}</a> -
Python / Django NoReverseMatch
I'm giving Python / Django a ago, going alright so far. I'm in the middle of setting up Django authentication, but I've hit a error; Reverse for 'user_review_list' not found. 'user_review_list' is not a valid view function or pattern name. Here are my views: def user_review_list(request, username=None): if not username: username = request.user.username latest_review_list = Review.objects.filter(user_name=username).order_by('-pub_date') context = {'latest_review_list':latest_review_list, 'username':username} return render(request, 'reviews/user_review_list.html', context) In my base.html I call the following: <li><a href="{% url 'reviews:user_review_list' user.username %}">Hello {{ user.username }}</li> I've checked my other html templates and they all seem to be calling it correctly, is there anything I'm missing? Thanks. -
Django Json saved in DB how to use in template?
I am trying to save a Json data in DB and then display it in template. Data is saved as: {"reaction": [{"reactionmeddrapt": "Stress fracture", "reactionmeddraversionpt": "20.1", "reactionoutcome": "1"}, {"reactionmeddrapt": "Drug effect incomplete", "reactionmeddraversionpt": "20.1", "reactionoutcome": "6"}, {"reactionmeddrapt": "Osteoarthritis", "reactionmeddraversionpt": "20.1", "reactionoutcome": "3"}, {"reactionmeddrapt": "Fracture delayed union", "reactionmeddraversionpt": "20.1", "reactionoutcome": "6"}, {"reactionmeddrapt": "Knee arthroplasty", "reactionmeddraversionpt": "20.1", "reactionoutcome": "6"}], "drug": [{"medicinalproduct": "PROLIA", "drugindication": "PRODUCT USED FOR UNKNOWN INDICATION", "drugadministrationroute": "065", "drugdosagetext": "UNK, Q6MO", "openfda": {"manufacturer_name": ["Amgen Inc"], "unii": ["4EQZ6YO2HI"], "product_type": ["HUMAN PRESCRIPTION DRUG"], "rxcui": ["993452", "993456"], "spl_set_id": ["49e5afe9-a0c7-40c4-af9f-f287a80c5c88"], "route": ["SUBCUTANEOUS"], "generic_name": ["DENOSUMAB"], "brand_name": ["PROLIA"], "product_ndc": ["55513-710"], "pharm_class_epc": ["RANK Ligand Inhibitor [EPC]"], "substance_name": ["DENOSUMAB"], "spl_id": ["f0a4aa32-b689-4a2a-b575-7b3156e79c0c"], "pharm_class_moa": ["RANK Ligand Blocking Activity [MoA]"], "application_number": ["BLA125320"], "nui": ["N0000187054", "N0000187055"], "package_ndc": ["55513-710-01"]}, "drugdosageform": "SOLUTION FOR INJECTION", "drugcharacterization": "1", "activesubstance": {"activesubstancename": "DENOSUMAB"}, "drugauthorizationnumb": "125320", "actiondrug": "5", "drugadditional": "3"}]} In my view I converted this data using json.loads(json_data) Now I am trying to iterate this in template but not able to do it. I have tried with Json_data with json.loads and without json.loads. It does not seem to work. I have tried every every thing in template {% for key, value...... and directly {{json_data.field_name}} It seems to be one of most asked question on SO and no specific … -
How to update (GET) from one view/ model and enter(POST) from another view/model in one django template
I am creating a User input form using two models. 1. Account ( Having Fixed Values) 2. NetworkInformation ( Information Related to Account) Now i have created an Index View where i have all the accounts mentioned from my Account Model.Below is the account List View: Account Name Country Name Market Name Manager Account1 UK M1 Manager1 Add Information Account2 India M2 Manager2 Add Information Account3 US M3 Manager3 Add Information Account4 Ghana M4 Manager4 Add Information I want to click on Add Information link to navigate to the detail page of account along with the input form for network, so that I can enter network information related to that account. Here is my Model.py class AccountInformation(models.Model): accountName = models.CharField(max_length=40) countryName = models.CharField(max_length=40) marketName = models.CharField(max_length=20) managerName = models.CharField(max_length=50) def get_absolute_url(self): return reverse('AccountInformationIndexView') def __str__(self): return self.accountName class NetworkRelatedInformation(models.Model): account = models.ForeignKey('AccountInformation', on_delete=models.DO_NOTHING) month = models.CharField(max_length=40, default='Select Month') year = models.IntegerField(default=0) a_count = models.IntegerField(default=0) b_count = models.IntegerField(default=0) c_count = models.IntegerField(default=0) d_count = models.IntegerField(default=0) Here is my views.py def AccountNetworkInputView(request, account): if request.method == 'GET': context_object_name = 'AccountInformation_list' template_name = 'personal/AccountInformationIndexView.html' def get_queryset(self): return AccountInformation.objects.all(id=pk) if request.method == 'POST': form = NetworkRelatedInformationForm(request.POST) if form.is_valid(): account = request.POST.get('pk') month = request.POST.get('month', '') …