Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to expand User(AbstractBaseUser) with OnetoOneField?
I want relate my Profile model with User model from class AbstractUserModel with OnetoOneFields. Is it possible? Or any solution with this problem. Here my models.py from django.db import models #from django.contrib.auth.models import User from django.contrib.auth.models import ( AbstractBaseUser ) class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active class Profile(models.Model): #HERE user = models.OneToOneField(AbstractBaseUser, on_delete=models.CASCADE) nama_lengkap = models.CharField(max_length=100, blank=True, null=True) tgl_lahir = models.DateField(null=True, blank=True) alamat = models.CharField(max_length=255) foto_profil = models.ImageField(upload_to='foto_profil',blank=True) jabatan = models.ForeignKey(Jabatan, on_delete=models.CASCADE) def __str__(self): return "{} - {}".format(self.user, self.nama_lengkap) when I migrate this, just show some errors message like this: SystemCheckError: System check identified some issues: ERRORS: users.Profile.user: (fields.E300) Field defines a relation with model 'AbstractBaseUser', which is either not installed, or is abstract. users.Profile.user: (fields.E307) The field users.Profile.user was declared with a lazy reference to 'auth.abstractbaseuser', but app 'auth' doesn't provide model 'abstractbaseuser'. thanks in advance -
Some of the fields doesn't show up in nested serializer
I have a nested serializer which I am using to create and update the model. The model is shown below: class Grade(models.Model): grade = models.CharField(max_length=255, primary_key=True) class Student(models.Model): class Meta: unique_together = ("rollno", "grade") name = models.CharField(max_length=255) grade = models.ForeignKey(Grade,related_name='StudentList', on_delete=models.CASCADE) rollno = models.BigIntegerField() And the corresponding serializer is: class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ("name", "grade", "rollno") read_only_fields = ('grade',) class GradeSerializer(serializers.ModelSerializer): StudentList = StudentSerializer(many = True) class Meta: model = Grade fields = ("grade", "StudentList") def create(self, validated_data): ''' Some function''' def update(self, instance, validated_data) ''' Some function''' My code works perfectly fine for both create and update but the message at front end is not as desired: This is how my payload looks like while creating/updating { "StudentList": [ { "name": "mw", "grade": "ten", "rollno": 32 }] } And that is how I exactly get it back when I update it but when I try to create with the same payload the field grade is missing! I get this: { "StudentList": [ { "name": "mw", "rollno": 32 }] } But I want to get the frontend to show me the same payload as input above. And if I remove the read_only_fields = ('grade',) from … -
How to customize default auth login form in Django?
How do you customize the default login form in Django? # demo_project/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('pages.urls')), path('users/', include('users.urls')), # new path('users/', include('django.contrib.auth.urls')), # new path('admin/', admin.site.urls), ] <!-- templates/registration/login.html --> <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> Above code works but I need to customize that {{form.as_p}} Where is that form or can it be override? Thanks for the help. -
Unable to delete Django session key
I am using Django 2.1.7 and I am trying to delete a session key from the Django sessions and I am not able to do so. I am trying to send data from one view to another, once the second view has seen the data, it should be able to delete the key. For example: Let's say I have a function that registers an account and adds the user name to a named session. This method works fine, because I can see a cookie with username-localhost-8889 def account_register(request): # ... create user and send a confirmation email with variable username request.session['username'] = username request.session.modified = True # not sure if I have to do this. # return render(...) ## Redirect to account_done Now, once the cookie is created the above view redirects to the below view. In this view, I read the session value (pop it), which should remove it, but that doesn't happen, when I refresh the page it still renders the page def account_done(request): template = 'accounts/account_registration_done.html' username = request.session.pop('username', None) # This doesn't actually remove the key request.session.modified = True # not sure if I have to do this. if username is not None and User.objects.filter(username=username).exists(): context … -
Why passing arguments to parent template makes the child template not be able to use them
im making a django project for school website I have a base.html that acts as parent template for the child templates which is the content of every page The base.html includes a navbar with the school logo and a section on it titled "Units" this is the code to render a lecturer page views.py . . def lecturer_home(request): user = request.user query for the user first name and full name query for the units that the user is teaching and their teaching period in unit_list and period_display class_display = zip(unit_list, period_display) user_dict = { 'f_name' : user.first_name, 'fl_name' : user.first_name + ' ' + user.last_name, 'class_display' : class_display, } return render(request, 'Lecturer/lecturerdashboard.html', user_dict) else: return HttpResponse('Unexpected error') lecturerdashboard.html extends the base.html I put less code for my views.py because I don't think I made any errors. What I want to confirm with you all is, the user_dict I passed in lecturerdashboard.html can also be used in the base.html, but confusingly I find that if a key and value is used in either one, the other one cannot use it. for example, I am able to display the units in the content section in the lecturerdashboard.html but when I used class_display … -
NoReverseMatch at /mypage/
I am creating a mypage which allows see and update user info. But it seems that mypage.html doesn't recieve user_detail and user_update, since the error message says 'NoReverseMatch at /mypage/ Reverse for 'user_detail' with arguments '(None,)' not found.' url path('mypage/', views.MypageView.as_view(), name='mypage'), path('user_detail/<int:pk>/', views.UserDetail.as_view(), name='user_detail'), path('user_update/<int:pk>/', views.UserUpdate.as_view(), name='user_update'), views.py class UserDetail(OnlyYouMixin, generic.DetailView): model = User template_name = 'perotta/user_detail.html' class UserUpdate(OnlyYouMixin, generic.UpdateView): model = User form_class = UserUpadateForm template_name = 'perotta/user_form.html' def get_success_url(self): return resolve_url('perotta:user_detail', pk=self.kwargs['pk']) class MypageView(generic.TemplateView): template_name = 'perotta/mypage.html' mypage.html {% extends "perotta/base.html" %} {% block content %} <ul class="list-group"> <li class="list-group-item"> <a href="{% url 'perotta:user_detail' user.pk %}">ユーザー情報閲覧</a> </li> <li class="list-group-item"> <a href="{% url 'perotta:user_update' user.pk %}">ユーザー情報更新</a> </li> <li class="list-group-item">Vestibulum at eros</li> </ul> {% endblock %} sorry, since the website is for the Japanese, it may contains Japanese words. I'm new to programing, so I would really appreciate how to solve this. -
How to create dynamic variable to create NULL filter in django db query
I am running db query after getting a value from a form in Django. There are many options in the form and hence I want to pass it as variable, but also want to filter null values. Passing to values is fine as it takes a string, but I am not able to pass the variable to null filter, unless I mention it. How to pass value to null filter as a variable? parameter = 'temperature' TempData.objects.all().values(parameter).filter(temperature__isnull=False) -
REST_framework Attrinbute
AttributeError at /api/scrumusers/ Got AttributeError when attempting to get a value for field scrumgoal_set on serializer ScrumUserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the ScrumUser instance. Original exception text was: 'ScrumUser' object has no attribute 'scrumgoal_set'. serializer.py from .models import * from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username','groups','password',] class ScrumGoalSerializer(serializers.ModelSerializer): class Meta: model = ScrumyGoals fields = ['goal_id','goal_name','goal_status'] class ScrumUserSerializer(serializers.ModelSerializer): scrumgoal_set = ScrumGoalSerializer(many=True) class Meta: model = ScrumUser fields = ['nickname', 'id','scrumgoal_set'] class ScrumProjectRoleSerializer(serializers.ModelSerializer): # user = ScrumUserSerializer() # scrumgoal_set = ScrumGoalSerializer(many=True) class Meta: model = ScrumProjectRole fields = ('role', 'user', 'id') -
serializing a field in the model with many to one relation
I have a post model and an image model as follows: class PropertyPost(models.Model): .... class Image(models.Model): prop_post = models.ForeignKey( PropertyPost, related_name='images4thisproperty', on_delete=models.CASCADE) and here is their associated serializes: class PropPostSerializer(serializers.HyperlinkedModelSerializer): images4thisproperty = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='image-detail') class Meta: model = PropertyPost fields = (...,images4thisproperty,...) class ImageSerializer(serializers.HyperlinkedModelSerializer): prop_post = serializers.SlugRelatedField(queryset=PropertyPost.objects.all(), slug_field='pk') class Meta: model = Image fields = ( 'url', 'photo', 'prop_post', ) now when I serialize my objects , the output json looks like this for propertypost model: { "images4thisproperty": [ "http://139.50.80.132/images/4", "http://139.50.80.132/images/3" ], } and looks like this for Image model: { "url": "http://139.50.80.132/images/1", "photo": "http://139.50.80.132/media/myposts/2019/20190327004444_8e3f5152-a3fd-40f2-857b-e16db3900fee.png", "prop_post": 1, }, { "url": "http://139.50.80.132/images/2", "photo": "http://139.50.80.132/media/myposts/2019/20190327004450_659c207a-f3e1-471e-b2b0-c33c4708494a.png", "prop_post": 1, }, I was wondering if I can have photo field of the Image model to be serialized in my propertypost too. in other words I would like to have this in my propertypost serializer output: { "images4thisproperty": [ "http://139.50.80.132/images/4", "http://139.50.80.132/images/3" ], "photo": [ "http://139.50.80.132/media/myposts/2019/20190327004444_8e3f5152-a3fd-40f2-857b-e16db3900fee.png", "http://139.50.80.132/media/myposts/2019/20190327004450_659c207a-f3e1-471e-b2b0-c33c4708494a.png", ] } Please let me know how can I do that, Thanks, -
Django can only concatenate str (not "list") to str
Django can only concatenate str (not "list") to str Error Messages....... I have some code like this: function form_submit() { var arr_category = new Array(); var arr_lawyer = new Array(); var data = new Object(); $('input[name^="category_idx"]').each(function() { arr_category.push($(this).val()); }); $('input[name^="lawyer_idx"]').each(function() { arr_lawyer.push($(this).val()); }); console.log("arr_category=="+arr_category); console.log("arr_lawyer=="+arr_lawyer); if (confirm('edit??') == true) { data.arr_category = arr_category; data.arr_lawyer = arr_lawyer; call_ajax('/admin/lawyer/recommend_add', data); //alert("arr_lawyer=="+arr_lawyer); } } Am I doing well in jquery? look at console.log arr_category==1,2,3,4,5,6,7,8,9 arr_lawyer==64,37,57,58,130,62,38,51,110 admin_view.py @csrf_exempt def recommend_add(request): print("TEST BANG VALUE------------") if request.is_ajax() and request.method == "POST": arr_category = request.GET.getlist('arr_category[]') print("arr_category------------" + arr_category) code = 0 msg = "TEST." data = json.dumps({ 'code': code, 'msg': msg, #'retURL': retURL }) return HttpResponse(data, content_type='application/json') I want to print. error message TypeError: can only concatenate str (not "list") to str How can I do that? -
Using iframe in Django, keep getting 'TemplateDoesNotExist'
I am using iFrame with Django 2.0.13. I keep getting TemplateDoesNotExist error, and I don't see what I'm missing. I've looked at other answers here on StackOverFlow and I seem to be doing everything. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], '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', ], }, }, ] urls.py from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView from NatureApp import views urlpatterns = [ path('', views.index, name="index"), path('NatureApp/', include('NatureApp.urls')), path('admin/', admin.site.urls), path(r'Map2.html', TemplateView.as_view(template_name="Map2.html"), name='Map2'), ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. # def index(request): # return HttpResponse("Hello World!") def index(request): my_dict = {'insert_me':"Hello I am from views.py!"} return render(request,'NatureApp/index.html',context=my_dict) Map2.html should being showing. I see index.html fine, but inside the iFrame I see the TemplateDoesNotExist message. I'm new to Django, I'm trying to include all code needed for troubleshooting. -
Create the Django app or the virtual environment first?
I have been trying to successfully create projects using Django however I have seen projects where the user will create the project first THEN the virtual env. I have also seen instances where the user creates the virtual env and THEN the django app. Both sides argue that their method is better, but now I am confused. Pls help -
form.upload.errors doesnt show error, the field just empties itself
When a user submits my form i've added field.errors on all possible fields. Every single field can render the error if there's any, except the file upload file. I have a custom validator that checks if it ends with .zip, and if it doesnt then raise error. This error isn't shown when submitting another filetype. The upload field just resets and shows nothing. Models.py upload = models.FileField(upload_to=user_directory_path, validators=[validate_file_extension]) def validate_file_extension(value): if not value.name.endswith('.zip'): raise ValidationError('Only zip files are allowed!') Template.html <div class="file-field input-field"> <div class="btn"> <span>File</span> {{form.upload}} {{form.upload.errors}} </div> </div> -
error in sending an image blob javascript to django. csrf token missing or incorrect
The users in my django website have a profile image that is cropped by the user. after the cropping i need to send the cropped image to the server which is converted to blob then sent via ajax. my problem is that it has a 403 (Forbidden) on the browser, while the terminal says Forbidden (CSRF token missing or incorrect.) i have tried many solutions and i keep getting different errors each time. I don’t know much about Django since i am a front-end developer, i hope you would explain it in an easy way for me to understand. any help is greatly appreciated and thanks in advance. iEdit.saveBtn.on("click", function(){ // cropping imgData = pCtx.getImageData(0, 0, 150, 100); iEdit.callback(iEdit.processCan.toDataURL("image/"+iEdit.imageType, iEdit.imageQuality)); iEdit.close(); var image = $("#file-upload"); var data = imgData; var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); var formData=""; formData = new FormData(); blob, function (iEdit) { canvasToBlob( data, function (data) { expect(data.type).to.equal('image/jpeg'); formData.append('image', data); formData.append('csrfmiddlewaretoken', '{% csrf_token %}'); done(); }, 'image/jpeg' ) }, { data: true }; console.log("data: "+formData);//it always prints undefined console.log("data: "+data);// the output is [object FormData] $.ajax({ url: $(image).attr("data-url"), // same url 'action' in form "csrfmiddlewaretoken" : $(image).siblings("input[name='csrfmiddlewaretoken']" ).val(), type: 'POST', data: { "profile_image":data}, dataType: "json", headers:{"HTTP_X_CSRF_TOKEN":csrftoken}, mimeType:"multipart/form-data", cache: false, … -
Trying to make a captcha field for forms
I'm trying to create a custom captcha field for a form, and it seems to be working alright except for the fact that when the code is supposed to pick a random captcha to return to the end-user for them to solve, it returns a ValueError: too many values to unpack (expected 2). I think this is because the list isn't being randomised and python is selecting the entire list to use as the user's captcha. How can I fix this issue? class CaptchaField(IntegerField): widget = CaptchaInput error_msgs = { 'incorrect': _('Captcha incorrect- try again'), } def __init__(self): captcha_array = ( ('What is the product of fifteen and four?', 60), ('What is four plus four?', 8), ('What is nine times one?', 9), ('How many letters are in the word orange?', 6), ('What is the sum of ten and two?', 12), ('What is the difference of eighty-four and nineteen?', 65), ('How many letters are in the word forest?', 6), ('How many letter are in the word apple?', 5), ('If there are four palm trees and one dies, how many are alive?', 3), ('What is four divided by two?', 2), ('How many letters are in the name of the capital of France?', … -
Built-in template filter for prepending a string to a template in Django?
I want to prepend a string to a template. I know you can use the |add filter to append a string to the end. That's not what I'm trying to do though. I want the string before my template. For example if my template is {{ index.salary }} how would I add a $ to the beginning? I know you can make your own filter. I was just curious if they have something built-in for this. -
django makemessages - CommandError: errors happened while running msguniq - syntax error
I'm using django 1.10.5 with python 3.6.5 on a Windows 7 OS. I have a test app that has existing translation strings. The makemessages command worked in the past. However, in the last week I have received the following error when I've attempted to run the django-admin makemessages command: (myappenv36) C:\Users\me\desktop\myapp\myapp [master ≡ +0 ~13 -0 !]> dja ngo-admin makemessages CommandError: errors happened while running msguniq C:\Users\me\desktop\myapp\myapp\locale\django.pot:1783:3: syntax error C:\Users\me\desktop\myapp\myapp\locale\django.pot:1783: keyword "core" un known C:\Users\me\desktop\myapp\myapp\locale\django.pot:1783: keyword "models" unknown C:\Users\me\desktop\myapp\myapp\locale\django.pot:1783: keyword "py" unkn own C:\Users\me\desktop\myapp\myapp\locale\django.pot:1783: keyword "core" un known C:\Users\me\desktop\myapp\myapp\locale\django.pot:1783: keyword "models" unknown C:\Users\me\desktop\myapp\myapp\locale\django.pot:1783: keyword "py" unkn own C:\Users\me\desktop\myapp\myapp\locale\django.pot:1785: keyword "core" un known C:\Users\me\desktop\myapp\myapp\locale\django.pot:1785: keyword "models" unknown C:\Users\me\desktop\myapp\myapp\locale\django.pot:1785: keyword "py" unkn own C:\Users\me\desktop\myapp\myapp\locale\django.pot:4543:3: syntax error C:\Users\me\desktop\myapp\myapp\locale\django.pot:4543: keyword "template s" unknown C:\Users\me\desktop\myapp\myapp\locale\django.pot:4543: keyword "base" un known C:\Users\me\desktop\myapp\myapp\locale\django.pot:4543: keyword "resume_m enu" unknown C:\Users\me\desktop\myapp\myapp\locale\django.pot:4543: keyword "html" un known C:\Users\me\desktop\myapp\myapp\locale\django.pot:4545: keyword "template s" unknown C:\Users\me\desktop\myapp\myapp\locale\django.pot:4545: keyword "header" unknown C:\Users\me\desktop\myapp\myapp\locale\django.pot:4545: keyword "header" unknown C:\Users\me\desktop\myapp\myapp\locale\django.pot:4545: keyword "html" un known C:\Users\me\desktop\myapp\myapp\locale\django.pot:4548: keyword "template s" unknown msguniq: too many errors, aborting I have thoroughly searched Google and SO for an answer to this issue, but I have come up blank. These are the attempts I have made to fix the issue: 1. Followed the django 1.10 docs and re-installed … -
developing a django cms
first of all i'd like to apologize if my problem seems to broad to answer but i'm really getting frustrated over this. so i'm a wordpress developer mainly (used to be a front end developer) and i'm getting into python django. but after taking many courses i can't seem to understand how to do the content management aspect of my project. so here is a rundown of my problem in wordpress there is this concept of custom post meta where you can put fields that can change the heading of pages and fully customize the website so that the client won't need me every time he needs to change anything (CMS basically) now i can't even begin to imagine how to go about doing something like that for django i've tried putting a custom form on top of my list view in the admin page but that doesn't look so good and what if i need to customize a page that doesn't belong to a module with a list view i've tried to make an app and call it page but then what about the stuff that is directly related to a module. so my question is: how should i … -
Django thousand separator in ModelForms input fields
How I can add thousand separators for number input fields in a ModelForm. I am using 'load humanize' and '|intcomma' in templates to format some numbers.but How I could do that for fields in modelforms. -
Django: Filter on Annotated Value
I have a situation where I have a model called trip. Each trip has a departure_airport and an arrival_airport which are related fields and both part of the airport model. Each object in the airport model has a location represented by latitude and longitude fields. I need to be able to take inputs from two (potentially) separate departure and arrival airport locations using something like the Haversine formula. That formula would calculate the distance from each departure/arrival airport in the database to the location of the airports that have been taken as input. The difficult part of this query is that I annotate the trip queryset with the locations of the departure and arrival airports, however because there's two sets of latitude/longitude fields (one for each airport) with the same name and you can't use annotated fields in a sql where clause, I'm not able to use both sets of airports in a query. I believe the solution is to use a subquery on the annotated fields so that query executes before the where clause, however I've been unable to determine if this is possible for this query. The other option is to write raw_sql. Here's what I have so … -
Django “python-social-auth”: HTTP 403 Client Error with github
I've followed closely this tutorial which is great. Everything worked fine until today, where when I log with github I get this error: HTTPError at /oauth/complete/github/ 403 Client Error: Forbidden for url: https://github.com/login/oauth/access_token What am I missing / what could I have changed? -
Alternative to Apache and Nginx for hosting Django Application?
I am on a windows server. I am having so many compatibility issues with installing apache/mod_wsgi. Version mismatches. And, since, nginx is not suitable for windows. I am looking for a simple alternative to implement SSL on a Django Application. Thanks. -
Add timestamp and username to log
I have setup Logging inside my settings.py, and I want to know if it's possible to add to the error log line - Which user experienced the error and a timestamp for the issue. Is this possible? Current code LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } -
Altering primary key of Django models with many-to-many relationships
I have two models, Image and Dataset that are connected through a many-to-many relationship: class Image(models.Model): id = models.CharField(max_length=255, primary_key=True) datasets = models.ManyToManyField(Dataset, blank=True) class Dataset(models.Model): ... I wanted to use a sequential integer as id instead of the VARCHAR. So I renamed the id field to id_old, which made Django create an integer auto-field as an id column with the following migrations like I wanted, to which I added to delete the id_old field. operations = [ migrations.RenameField( model_name='image', old_name='id', new_name='id_old', ), migrations.RemoveField( model_name='image', name='id_old', ), migrations.AddField( model_name='image', name='id', field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), ), But the problem is that now the through table in Postgres backend has the image_id column with type VARCHAR, hence I get the following error if I want to add a dataset to an image: operator does not exist: character varying = integer LINE 1: ...tasets" WHERE ("app_image_datasets"."image_id" = 12764 AN... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Since the image_id field didn't get altered during these operations, I also lose the relationships between datasets and images. So how can I alter a primary key field in a model with M2M relationships? -
How to query only the fields of the logged in user?
So I use a model which is linked to my custom user (AbstractUser) in Django. I want to loop over all the objects of the current logged in user that belong to him. So these are the models: class CustomUser(AbstractUser): # Define all the fields company = models.CharField(blank=True, null=True, max_length=150, unique=True) email = models.EmailField(blank=True, null=True) username = models.CharField(blank=True, null=True, max_length=150) first_name = models.CharField(blank=True, null=True, max_length=150) last_name = models.CharField(blank=True, null=True, max_length=150) phone_number = models.CharField(max_length=15, blank=True, null=True) kvk_number = models.IntegerField(blank=True, null=True) vat_number = models.CharField(blank=True, null=True, max_length=150) customer_type = models.CharField(max_length=1, choices=CUSTOMER_CHOICES, null=True, blank=True) # Choices are defined before the model # Username is required here otherwise createsuperuser will throw a error. We define the usernamefield here as the email REQUIRED_FIELDS = ['username', 'email'] USERNAME_FIELD = 'company' def __str__(self): return self.company class UserLinks(models.Model): # Define all the fields user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=2, choices=LINK_CHOICES, null=True, blank=True) link = models.URLField(blank=True, null=True) login_name = models.CharField(blank=True, null=True, max_length=150) password = models.CharField(blank=True, null=True, max_length=150) def __str__(self): return self.name class Meta: verbose_name = "User link" verbose_name_plural = "User links" And this is my view: def get(self, request): user = CustomUser.objects.all() return render(request, self.template_name ,{'user': user}) Then when I want to loop through the objects through …