Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RuntimeError: doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS - Django
The folder organization is like this: /project/ apps/ app1/ app2/ ........... core/ view.py ............ __init__.py manage.py settings.py urls.py But I get an error when I want to import a model "House" that I have in the folder "app2" to view.py, the import is the following "from apps.app2 import House" and the error I get is this: House does not declare an explicit app_label and is not in an app in INSTALLED_APPS. If you can help me with a solution, thanks in advance. -
how to plot two graph using plottly using dame function in django
I am trying to plot two graphs on my Django index page. If I call two different functions, then I function is working, but another one is not when I try using the same function, then I do not understand how to give context and call this function here. I am sharing my code sample. Maybe anyone can explain me. data_plots = go.Scatter(x=df2['MeterReading_DateTime'],y= df2['ACT_IMP_TOT'],marker = {'color' : '#335253'}) data_plots1 = go.Scatter(x=df3['MeterReading_DateTime'],y= df3['ACT_IMP_TOT'],marker = {'color' : '#335253'}) #data_plots = px.pie(values=random_x, names=names) layout = {'title': '','xaxis': {'title': 'Date and time'},'yaxis': {'title': 'Total Import(KWH)'},'plot_bgcolor':'#E8E8E8'} fig = {'data': data_plots, 'layout': layout} fig1 = {'data1': data_plots1, 'layout': layout} plot_div = offline.plot(fig, output_type='div') plot_div1 = offline.plot(fig1, output_type='div') return plot_div,plot_div1 def home(request): my_graph = homee(request) context={'graph1':my_graph,'plot_div1':my_graph} return render(request, "index.html", context) -
I can't verify email of user in django
I have django app with authentication and email verification in it. First, user enters credentials in form, then I send him an email with link to verification. And now I get an error. When user clicks on link in mail it says that token is not recognized. from .utils import generate_token class PersonalRegister(View): def post(self, request, *args, **kwargs): ... #get data from form using request.POST.get #sends email current_site = get_current_site(request) email_subject = 'Activate account | Zane' email_body = render_to_string('authentication/email/email_body.html', { 'user': models.PersonalUser, 'domain': current_site, 'uid': urlsafe_b64encode(force_bytes(user.pk)), 'token': generate_token.make_token(user) }) email = EmailMessage(subject=email_subject, body=email_body, from_email=settings.EMAIL_FROM_USER, to=[user.email]) email.send() ... def get(self, request, *args, **kwargs): return render(request, 'authentication/personal/personal_signup.html') From .utils I have imported that function: from time import time from django.contrib.auth.tokens import PasswordResetTokenGenerator import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (six.text_type(user.pk)+six.text_type(timestamp)+six.text_type(user.is_email_verified)) generate_token = TokenGenerator() In render_to_string I have this file email_body.html {% autoescape off %} Hi {{mail}} Please use the link below to verify your account. http://{{domain}}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} So when user clicks on this email it takes him to site which triggers another function: urls.py from django.urls import path from .views import ( Login, PersonalRegister, logout_user, activate_user ) urlpatterns = [ path('login/', Login.as_view(), name='login'), … -
How can I get number of input fields based on users selected number in django models?
So, you guys have seen we search and get for example "top 10 best horror films in hollywood". and these lists sometimes have 5/10/15 films reviews. so I wanted to do that in my project. but in models I have the "List" class. and here I want to set whenever someone creates a list (an instance of List model) they can first select how many movies they wanna put in. for example How many entries you wanna put : [ ], here we can add any int values for example 10. and then the user gets 10 input groups. each group contains (name, image, description) I am sorry if I'm terrible in my explanation . A bit jumbled up here! Thanks. -
Limit 1 after filter in django
SystemsV2.objects.filter(Q(sysname = 'DC_BW_SBX_S4H') | Q(sysname='DC_BW_DEV_S4H')).values('sysname') Executing the above command gives this output, <QuerySet [{'sysname': 'DC_BW_SBX_S4H'}, {'sysname': 'DC_BW_SBX_S4H'}, {'sysname': 'DC_BW_DEV_S4H'}]> How can we make it so that only one of each exists in the result. For example, <QuerySet [{'sysname': 'DC_BW_SBX_S4H'}, {'sysname': 'DC_BW_DEV_S4H'}]> -
Bootstrap navbar dropdown not working due to FlexStart css
I know this is a very common issue; however, this one is peculiar. When I use just the regular CSS style sheets (so without style.css), everything works fine, but as soon as I input in main.css, the dropdown stops working. I have no idea which specific part of the CSS is throwing off the dropdown so I am asking for help. I am using Django templates and if I include the style.css on just the home.html page then the dropdown only doesn't work there. I want to try and keep the FlexStart template so I would appreciate the help. base.html {% load static i18n %}<!DOCTYPE html> {% get_current_language as LANGUAGE_CODE %} {% load bootstrap_icons %} <html lang="{{ LANGUAGE_CODE }}"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>{% block title %}Semiconnect{% endblock title %}</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Behold My Awesome Project!"> <meta name="author" content="Dilreet Raju"> <link rel="icon" href="{%static 'images/favicons/favicon-32x32.png' %}"> {% block css %} {% load static %} <!-- Latest compiled and minified Bootstrap CSS --> <!-- Latest compiled and minified Bootstrap CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" integrity="sha512-GQGU0fMMi238uA+a/bdWJfpUGKUkBdgfFdgBm72SUQ6BeyWjoY/ton0tEjH+OSH9iP4Dfh+7HM0I9f5eR0L/4w==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <!-- Your stuff: Third-party CSS libraries go here --> <!-- This file stores project-specific CSS --> <link href="{% … -
Why Django is not creating Foreign Key constraint on MySQL?
I'm not new to Python nor Django, but this is the first time I'm creating a completely new big project from scratch, and also the first time I'm actually creating the models for the whole database and I'm kinda confused here. Does Django does not really create the ForeignKey constraints on the Database to check if ID exists? It is just a logical python thing that works only when the server is running? Or is it a problem that happens on MySQL? Just to be clear what I'm talking about, the first thing I noticed because as a Laravel developer on PHP side, I'm used to always check the database diagram that PhpStorm/PyCharm generates by connecting to the database, and on Laravel migrated tables, we can see the arrows pointing to the respective foreign key tables relationships, but on the Django created database there is not a single arrow on the database diagram generated by the JetBrains IDE. So I went testing. For example, I have the following models: class Series(models.Model): class Meta: app_label = 'core' db_table = 'km_series' verbose_name_plural = 'series' # added this to avoid plural being "seriess" name = models.CharField(max_length=200) description = models.TextField(default=None, blank=True, null=True) cover_img = … -
Get data from another function to app callback
So I have this data in my views. py. and I’m passing the value to the iotData function that located in my Dash app called ph.py in my views.py from .overview import ph //this is my dash app// def overview(request): post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') ph.iotData(value) //passing the data to this function// return render(request, 'html') ph.py def iotData(value): print(value) //printing the data that from my views.py// @app.callback(Output('graph-ph', 'figure'), [Input('interval-graph-update', 'n_intervals')], [State('graph-ph', 'figure')]) def update_extend_traces_traceselect(n_intervals, fig_raw): //I want to access iotData here so that I can use the data for my graph// how can I pass the data from iotData to my app.callback function -
Sum in query with F() return None instead zero if value is null
I have this query sq_edit = UsulanRekomposisiData.objects.filter(file=draft, prk=OuterRef('prk')) cols = ['edit_jan', 'edit_feb', 'edit_mar', 'edit_apr', 'edit_mei', 'edit_jun', 'edit_jul', 'edit_aug', 'edit_sep', 'edit_okt', 'edit_nov', 'edit_des'] expr = reduce(add, (F(col) for col in cols)) lrpa = monitoring. \ annotate( edit_jan = sq_edit.values('jan'),edit_feb = sq_edit.values('feb'),edit_mar = sq_edit.values('mar'),edit_apr = sq_edit.values('apr'), edit_mei = sq_edit.values('mei'),edit_jun = sq_edit.values('jun'),edit_jul = sq_edit.values('jul'),edit_aug = sq_edit.values('aug'), edit_sep = sq_edit.values('sep'),edit_okt = sq_edit.values('okt'),edit_nov = sq_edit.values('nov'),edit_des = sq_edit.values('des') ).annotate(sum_edit = expr) I want to annotate the sum of edit in each month but it always return None i guess because one of the month value is null. I want if the value is None the F return 0 or is there any other way to get the sum? -
Signal so that when someone follows someone a thread is created between them 2
I have this in models and I want to create a signal that when someone follows someone, a thread is automatically created between that person and the person they followed. The models are in 2 different apps, one from the social network and the other from the chat. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(default='Hola, este es mi Blooby!!!', max_length=100) image = models.ImageField(default='default.png') def __str__(self): return f'Perfil de {self.user.username}' def following(self): user_ids = Relationship.objects.filter(from_user=self.user)\ .values_list('to_user_id', flat=True) return User.objects.filter(id__in=user_ids) def followers(self): user_ids = Relationship.objects.filter(to_user=self.user)\ .values_list('from_user_id', flat=True) return User.objects.filter(id__in=user_ids) class Post(models.Model): timestamp = models.DateTimeField(default=timezone.now) content = models.TextField(max_length=300) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') liked = models.ManyToManyField(User, default=None, blank=True) class Meta: ordering = ['-timestamp'] def __str__(self): return self.content @property def num_likes(self): return self.liked.all().count() LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike'), ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES ,default='Like', max_length=10) class Relationship(models.Model): from_user = models.ForeignKey(User, related_name='relationships', on_delete=models.CASCADE) to_user = models.ForeignKey(User, related_name='related_to', on_delete=models.CASCADE) def __str__(self): return f'{self.from_user} to {self.to_user}' class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.ForeignKey(User,related_name="user_name" , on_delete=models.CASCADE) body = models.TextField() timestamp = models.DateTimeField(default=timezone.now) The models of the app chat , here is the thread class ThreadManager(models.Manager): def by_user(self, **kwargs): user = kwargs.get('user') lookup … -
Pass data from views.py into the plotly dash callback function
I’m working with node js and Django data connection. I have this middleware using node js that can send data using post request. my node.js const payload = mydata; //POST payload to django var obj = { data: payload }; jsonobj = JSON.stringify(obj); var XMLHttpRequest = require("xhr2"); var xhr = new XMLHttpRequest(); xhr.open("POST", "http://127.0.0.1:8000/", true); xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhr.send(jsonobj); And I can access that data in my django project views.py using this following code. It’s printing the data that node js sent. from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def overview(request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') print(value) return render(request, 'myhtml') how can I pass this data (value = post_data.get(‘data’)) into a Plotly dash callback function. I tried this function, but I think it's not recognized request @app.callback(Output('graph-ph', 'figure'), [Input('interval-graph-update', 'n_intervals')], [State('graph-ph', 'figure')]) def update_extend_traces_traceselect(n_intervals, fig_raw, request): if request.method == 'POST': post_data = json.loads(request.body.decode("utf-8")) value = post_data.get('data') print(value) in my template.html {% load plotly_dash %} {% plotly_app name='SimpleExample' ratio=1 %} -
How to solve "user.backend = backend AttributeError: 'NoneType' object has no attribute 'backend" in Django Tests
I'm new to django 3.6 and tried to write a test that involved the use of force_login. But anytime I run it, it gives me the error user.backend = backend AttributeError: 'NoneType' object has no attribute 'backend' even when my force_login backend parameter is already set to django.contrib.auth.backends.ModelBackend this is my test code def test_address_create_stores_user(self): user3 = models.User.objects.create_user('user3', 'pw432joij') post_data = { 'name':'john kercher', 'address1':'1 av st', 'address2':'', 'zip_code':'MA12GS', 'city':'Manchester', 'country':'uk', } self.client.force_login(user3, backend='django.contrib.auth.backends.ModelBackend') self.client.post(reverse('address_create', post_data)) self.assertTrue(models.Address.objects.filter(user=user3).exists()) and this is the error it gives *ERROR: test_address_create_stores_user (main.tests.tests_views.TestPage) Traceback (most recent call last): File "C:\Users\DD\Desktop\practical django\booktime\main\tests\tests_views.py", line 128, in test_address_create_stores_user self.client.force_login(user3, backend='hhh') File "C:\Users\DD.virtualenvs\practical_django-UtJdiNPl\lib\site-packages\django\test\client.py", line 600, in force_login user.backend = backend AttributeError: 'NoneType' object has no attribute 'backend'* -
Nginx support multiple hostnames
I am working on my django + nginx + docker-compose project I want to access my site via ip and mysite.com Problem -- ip url is working, but mysite.com returns error: 403 Forbidden Nginx My code - docker-compose.yml services: django: build: ./project # path to Dockerfile command: sh -c " sleep 3 && gunicorn --bind 0.0.0.0:8000 core_app.wsgi" ... expose: - 8000 env_file: - ./.env depends_on: - db nginx: image: nginx:1.19.8-alpine depends_on: - django env_file: - ./.env ports: - "80:80" volumes: - ./project/nginx-conf.d/:/etc/nginx/conf.d ... nginx-conf.d upstream app { server django:8000; } server { listen 80; server_name 127.0.0.1 mysite.com www.mysite.com; location / { proxy_pass http://django:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /var/www/html/static/; } } -
In Django, using urlpatterns, how do I match a url-encoded slash character as part of a parameter?
In a Django app — this one — I have a urlpatterns list that looks like this: urlpatterns = [ url(r'^$', schema_view, name='swagger'), url(r'^(?P<page_title>.+)/(?P<rev_id>[0-9]+)/$', WhoColorApiView.as_view(), name='wc_page_title_rev_id'), url(r'^(?P<page_title>.+)/$', WhoColorApiView.as_view(), name='wc_page_title'), ] The second entry will match a path like /en/whocolor/v1.0.0-beta/September_11_attacks/1108730659/?origin=* and the third will match a path like /en/whocolor/v1.0.0-beta/September_11_attacks/?origin=*. The idea is that it's matching a page_title parameter (a Wikipedia article title), and an optional integer rev_id (revision id) parameter. However, it does not work as intended for an article titled "Post-9/11", with path /en/whocolor/v1.0.0-beta/Post-9%2f11/?origin=*. I want this not to match the second pattern (which gets matched as page_title "Post-9" and rev_id 11), and instead match the third pattern. I understand why the second pattern should match if the path is /en/whocolor/v1.0.0-beta/Post-9/11/?origin=*, but when the title is url-encoded as "Post-9%2f11" it still matches the second pattern instead of continuing on to the third pattern. How can I make Django treat the url-encoded slash as part of the parameter instead of a path separator? -
"decouple" could not be resolved
I have uninstalled and reinstalled decouple several times, but my settings.py folder is still saying "decouple" could not be resolved. After uninstalling, I even search for it to make sure it's not hiding somewhere, but it says it's not installed. Then, I reinstall using pip install python-decouple Any idea what else can be done? Here's my settings code: import os from decouple import config from datetime import timedelta from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG') ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_extensions', 'user', 'listing', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'core.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'core.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': {}, 'users': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'listings_users', 'USER': … -
Display Messages notifications inside a div box
When the user enter a not valid credentials it print this notificaitons message: Sorry, your password was incorrect.<br/> Please double-check your password But this doesn't look good when it is printed: I want it to be printed between the Login button and the Forgot password. Like that: So theoretically the white box should expend to the bootom to leave so place for the notifications message html file <div class="testlol2" > <div class="login-box" align="center"> <img class="logo" src="{% static 'images/testlogo.png' %}" alt=""> <div class="testlol" align="center"> <form action="" method="post"> {% csrf_token %} {{ form|crispy }} <div class="my-button"> <input class="login-button" type="submit" value="Log in"> </div> </form> {% if messages %} <ul class="messages"> {% for message in messages %} <p{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</p> {% endfor %} </ul> {% endif %} <a class="forgot" href="">Forgot password?</a> </div> </div> </div> css file body{ background-color: #fafafa !important; } .messages { position: relative; top: 10px; right: 8px; color: red; } .logo { position: relative; top: 28px; left: 134px; width: 200px; } .testlol { position: relative; top: 115px; right: 90px; } .testlol2 { display:flex; justify-content: center; } .login-box { display:flex; justify-content: center; align-items: start; align-self: center; position: relative; top: 100px; background: #fff; border: 1px solid … -
justify-content disappears inside mail Django HTML
I created a function in Django to sending activation mails. Now I am styling mail, but the problem is that the justify-content: center; property inside header tag disappears in the mail message. I mean margin-bottom: 20px; display: flex; font-size: 20px; options exist there but justify-content not. def send_activation_email(user, request): email_subject = "..." email_body = render_to_string('activate.html', { ... }) email=EmailMessage(subject=email_subject, body=email_body, from_email=EMAIL_FROM_USER, to=[user.email]) email.content_subtype='html' email.send() <body style="padding: 30px; background-color: #f0f0f0;"> <div style="background-color: white; padding: 30px; border-radius: 10px; box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 1px 3px 1px;"> <header style="margin-bottom: 20px; display: flex; justify-content: center; font-size: 20px;">...</header> </div> </body> -
Unresolved reference, when trying to import an app in django
I'm having problems while trying to import my app.(unresolved reference of new_app and some_page) views.py content: from django.shortcuts import render from django.http import HttpResponse def some_page(request): return HttpResponse('Hello world') In settings i've added app: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'new_app' ] -
Using Postgresql in Django and wants to caculate storage of used by tables
I am using postgresql as django database now i want to calculate the storage size of my models. Like i want to calculate the storage of my model data. Can any provide a solid solution. Recently i see the example of python sys import but this didn't help me kindly provide a solid solution. -
How to Include multiple urls to one django app
In django I've an application 'users' which has a custom user model, a custom registration and profile views, How can I include the app's urls and django's default login and logout urls to the same 'users' app at the same time as below: from django.urls import path, include urlpatterns = [ path('users/', include("django.contrib.auth.urls")), # Django's default authentication urls for login and logout views path('users/', include('users.urls')), # 'users' app custom urls for the registration and profile views ] -
Unable to stop a while loop in djnago chanels after receiving a message (Trying to do a timer using while and asyncio)
I want to stop the while loop when i receive new message how can i do this I am doing this task each time receiving a message from the front end (Its Like A timer, when i press the button the timer start and if the timer == 20s or the button is pressed again the timer will restart) restarting = True i = 0 restarting = False while restarting == False : i += 1 await asyncio.sleep(1) if i == 20 or restarting == True : await self.channel_layer.group_send( self.room_group_name, { 'type': 'starting_timer', 'Timer': i, } ) break await self.channel_layer.group_send( self.room_group_name, { 'type': 'starting_timer', 'Timer': i, } ) so my problem is when i receive a message before 20s (lets say i pressed the button after 5s) the old timer keep sending messages from the old while loop and send another messages of the restarted timer I want to stop the while loop when i receive new message how can i do this -
How to count how many itens were created by day, week and month from DateTimeField()
Having the following model: class Objects(models.Model): created_at = models.DateTimeField(auto_now_add=True) How can I count how many Objects were created by day, week and month, returning an integer number for each query? -
MongoDB connection via Django connector using X.509 certificate
I have a Django API project for which I am using a MongoDB cloud database. The connection to the DB requires authentication via X.509 certificates. How do I achieve this trusted connection using the Djongo connector? Below is the Database connection configuration for my local setup. What needs to change for the CLoud connection with X.509? Thank you for your time and valuable suggestions!!! -
Boostrap Modal and loading images in Django
Firstly I am a beginner at Django but am slowly learning, I have deployed a couple of Django projects, but I have come up against a problem where I have run out of ideas on how to solve due to a lack of knowledge. I have no experience really with the frontend, I have yet to touch Boostrap (although obviously know some HTML ) or JS in detail. I am using a HTML template to build a Photography portfolio, I have a Album view with image thumbnails which work nicely and I have a href to the list of images within that Album. The problem is that template uses Boostrap Modal to open the list of images within the same page, this looks very nice and I want to try and keep it working but unsure how to pass my Django data (ie., the slug from the href ) through the modal. What I have attempted is to split my gallery-detail template which takes in the listview of the Album images filter by that album, and then include that within my main Gallery template which uses my Gallery ListView to show the thumbnails. I though the modal would work this … -
How display categories in forms only for user who created this?
I am creating app for control transaction (expense, income, budget). I want each user to be able to create their own spending categories and their own expenses. All expenses and categories created by a user are to be visible only to that user. If user A creates the category "Food123" then user B cannot see it. He can create his own such category. I've created two models - Category and Expense. class Category(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="category") class Expense(models.Model): name = models.CharField(max_length=100) amount = models.DecimalField(max_digits=8, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="expense") I use a generic view when creating expenses and categories. class ExpenseListView(LoginRequiredMixin, ListView): model = Expense context_object_name = 'expense' template_name = 'expense/expense_list.html' def get_queryset(self): return self.request.user.expense.all() class ExpenseCreateView(CreateView): model = Expense success_url = '/record/expense' form_class = ExpenseForm def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return HttpResponseRedirect(self.get_success_url()) class CategoryCreateView(CreateView): model = Category success_url = '/record/expense' form_class = CategoryForm def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return HttpResponseRedirect(self.get_success_url()) What is more, I've used forms.py. class ExpenseForm(forms.ModelForm): class Meta: model = Expense fields = ('name', 'amount', 'category') class CategoryForm(forms.ModelForm): class Meta: model = Category fields …