Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Change the Format of a DateTimeField Object when it is Displayed in HTML through Ajax?
models.py class Log(models.Model): source = models.CharField(max_length=1000, default='') date = models.DateTimeField(default=datetime.now, blank = True) views.py The objects in the Log model are filtered so that only those with source names that match a specific account name are considered. The values of these valid objects will then be listed and returned using a JsonResponse. def backlog_list(request): account_name = request.POST['account_name'] access_log = Log.objects.filter(source=account_name) return JsonResponse({"access_log":list(access_log.values())}) dashboard.html This Ajax script is the one that brings back the account name to the views.py. If there are no valid objects, the HTML will be empty; however, it will display it like this otherwise. <h3>You scanned the QR code during these times.</h3> <div id="display"> </div> <script> $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'POST', url : "/backlog_list", data:{ account_name:$('#account_name').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success: function(response){ console.log(response); $("#display").empty(); for (var key in response.access_log) { var temp="<div class='container darker'><span class='time-left'>"+response.access_log[key].date+"</span></div>"; $("#display").append(temp); } }, error: function(response){ alert('An error occurred') } }); },1000); }) </script> My goal is to have the Date and time displayed like "Jan. 10, 2000, 9:30:20 A.M." I've tried changing the format directly from the models.py by adding "strftime" but the error response is triggered. -
Adding a custom, non-model attribute to query set in Django?
Newbie to DRF and have a model called posts. And another called user. The post object looks as follows: class Post(models.Model): """ Post model """ title = models.CharField(max_length=250) body = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='forum_posts') parent_post = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) time_stamp = models.DateTimeField(default=timezone.now) objects = models.Manager() The serializer for this model is: class PostSerializer(serializers.ModelSerializer): class Meta: model = models.Post fields = ('id', 'title', 'body', 'parent_post', 'author', 'time_stamp') extra_kwargs = {'id': {'read_only': True}, 'author': {'read_only': True}} When returning data for this model, I want to add an extra attribute to each object within the query set called "author_username". The username should be the username belonging to the post's author id. I also want to do this without modifying the model to add another attribute such as "author_username" since this'll be redundant (already have an FK for author). So, ideally, the json for an object would look like: 'post_id': 1 'post_title': 'Example post' 'post_body': 'Example post' 'author_id': 1 'parent_post_id': null 'time_stamp': '2022' 'author_username': 'testUser' How can I go about doing this? Here's my view: class PostList(generics.ListCreateAPIView): permission_classes = [IsAuthenticatedOrReadOnly] queryset = models.Post.objects.all() serializer_class = serializers.PostSerializer -
How to convert db data into json format using python
database table data as input I have the above type of table data (screenshot) and i wanted to convert it into json dictionary using python. I tried my best but unable to create the hierarchy as per my requirement. I want the following json output. output result as json format -
Django Models: Filter a subset of a query set
I have these two models: class InspectionPoint(models.Model): ... review_check = models.BooleanField(default = 0) flight = models.ForeignKey( Flight, related_name='inspection_points', on_delete=models.CASCADE, null=True, blank=True ) ... class ImageSnapshot(models.Model): ... inspection = models.ForeignKey( InspectionPoint, on_delete=models.CASCADE, related_name = 'snapshots' ) flight = models.ForeignKey( Flight, related_name='snapshots', on_delete=models.CASCADE, null=True, blank=True ) ... I already have snapshots queryset with: snapshots = ImageSnapshots.objects.filter(flight=flight) but that gives me all snapshots. I want to filter snapshots that have only (review_check = True) Any idea? -
Django Channels Channels-redis How can I access the database of redis and how can I use it?
I used Django Channels for the first time and Redis for the first time through Channels. I want to use the data stored in the redis server currently in use by django or save it in the redis server. When listing chat rooms, I want to use channels_layer.receive_count to show the number of people who are accessing the chat room. (Like Twitch) When I access the chat room, I want to list the information of the users there. It would be nice if you could tell me how. Thank you! -
Two django projects with common userbase , authentication and sharing of key functionalities
I'm building a Django v3.2 project that requires merging of 2 projects(social app and ecommerce) - both of which are separate open source django projects. The end goal is to share users, posts and a common user registration and authentication process and keep a common database for both. Project 1 has a 5 docker containers(api backend, worker,scheduler, sql db, redis db) and project 2 has 1 docker container(that has a frontend sandbox ecommerce website). I came across this post while searching which is similar : How to make two django projects share the same database Based on the post share above, My core question is : While I'm using 2 separate projects that run their own docker containers, what changes will I have to make so that Registration, Authentication & Users are common Functionalities are shared. Essentially, I would like to import modules from project1-->project2 and project2-->project1 and design additional functionalities as per need. I initially tried copying files from project 2 into project 1 so that the project1 social app and functionality is just extended. But I'm running into all sorts of problems. Here is the question pertaining to the same : Python3.10:ModuleNotFoundError: No module named 'commerce' -
This code worked yesterday for another project, but its showing some error, I cannot get what the error is
what is the error here this is my models.py code, this code worked for another app, but not working in this. why? -
Adding an additional key-value pair to objects in a list before passing it to a Template - Working, but I'm not sure why
New to Django and I wanted to append a key:value pair to each Job object in a Queryset/list before passing it to a template. Researching on here it says you can't just append a field, but rather need to create a new dict or could possibly add attributes or something, but messing around I got it to work great, but logically it seems it shouldn't work, and I worry I may run into problems or data inconsistency somewhere. My "jobs" view gets all Jobs currently not assigned to a User, filters out Jobs based on the current signed in Users listed skillset(a custom field for my User model), and then the functionatily I'm adding is to check the current Users schedule, and add a value "conflict":True if the schedule conflicts so I can highlight it red when rendering the list of jobs to the screen. views.py (abbreviated): def jobs (request): //get all unassigned jobs, and create a list of only jobs where the user has matching skills available = Job.objects.filter(assigned_to__isnull=True).order_by('start_time').all() available = [job for job in available if request.user.is_skilled(job)] //go through each job, make it a dict, and add "conflict":True to it if scheudle confict for job in available: if … -
applying reverse relations with Foreign Key on two different Django models produces incorrect output
Class Job(Base): . . joining_status = models.BooleanField(default=False) drive = models.ForeignKey(Drive, null=True, blank=True) Class Internship(Base): . . joining_status = models.BooleanField(default=False) drive = models.ForeignKey(Drive, null=True, blank=True) Class Drive(xyz): . . . I'm trying to annotate count of jobs & internship (sum) having joining status true for a specific drive id. Drive.objects.filter(id=716).annotate(\ ...: x= Count(Case(\ ...: When(Q(internship__joining_status=True), then=1), output_field = IntegerField()))).values('x') output {'x':0} Drive.objects.filter(id=716).annotate(\ ...: x= Count(Case(\ ...: When(Q(job__joining_status=True), then=1), output_field = IntegerField()))).values('x') output {'x':1} But when I'm combining both together it is producing undesired result. Drive.objects.filter(id=716).annotate(\ ...: x= Count(Case(\ ...: When(Q(job__joining_status=True) | Q(internship__joining_status=True), then=1), output_field = IntegerField()))).values('x') output: {"x":2} // undesired output it should be {'x':1} I tried using multiple when conditions also, but the result was again undesirable. I'm a bit new in django, need help in writing this query. -
get the two types of sets from a model with condition
I want to get the credits and debits from the model, with condition tried a lot of methods but failed to approach the answer, the model i am working on is class SupplierTrans(models.Model): supplierName = models.ForeignKey(Supplier, on_delete = models.CASCADE) paid = models.BooleanField(default=True) amount = models.IntegerField() remarks = models.CharField(max_length = 200) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: ordering = ['-update', '-created'] def __str__(self): return str(self.supplierName) @property def paid_purchsased(self): return 'Paid' if self.paid == True else "Purchased" I approach in a methos that is sup = SupplierTrans.objects.annotate( credit = Sum('amount', paid=True), debit= Sum('amount', paid=False)).order_by('supplierName__name') but its not working the out is get the all the sum of the amount in the table if not filtering boolean values but the required is getting by the following method credit_amt = SupplierTrans.objects.filter(paid=True).aggregate(Sum('amount')) debit_amt = SupplierTrans.objects.filter(paid=False).aggregate(Sum('amount')) I wana get the following values in the above condition is there any approach, or should change the table structure -
How can query for group by based on unique value in Django
I want to group by data based on unique value. Eg. country: xyz, city: abc; country: xyz, city: efg; country: wxyz, city: abcde Query Result: xyz:[abc, efg], wxyz: [abcde] I solved this using dictionary**( query_res[country_val].append(city_val) )** , but I want to know if there have better solution. -
My Django Admin input doesn't allow me to add more than one image
I'm trying to make a Django model, with Django Rest Framework. I want this to allow me to load one or more images in the same input. MODELS: from django.db import models from datetime import datetime from apps.category.models import Category from django.conf import settings class Product(models.Model): code = models.CharField(max_length=255, null=True) name = models.CharField(max_length=255) image = models.ImageField(upload_to='photos/%Y/%m/', blank = True, null=True, default='') description = models.TextField() caracteristicas = models.JSONField(default=dict) price = models.DecimalField(max_digits=6, decimal_places=2) compare_price = models.DecimalField(max_digits=6, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) sold = models.IntegerField(default=0) date_created = models.DateTimeField(default=datetime.now) def __str__(self): return self.name class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name = 'images') image = models.ImageField(upload_to='photos/%Y/%m/', default="", null=True, blank=True) SERIALIZER: from rest_framework import serializers from .models import Product, ProductImage class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImage fields = ["id", "product", "image"] class ProductSerializer(serializers.ModelSerializer): images = ProductImageSerializer(many=True, read_only=True) uploaded_images = serializers.ListField( child = serializers.ImageField(max_length = 1000000, allow_empty_file = False, use_url = False), write_only=True ) class Meta: model = Product fields = [ 'id', 'code', 'name', 'description', 'caracteristicas', 'price', 'compare_price', 'category', 'quantity', 'sold', 'date_created', 'images', 'uploaded_images' ] def create(self, validated_data): uploaded_images = validated_data.pop("uploaded_images") product = Product.objects.create(**validated_data) for image in uploaded_images: newproduct_image = ProductImage.objects.create(product=product, image=image) return product I would simply like how to make the … -
How can I get the values of cartItem and make a n order?
How can I get the obj of the the cartItem and place an order? here's how my models.py look like. class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) class CartItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) cart = models.ForeignKey('Cart', on_delete=models.CASCADE) selected = models.BooleanField(default=False) -
How do I hit a Django-allauth login endpoint for automated testing
Context: I am creating some boilerplate automation to essentially login to a website as a restricted user and then verify that when I hit another endpoint, I get an unauthorized response. I don't have much experience with setting up an API automated testing framework from scratch, but I am using Behave and Behave-Django for all other automation. All my test data is coming from a django .env file. My current step to hit the login api as a restricted user is as follows: @given('I log in as a restricted user') def login(context, user): context.url = 'https://myurl.com' context.user_logged_in.send(user) assert context.status_code == 403 I'm pretty green when it comes to django, so if I'm not even close let me know. Thanks! -
GET specific item from table on click in Django MVT
I have a table of products being displayed in my template using jinja loop. ` {% extends 'base.html' %} {% load static %} {% block css %} <link rel="stylesheet" href= "{% static 'css\store.css' %}" > {% endblock %} {%block content%} {% load static %} <div class="secondnav"> <a class="nav-item" href="construction"> Figures </a> <a class="nav-item" href="construction"> Manga </a> <a class="nav-item" href="construction"> Clothes </a> </div> {% for product in products %} <div class="container2"> <div href="item" class= 'product-item'> <div class= 'image-cont'> {# Pass the id of the product to the item view when the user clicks on the product #} <a href="{% url 'item' product.id %}"><img class='product-image'src = '{{product.product_picture.url}}' alt="" ></a> </div> {% if product.offer != 0 %} <div class= 'offer-banner' > {# Pass the id of the product to the item view when the user clicks on the offer banner #} <a href="{% url 'item' product.id %}">Special Offer</a> </div> {% endif %} </div> <div href="item" class="product-content"> <div href="item" class="product-title"> {# Pass the id of the product to the item view when the user clicks on the product title #} <a href="{% url 'item' product.id %}" >{{product.name}}</a> </div> <div class="product-price"> {# Pass the id of the product to the item view when the user … -
IntegrityError at /api/course/ (1048, "Column 'category_id' cannot be null")
Hello everyone i need some help over this issue in Django *IntegrityError at /api/course/ (1048, "Column 'category_id' cannot be null") i got this when i tried to insert a new course * class Course(models.Model): category = models.ForeignKey(CourseCategory, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE , related_name='teacher_courses') title = models.CharField(max_length=150) description = models.TextField() featured_img = models.ImageField(upload_to='course_imgs/',null=True) techs = models.TextField(null=True) class Meta: verbose_name_plural = "3. Courses" def related_content(self): related_content=Course.objects.filter(techs__icontains=self.techs) return serializers.serialize('json',related_content) def tech_list(self): tech_list = self.techs.split(',') return tech_list def __str__(self): return self.title class CourseList(generics.ListCreateAPIView): queryset = models.Course.objects.all() serializer_class = CourseSerializer def get_queryset(self): qs = super().get_queryset() if 'result' in self.request.GET: limit = int(self.request.GET['result']) qs = models.Course.objects.all().order_by('-id')[:limit] if 'category' in self.request.GET: category = self.request.GET['category'] qs = models.Course.objects.filter(techs__icontains=category) if 'skill_name' in self.request.GET and 'teacher' in self.request.GET: skill_name = self.request.GET['skill_name'] teacher = self.request.GET['teacher'] teacher = models.Teacher.objects.filter(id=teacher).first() qs = models.Course.objects.filter(techs__icontains=skill_name,teacher=teacher) return qs class CourseSerializer(serializers.ModelSerializer): class Meta: model = models.Course fields =['id','title','description','category_id','teacher','featured_img','techs','course_chapters','related_content','tech_list'] depth=1 I have been searching the solution for hours but i did not get any way to solve the issue and i expect you to help me thank you -
Django many to many model get none
I have been dealing with a project for a few days and today I encountered an error. I wanted to write it here as I have no idea how to solve it. My first model: from django.db import models # Create your models here. class Video(models.Model): title = models.CharField(max_length=100) video_slug = models.SlugField(unique=True) description = models.TextField(max_length=500) image = models.ImageField(upload_to='images/' , blank=True, null=True) video = models.FileField(upload_to='videos/', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) category = models.ManyToManyField('categories.Category', blank=True) def __str__(self): return self.title def get_absolute_url(self): return "/video/" + self.video_slug class Meta: verbose_name_plural = "Videos" ordering = ['-created_at'] get_latest_by = 'created_at' secondary model: class Category(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) category_slug = models.SlugField(max_length=100, unique=True) image = models.ImageField(upload_to='category', blank=True, null=True) description = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name def get_absolute_url(self): return "/category/" + self.category_slug class Meta: verbose_name_plural = "categories" ordering = ['name'] and view.py ... class VideoListView(ListAPIView): queryset = Video.objects.all() serializer_class = VideoSerializer When i send get request i got this [ { ... "category": "categories.Category.None", ... } ] What should i do? Please help me. -
Getting field from another model into my custom serializer
I am trying to get 'first_name' and 'last_name' field into my serializer that uses a model which has no user information: This is the serializers.py file: enter image description here This is the models.py file (from django-friendship model): enter image description here I am also attaching views.py: enter image description here -
Why is my else clause not working in Django?
I'm trying to create a search error for my ecommerce website. When a user inputs a search that is not in the database, it should return the search error page. Though it seems my else clause isn't working. I tried putting the else clause in the search.html page, but it keeps giving me errors and it seems when I try to fix the errors, nothing really happens, it stays the same. I expect the search_error.html page to appear when the user inputs a product name that is not in the database. Though I keep getting for example, when I type "hello," the page appears with "Search results for hello." But it should result the search_error.html page. I also tried currently a else clause in my views.py, but it shows the same thing. I think my else clause isn't working and I don't know why. My views.py: def search(request): if 'searched' in request.GET: searched = request.GET['searched'] products = Product.objects.filter(title__icontains=searched) return render(request, 'epharmacyweb/search.html', {'searched': searched, 'products': products}) else: return render(request, 'epharmacyweb/search_error.html') def search_error(request): return render(request, 'epharmacyweb/search_error.html') My urls.py under URLPatterns: path('search/', views.search, name='search'), path('search_error/', views.search_error, name='search_error'), My search.html page: {% if searched %} <div class="pb-3 h3">Search Results for {{ searched }}</div> <div … -
problem initialize django serializer with extra vars to be used in choice field
I have a django serializer like this # urls urlpatterns = [ path("cat", CatView.as_view(), name="cat") ] and # serializers class CatSerializer(serializers.Serializer): name = serializers.ChoiceField(choices=[]) def __init__(self, *args, **kwargs): self.names = kwargs.pop("names") self.fields["name"].choices = self.names super().__init__(self, *args, **kwargs) and views # views class CatView(APIView): def __init__(self, *arg, **kwargs): super().__init__(*arg, **kwargs) self.names = ['a', 'b', 'c'] def get_serializer(self, *args, **kwargs): serializer_class = CatSerializer return serializer_class( *args, **kwargs, names=self.names ) def post(self, request): request_body = request.body serializer = self.get_serializer( data=json.loads(request_body), ) is_data_valid = serializer.is_valid() if is_data_valid: serialized_data = serializer.data return Response({"message": "success", "serialized-data": serialized_data}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is a simplified version of my question. I am trying to dynamically initialize a serializer that has a choice field name and its choices are coming from kwargs passed to the serializer once initialized. if I call OPTIONS method on this class it returns { "name": "Cat", "description": "", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "name": { "type": "choice", "required": true, "read_only": false, "label": "Name", "choices": [ { "value": "a", "display_name": "a" }, { "value": "b", "display_name": "b" }, { "value": "c", "display_name": "c" } ] } } } } and if I make a … -
I want to change dict content when i clicked button django
Hey guys i have a problem i want to change dict data of python file from html button. I change change data just one time till now. Idk how can i change it when everytime i clicked the button. Django - When button is clicked I want to change the dictionary content Actually i want something like this problem That’s my html file <form action="change/" method="post"> {% csrf_token %} <input type="submit" name = "p1" value = "Program1"> <input type="submit" name = "p1" value = "Program1"><br><br> </form> And that’s the views.py from django.shortcuts import render def index(request): return render(request, "index.html") def change(request): if request.method == 'POST': p1 = request.POST["p1"] p2 = request.POST["p2"] dict = { 'p1': p1, 'p2': p2, } return render(request, 'change.html', dict) -
Lesson() got an unexpected keyword argument 'invoice_number'
I keep failing to save form data in order to pass them into the table to list in admin page. Since I'm fairly new to Django, I don't know what is wrong with my save method in form.py I have tried super().save(commit=False) but I'm not quite sure how to use it. As long as I understand it's used in order to manipulate the data before it's actually saved in the database. I'm not sure if that's the case for me though. Could someone explain why my error occurred and elaborate when to use super.save() and super.save(commit=False)? models.py class Lesson(models.Model): lesson_id = models.AutoField(primary_key=True) lesson_name = models.CharField(max_length=255) student = models.ForeignKey(User,on_delete=models.DO_NOTHING,related_name='studying') teacher = models.ForeignKey(User,on_delete=models.CASCADE, related_name='teaching') start_time = models.DateTimeField(default=timezone.now) interval = models.IntegerField() duration = models.IntegerField() created_at = models.DateTimeField(default=timezone.now, blank=True) updated_at = models.DateTimeField(default=timezone.now, blank=True) is_request = models.BooleanField() number = models.IntegerField(default=-1) price = models.IntegerField(default=-1, blank=True) invoice_number = models.CharField(max_length=10) @property def invoice_number(self): strStudentId = str(self.student_id) strLessonId = str(self.lesson_id) return strStudentId + "-" + strLessonId @property def price(self): return self.duration/5 * self.number forms.py class InvoiceForm(forms.Form): invoice_number = forms.CharField(label="Invoice Number") total_payable = forms.IntegerField(label="Total Payable") def save(self): """Create a new invoice request.""" lesson = Lesson.objects.create( invoice_number = self.cleaned_data.get('invoice_number'), price = self.cleaned_data.get('price'), is_request = False, ) return lesson views.py def invoice(request, … -
'dict' object has no attribute 'model' ISSUE
When I select a date range, I want it to show the number of hard drives saved in the database and the total size of these hard drives in the selected date range. FILTERS.PY class MateryalFiltrele(django_filters.FilterSet): baslangicTarihi = DateFilter(field_name="eklenmeTarihi", lookup_expr="gte", label='') bitisTarihi = DateFilter(field_name="eklenmeTarihi", lookup_expr="lte", label='') class Meta: model = MateryalEkle fields = ('cinsi','materyalBoyut') MODELS.PY class MateryalEkle(models.Model): MATERYALCINSI = [ ('USB', 'USB'), ('HDD', 'HDD'), ] cinsi = models.CharField(max_length=50, choices=MATERYALCINSI) materyalBoyut = models.IntegerField(max_length=5) eklenmeTarihi = DateField(auto_now_add=True) def __str__(self): return self.cinsi VIEWS.PY def istatistik(request): topla = MateryalEkle.objects.filter(cinsi='HDD').aggregate(tumhddtopla=Sum('materyalBoyut')) toplafiltre = MateryalFiltrele(request.GET, queryset=topla) return render(request, 'delil/istatistikler.html', {'toplafiltre':toplafiltre}) HTML <div> {{ toplafiltre.form.baslangicTarihi | as_crispy_field }} {{ toplafiltre.form.bitisTarihi | as_crispy_field }} <button type="submit" ></button> </div> <table class="table mt-5"> <thead> <tr> {% for tekil in hddToplaFiltre.qs %} <th class="ubold text-info ufo60" scope="col">{{tekil.tumhddtopla}}</th> {% endfor %} </tr> </thead> </table> enter image description here -
Django add element to dynamic form
Is there a way to add image element for each input in form? I need to have an image alongside each input from form. I created this sample form and model that works the same way as in my code. The result I'd like to get is this. Sample form code class CreateProfileForm(forms.ModelForm): fieldsets = [ ("Fieldset 1", {'fields': [ 'first_name', 'last_name' ]}), ("Fieldset 2", {'fields': [ 'address', 'phone' ]}), ] class Meta: model = Profile fields = '__all__' Sample model code class Profile(models.Model): # FIELDSET 1 first_name = models.CharField(max_length=50, verbose_name="First name") last_name = models.CharField(max_length=50, verbose_name="Last name") # FIELDSET 2 address = models.CharField(max_length=50, verbose_name="Address") last_name = models.EmailField(verbose_name="Email") The view def create_profile(request): form = CreateProfileForm() return render(request, 'form.html', {'form': form}) The template with the form {% load forms_fieldset static %} <div class="form data-form"> <form> {{ form|fieldset:'#000080' }} <div class="form-group"> <button name="upload" type="submit">Create</button> </div> </form> </div> -
username of the loggedin user is not showing in the profile page
I am doing a project using django where I have two apps. One is users app and another is blog app. Firstly, I used built-in django user model. But later I had to extend the built-in user model to add a new column. users/forms.py from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from blog.models import Category User = get_user_model() class UserRegisterForm(UserCreationForm): email = forms.EmailField() categories = Category.objects.all() cid = forms.ModelChoiceField(queryset=categories) class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'cid'] This is custom user model where I have added a new column cid which a foreign key in a category table. users/model.py from django.db import models from blog.models import Category from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): cid = models.ForeignKey(Category, on_delete=models.CASCADE) However, before implementing the custom user model, what I did that after successfully logging in, users will be able to see their profile page with their username. blog/profile.html {% extends 'users/base.html' %} {% block content %} <h1>{{ user.username }}</h1> {% endblock content %} but after creating the custom user model, when the users go to their profile page after logging in, the username is not displaying. How to solve …