Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integrate django rest auth with django allauth
I am trying to integrate django rest auth with django allauth. I installed them both as their documentation says and I have issue with configuring the routes. This is what I made in my urls file: urlpatterns = [ re_path(r'^auth/', include('rest_auth.urls')), re_path(r'^auth/signup/', include('rest_auth.registration.urls')), ... ] The registration works fine, but on my confirmation email that I receive there is a link. Clicking on that link gives 500 status code with the following exception: TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()' What did I do wrong? how should I configure django rest auth and django allauth? Is there any tutorial that provide step by step instructions (I am new to django)? -
ValueError: Missing staticfiles while deploying Django app to Heroku with Whitenoise
I've followed several tutorials on how to deploy a Django app with static files- however, I'm having no luck getting this working! Settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' django_heroku.settings(locals()) del DATABASES['default']['OPTIONS']['sslmode'] Example template file: {% load static from staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css"> Error: ValueError: Missing staticfiles manifest entry for 'vendor/fontawesome-free/css/all.min.css' Thanks so much! -
Django simple annotation across two models
I've got three models, User, Achievement, and UserAchievement: class User(AbstractUser): email = models.EmailField(_('email address'), unique=True) ... class Achievement(models.Model): name = models.CharField(max_length=64) points = models.PositiveIntegerField(default=1) class UserAchievement(models.Model): # Use a lazy reference to avoid circular import issues user = models.ForeignKey('users.User', on_delete=models.CASCADE) achievement = models.ForeignKey(Achievement, on_delete=models.CASCADE) I'd like to annotate Users with a 'points' column that sums up the total points they've earned for all their achievements as listed in the UserAchievement table. But clearly I'm not fully up to speed with how annotations work. When I try: users = User.objects.annotate(points=Sum('userachievement__achievement__points')) for u in users: print(u.email, u.points) It crashes with: Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/dylan/.local/share/virtualenvs/server-E23dvZwD/lib/python3.7/site-packages/django/db/models/query.py", line 274, in __iter__ self._fetch_all() File "/Users/dylan/.local/share/virtualenvs/server-E23dvZwD/lib/python3.7/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/Users/dylan/.local/share/virtualenvs/server-E23dvZwD/lib/python3.7/site-packages/django/db/models/query.py", line 78, in __iter__ setattr(obj, attr_name, row[col_pos]) AttributeError: can't set attribute -
Django database objects not showing on the template
Am i am rendering django objects using django_tables and the for loop iteration but both methods aren't working i am trying to render objects saved in the database by a modelform. My first approach i used the django_tables2 which returned non-type object. currently i have used the for loop to iterate through the objects but the object values are not being displayed. what intrigues me is that all rows are being returned with no data. kindly help. models.py keynumber=models.CharField(max_length=10); workorder=models.CharField(max_length=50); contrator=models.CharField(max_length=50); contrator_contact=models.IntegerField(); assigned_name=models.CharField(max_length=50); assigned_ID=models.IntegerField(); assigned_contact=models.IntegerField(); date_to_return=models.DateField(); class Meta: managed=False db_table='ieng_mis_issuekeys'``` views.py ```def issuetable(request): query_set=zip(Issuekeys.objects.all()) context={'query_set': query_set} return render(request, 'keymanager.html',context)``` url.py ```url(r'^keymanager$', views.issuetable,name='keymanager'),``` keymanager.html ```<div class="bg-light" style="margin-top: 1em; margin-left: 1mm"> <table class="table table-hover"> <tbody> <tr> <th scope="col">Key Number</th> <th scope="col">Work Order</th> <th scope="col">Contractor</th> <th scope="col">Assignee Name</th> <th scope="col">Assignee Contact</th> <th scope="col">Date issued</th> </tr> {% for key in query_set %} <tr> <td>{{key.keynumber}}</td> <td>{{key.workorder}}</td> <td>{{key.contractor}}</td> <td>{{key.assigned_name}}</td> <td>{{key.assigned_contract}}</td> <td>{{key.date_to_return}}</td> </tr> {% endfor %} </tbody> </table> </div>``` output -
Is it possible for Models to know which tenant is using it?
I'm offering a SaaS, mostly as a django dashboard and customized admin panel. Using tenants I have one schema per customer sharing a database. The problem I have is that the customer should be able to create objects through the admin page and the objects should create an url with information about the tenant. For example customer Y's url would be Y.xzxzxz.com and customer X's url would be X.xzxzxz.com. There will be multiple types of urls with the same prefix. Currently I the customers have to manually input the customer prefix. Is it possible for the Models class to know which schema is using it? -
Pillow installed, but getting “no module named pillow”
i can't import PIL even when i installed it ? -
Django using __init__ method in classes extending (admin.ModelAdmin)
I am fairly new to Django. I have an admin.Models extended class that's pretty typical (has list_display, search_fields, etc). It looks something like this: class FooAdmin(admin.ModelAdmin): list_display = ( 'all', 'my', 'things', ) ... admin.site.register(Foo, FooAdmin) My problem is that this ModelAdmin loads somethings from a model with something like foo_list = Foo.objects.filter(group__name='something'). Because this is a heavy task, I'd like to do it once on initialization, and then use the same thing over and over again when specifying custom "_field" functions. My thoughts are to do this in the __init__ method of this class, but when implement my own constructor, it doesn't register with Django as a url; i.e. class FooAdmin(admin.ModelAdmin): def __init__(self, *args, **kwargs): super(Foo, self).__init__(*args, **kwargs) list_display = ( 'all', 'my', 'things', ) ... # This register portion removed. # admin.site.register(Foo, FooAdmin) The above will "build" correctly and run, but attempting to visit the site says the URL is not found (not surprising since I removed the register part). However, when I add the register portion back in, I get a message about a misuse of my constructor, i.e adding back the admin.site.register and running python manage.py runserver ... results in something like: TypeError: super(type, obj): obj … -
Django/uWSGI site not loading static assets when accessed from URL, loads fine when accessed from IP address
When going to http://159.89.34.173 the site loads fine. However, when going to http://cometthon.org the site either doesn't load entirely, or doesn't load static resources (such as images, JS, and CSS). I'm running on a Digital Ocean server, spawning uwsgi with the following command: uwsgi --http :80 --home ~/comet_env/ --chdir ~/CometTHON/ -w CometTHON.wsgi -p 5 -M *I know this isn't best practice, but I'm just trying to get this thing up and running Here's my domain configuration: I've watched the uWSGI logs, when trying to connect from the URL-side I don't see any activity in the logs. My allowed_hosts is set to all, so I know that's not the problem. -
unable to display Image in a Django Template (using ImageField)
i'm uploading an image from the admin site into the imagefield of the model.i've made the necessary changes in the settings.py and urls.py file and added the media directory in my project. Although the image shows up in the admin site, i get "The 'image' attribute has no file associated with it" error while rendering the template. here are my files: template(users.html) <!DOCTYPE html> {% load static %} <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href=""> </head> <body> <h1>Here are your users</h1> {% if user_list %} <ol> {% for user in user_list %} <li> User Info</li> <ul> <li>First Name:{{user.f_name}}</li> <li>Last Name:{{user.l_name}}</li> <li>Email:{{user.email}}</li> <li>Image:<img src="{{ user.image.url }}"></li> </ul> {% endfor %} </ol> {% endif %} </body> </html> models.py from django.db import models # Create your models here. class User(models.Model): f_name=models.CharField(max_length=20) l_name=models.CharField(max_length=20) email=models.EmailField() image=models.ImageField(upload_to='pictures',null=True,blank=True) def __str__(self): return (self.f_name+" "+self.l_name) views.py from django.shortcuts import render from django.http import HttpResponse from .models import User # Create your views here. def index(request): return HttpResponse("<em>My Second Project</em>") def help(request): helpdict = {'help_insert':'HELP PAGE'} return render(request,'appTwo/help.html',context=helpdict) def dispUsers(request): user=User.objects.order_by('f_name') user_dict={"user_list":user} return render(request,'appTwo/users.html',context=user_dict) settings.py """ Django settings for ProTwo project. Generated by 'django-admin startproject' using Django 2.0.5. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list … -
Django pagination does not match input Query
I have a bit of code that looks something like this. page_objects = Page.objects.exclude(lorem).filter(blah).annotate(key=bar).order_by(foo) paginator = Paginator(page_objects, 50) On my UI, I notice that with certain values of bar, I am missing rows in the output. I ran an experiment to compare the output of paginator against that of the query. page_results = [] for page_number in paginator.page_range: result = paginator.page(page_number) page_results += result.object_list paginator_ids = sorted([x.id for x in page_results]) page_object_ids = sorted(x.id for x in list(page_objects)) print(paginator_ids == page_object_ids) => FALSE print(len(paginator_ids) == len(page_object_ids)) => TRUE As you can see, the list of objects in the query and the list of all objects in the paginator did not match. I visually inspected the lists to confirm that this is correct (the ids in the two lists are clearly different). I am on Django==1.11.3 What is going on and why is my paginator not behaving like the docs? Interestingly, if I change the order_by to order_by(foo, 'id'), the paginator behaves as expected. -
Exception Value: no such table: vacancy_list_advuser
I added user class for registration AdvUser When I want to login or register, or createsuperuser I receive error: Exception Value: no such table: vacancy_list_advuser File "/home/alex/dev/python/django/junjob/myvenv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 305, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: vacancy_list_advuser What I did Checked AUTH_USER_MODEL = 'vacancy_list.AdvUser' # <app_name.model_name> Removed all migrations in vacancy_list/migrations then did makemigrations and migrate python manage.py migrate --run-syncdb What should I do to solve problem? My code: models.py from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractUser from django.db import models from django.dispatch import Signal from .utilities import send_activation_notification class Company(models.Model): name = models.CharField(max_length=200) about = models.TextField() def __str__(self): return self.name class Vacancy(models.Model): company_key = models.ForeignKey(Company, on_delete=models.CASCADE) title = models.CharField(max_length=200) salary = models.CharField(max_length=200, default='40.000') text = models.TextField(default="The text about vacancy") city = models.CharField(max_length=200, default='Москва') date_str = models.CharField(max_length=50, default='12 сентября') created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class AdvUser(AbstractUser): """ Model of user for registration """ is_activated = models.BooleanField(default=True, db_index=True, verbose_name='Прошёл активацию?') send_messages = models.BooleanField(default=True, verbose_name='Слать оповещёния о новых комментариях?') class Meta(AbstractUser.Meta): pass user_registrated = Signal(providing_args=['instance']) def user_registrated_dispatcher(sender, **kwargs): send_activation_notification(kwargs['instance']) user_registrated.connect(user_registrated_dispatcher) urls.py urlpatterns = [ path('', HomePageView.as_view(), name='vacancy_list'), path('search/', … -
How to encapsulate specific file parsing Django REST framework
I would like to create parsers for several types of files when I uploading them. After parsing i want to create model for each uploaded file. I create a function that takes xyz file and parse it to dict. I create an APIView, which handle request and applicate my function: I need more convenient and flexible code where each class has single responsibility. I think I need DRM serializers and parsers. But how I can connect them? views.py class parseXYZfile(generics.CreateAPIView): # serializer_class = parseXYZFileSerializer # parser_classes = [XYZFileParser] def post(self, request): files_data_list = request.FILES.getlist("files") d = {} for data in files_data_list: path = default_storage.save('tmp/tmp_file.xyz', ContentFile(data.read())) tmp_file = os.path.join(settings.MEDIA_ROOT, path) d[str(data)] = parseXYZ(tmp_file) os.remove(tmp_file) return Response(d) -
How to access Django Model Fields from save_formset
I have an Inline Model in Django model admin , and I need to create a condition before saving the items, here is the code am using : class PRCItemInline(admin.TabularInline): def get_form(self, request, obj=None, **kwargs): form = super(PRCItemInline, self).get_form(request, obj, **kwargs) form.base_fields['product'].widget.attrs['style'] = 'width: 50px;' return form ordering = ['id'] model = PRCItem extra = 1 autocomplete_fields = [ 'product', 'supplier', ] fields = ( 'product', # 1 'quantity', # 2 'unitary_value_reais_updated', # 4 'issuing_status', 'approval_status', 'receiving_status', ) readonly_fields = ['issuing_status', 'approval_status', 'receiving_status', ] def save_formset(self, request, form, formset, change): obj = form.instance if obj.purchase_request.is_analizer: return HttpResponse("You can't change this") else: obj.save() As you see, I used the save_formset method to be able to reach the fields of the model, and then filter based on it. but it just saves the items no matter the If statement I added. -
How to calculate number of remaining monthly recurring dates between now and a date in the future in Django with Postgres
I have a Django application with Django Rest Framework that is storing records in Postgres. A Vehicle model has an end_date DateField that represents the final payment date of a finance agreement, and a monthly_payment FloatField that represents the payment amount. The finance payment is made monthly, on the same day of the month as the final payment (e.g. if end_date is 25/01/2020, a payment is made on the 25th of every month between now and 25/01/2020 inclusive.) I have a ListVehicle ListCreateAPIView that returns a paginated list of vehicle records. I am using a custom PageNumberPagination class to return a data object alongside the results array that is populated by aggregating some of the fields in the Vehicle model. I want to include a field in this data object that contains the total remaining amount left to pay on all of the Vehicle entities in the database. I have tried using @property fields in the model that calculate the total remaining amount for each Vehicle, but you can't aggregate over calculated properties (at least not with queryset.aggregate), so the following solution did not work: @property def remaining_balance(self): return max(self.remaining_monthly_payments * self.monthly_payment, 0) @property def remaining_monthly_payments(self): now = datetime.datetime.now() end … -
"GET /static/my_style.css HTTP/1.1" 404 1660
Im getting this error "GET /static/my_style.css HTTP/1.1" 404 1660 in my terminal whenever I update my page I build. I think it's my code in my settings.py that is wrong and with the static files also. Tried different thing but still not working My static code right now STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles') ] This type of error [06/Nov/2019 19:54:58] "GET /static/my_style.css HTTP/1.1" 404 1660 -
ValueError: invalid literal for int() with base 10: '<view class>'
I try to update value in database but it show ValueError at /edit_account/edit_account invalid literal for int() with base 10: 'edit_account' Why it send to 'localhost:8000/edit_account/edit_account'. It should 'localhost:8000/useraccount' when I save the value. views.py def edit_account(request, id): user = User.objects.get(id=id) user = { 'user':user, } if request.method == 'POST': user.first_name = request.POST['first_name'] user.last_name = request.POST['last_name'] user.save(user.last_name, user.first_name) return redirect('useraccount') else: return render(request, 'polls/edit_account.html', user) urls.py path('edit_account/<id>', views.edit_account, name='edit_account'), templates <form action="edit_account" method="POST"> {% csrf_token %} <div class="form-group"> <label for="username1">Username: {{user.username}}</label><br> <label for="first_name">First name</label> <input type="text" class="form-control" name="first_name" value="{{user.first_name}}"> <label for="last_name">Last name</label> <input type="text" class="form-control" name="last_name" value="{{user.last_name}}"> </div> <div class="form-group"> <button type="Submit" class="btn btn-success">Save</button> </div> </form> -
Django - multiple inline forms validate 1 formset using another formset data
I have a main Model: MainModel -> MainModelForm that's used in a view I also have 2 inline forms that have the MainModel as primary key InlineModel1 => InlineModel1Form (formset = CustomOperatorFormset(BaseInlineFormset)) which has it's own set of validations. It is a 1 or none setup, I.e. it's not required, but once it's added, it has some validations in place. Using the CustomSetup from BaseInlineFormSet is working great. However, I have another model - InlineModel2 which is not required - until the user has entered atleast 1 row in InLineModel1Form. I'm losing hair over how to send/validate this, i.e using InlineModel1form data and check if there are any rows added, in InlineModel2Form Form. I need both set of inline forms setup separately, so a mixin showing everything in 1 place wouldn't work for me. -
Django Tutorial - error message doesn't display
I am working my way through the Django tutorial. Currently at Part 4, where if you vote without selecting a choice, the page should reload with an error message displayed above the poll. However, when I do so, the page reloads, but no error message is being displayed. The development server is not showing any errors, btw. Here is the template code: <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} <input type="submit" value="Vote"> </form> And here is a snippet of the view.py function for the vote: def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', {'question': question}, {'error_message' : "You didn't select a choice."}) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question_id,))) Any help as to why the error message is not showing? -
How can someone make Axios autorefresh data and store it in the backend using Django?
I have an instance of Axios running in my Vue.js environment while my web application itself is based on Django. I fetch data from a third party API which provides foreign exchange rates that are updated every 60 seconds. I now would like to accomplish the following: 1.) Make Axios auto-refresh the data every 60 seconds 2.) Re-render the DOM with the new rates (I use V-For) 3.) Save the newly fetched data somewhere in my backend 4.) Use the stored the data for any http requests from users of my web application (so that I only need one API call per minute rather than one for each visitor of my website). For the auto-refresh part i tried to use this threads input: How to auto refresh a computed property at axios in vuejs but couldn't make it. Since the other questions probably stretch the topic too wide, I would be very grateful if you could guide me with some keywords for further study to maybe make it happen by myself. Thank you very much in advance! Vue.config.devtools = true; var app = new Vue({ delimiters: ['[[', ']]'], el: '.eurQuotesWrapper', data() { return { rates: [], }; }, computed: { … -
column res_company.write_uid_id does not exist
while trying to make a link btween Django and Odoo, I used python manage.py inspectdb > sc_drive/models.py, but while trying to acces the table using django admin page i get the error below: column res_company.write_uid_id does not exist column res_company.create_uid_id does not exist models.py class ResCompany(models.Model): name = models.CharField(unique=True, max_length=1) # partner = models.ForeignKey('ResPartner', models.DO_NOTHING) create_date = models.DateTimeField(blank=True, null=True) write_uid = models.ForeignKey('ResUsers', models.DO_NOTHING, related_name='user_b_write_uid', blank=True, null=True) account_no = models.CharField(max_length=1, blank=True, null=True) email = models.CharField(max_length=1, blank=True, null=True) create_uid = models.ForeignKey('ResUsers', models.DO_NOTHING, related_name='user_b_create_uid', blank=True, null=True) phone = models.CharField(max_length=1, blank=True, null=True) write_date = models.DateTimeField(blank=True, null=True) company_registry = models.CharField(max_length=1, blank=True, null=True) Ps: I have already migrate after modifying related_name=... on models.py -
How to assign foreign key related field while creating model objects
I have model League one of its field country_code relate as foreign key to another model Country class League(models.Model): league = models.IntegerField(primary_key=True) league_name = models.CharField(max_length=200) country_code = models.ForeignKey("Country",null=True, on_delete=models.SET_NULL) class Country(models.Model): country = models.CharField(max_length=60) code = models.CharField(max_length=15,null=True) flag = models.URLField(null=True) lastModified = models.DateTimeField(auto_now =True) When i am trying to create League object data_json = leagues_json["api"]["leagues"] for item in data_json: league_id = item["league_id"] league_name = item["name"] country = item["country"] b = League.objects.create(league = league_id,league_name = league_name,country_code = country) I get en error ValueError: Cannot assign "'World'": "League.country_code" must be a "Country" instance. Like i understand error occurs because while i am creating object i didn't assign to country_code field proper Country object. Help with guidance how to do it -
How to fix "500 Internal Server Error in Django"
I deployed Django with elastic beanstalk. And that site show me this error. Which part should I check?? enter image description here enter image description here https://github.com/yunseongk/project93 -
Prevent django admin changes from creating a LogEntry
I want to use the Django admin so I include django.contrib.admin in my middleware, but by default this adds a django_log_entry table and triggers the creation of a log entry on all additions, changes, and deletions. How do I prevent this behavior? Should I overwrite the LogEntry model or can I simply unregister it? I can't seem to find any documentation. I'm using Django 2.1 -
Django REST Framework Model Serializer is not showing all fields for POST method?
I'm trying to make custom create()method to save my user profile when a User is created, the serializer works perfect for the GET method, but for POST it only shows one field instead of all fields. I specified the fields = '__all__' property, but still don't work GET: JSON Response: [ { "job_title": { "id": 1, "name": "Desarrollador" }, "birthdate": "2019-11-06", "roles": [ { "id": 1, "name": "Administrador", "description": "Administrador del sistema", "key": "ADMIN" } ] } ] POST: Expected JSON: [ { "birthdate": "2019-11-06", } ] Serializers: class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = '__all__' depth = 1 class UserSerializer(serializers.ModelSerializer): user_profile = UserProfileSerializer(read_only=False, many=False) class Meta: model = User fields = '__all__' depth = 1 def create(self, validated_data): profile_data = validated_data.pop('user_profile') user = User.objects.create(**validated_data) UserProfile.objects.create(user=user, **profile_data) return user views.py class UserDetail(generics.RetrieveUpdateDestroyAPIView): profile = serializers.PrimaryKeyRelatedField(many=False, queryset=UserProfile.objects.all()) queryset = User.objects.all() serializer_class = UserSerializer class UserProfileList(generics.ListCreateAPIView): queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer models.py class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user_profile', on_delete=models.CASCADE) birthdate = models.DateField(default=datetime.date.today) job_title = models.ForeignKey(JobTitle, related_name='job_title', on_delete=models.CASCADE) roles = models.ManyToManyField(Role) def createProfile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.created(user=kwargs['instance']) post_save.connect(createProfile, sender=User) def __str__(self): return self.user.username I need that POST method also requires the full JSON, the same as the GET … -
How to join two tables (multi row) in Django
I want to join 2 tables from 2 tables, such as 'auth_user' and 'polls_account'. How I can join them? models.py class Account(models.Model): usid = models.ForeignKey(User, on_delete=models.PROTECT) ROLE = ( ('01', 'Owner-Manager'), ('02', 'Staff'), ) role = models.CharField(max_length=2, choices=ROLE, blank=True, null=True) views.py def useraccount(request): user_list = User.objects.all() userlist = { 'user_list': user_list, return render(request, 'polls/useraccount.html', userlist) } I need to show table according this | username | firstname | lastname | role | ---------------------------------------------- | a | Mike | Hanze | Staff | And, should I change 'usid' to 'OneToOneField'?