Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django web project - connected with https. Forbidden (403) CSRF verification failed
There was no problem when connecting to the http server. If you log in from the web server after connecting to https, the following error works: In login.html {% csrf_token %} is written Forbidden (403) CSRF verification failed. Request aborted. More information is available with DEBUG=True. Is there any way to enable this when DEBUG= False? -
How to render filtered data using django and ajax
I'm very much new to AJAX and JQuery. So, my problem is: I want to show a filtered list of a django model called "Recipe" when a user clicks on a checkbox but I don't know how to pass in the data in ajax so that it reloads it correctly for example: I have a Recipes List in my home page which displays all the recipes and right next to it is a filter sidebar where a user can check multiple checkboxes in multiple categories to filter the data according to the input. But I don't know how to pass the data in the views so that ajax loads it into the page. Any help would be appreciated! Here's my code: views.py # filter recipes def filter_recipes(request): print(request) recipes = Recipe.objects.all() diff = request.GET.getlist("difficulty[]") if len(diff) > 0: filtered = recipes.filter(difficulty__in=diff) print(f"recipes =============== {filtered}" ) ajax = render_to_string("ajax/recipes_list.html", {"data": filtered}) return JsonResponse({"data": ajax}) <!-- JQuery script in landing_page.html--> <script> $(document).ready(function () { $(".ajax-loader").hide(); // start of filter by value $(".form-check-input").on("click", function () { let _filterObj = {}; $(".form-check-input").each(function (index, element) { let _filterValue = $(this).val(); let _filterKey = $(this).data("filter"); _filterObj[_filterKey] = Array.from( document.querySelectorAll( "input[data-filter=" + _filterKey + "]:checked" ) ).map(function … -
Unexpected behavior with Django migrations when trying to leverage MSSQL schemas
I currently maintain a Django project that uses a Postgres database and follows the principles in this article to leverage multiple schemas. This keeps all the tables nice and namespaced. I have a 'core' app, where I have defined a base model that has a couple foreign keys to my custom 'Auth' model. These fields are '_created_by' and '_last_updated_by'. Every model in every other app inherits from this model, and as a result every table in every schema has a foreign key relationship with my custom 'Auth' model. When using Postgres, I can migrate my custom 'Auth' app, and it creates all the necessary tables in the default 'public' schema. And then I can do: python manage.py migrate app --database=app_db for my other apps, and the relevant tables get created in the correct schema. (I have created the schemas beforehand, django does not do that for you) This is perfect. However recently it has become apparent that my life would be easier were we to use MSSQL for the backend. After some work, everything almost works, however when I migrate an app using the above command, it creates duplicate 'Auth' tables in the app schema. So now I have a … -
Hi everyone I'm struggling with a for loop in attempt to make a categories filter (Django - Bootstrap)
Like the title say's I have a problem trying to make a categories filter, already did one for my Blog because only has a couple of categories without subcategories, but this one is different because it has categories and subcategories with one to many fields and already tried multiples approaches but I couldn't make it work. I would be glad if someone lend me a hand. This one was my last attempt, I tried to make it like my other less complex categories filter. Store unique html template. <section class="page-section cta rounded p-6 p-md-5 m-md-4 text-center bg-light"> <div class="container"> <div class="row"> <div class="col-xl-9 text-center mx-auto"> <h2 class="section-heading mb-4"> <span class="section-heading-lower">Horizontal</span> </h2> <div style="padding-bottom: 1%; padding-top: 3%;"> <h4><span class="section-heading-upper">CATEGORIAS: </span></h4> {% for itemWide in itemsWide %} {% for category in itemWide.categories.all %} <a type="button" class="btn btn-dark" href="{% url 'storePacks' %}"> <span class="section-heading-upper" style="font-size:small;">{{category.name}}</span> </a> {% endfor %} {% endfor %} </div> </div> </div> </div> </section> Store model class ItemCategory(models.Model): name = models.CharField(max_length=50) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now_add=True) class Meta: verbose_name = 'itemCategory' verbose_name_plural = 'itemsCategories' def __str__(self): return self.name class SubCategoryVert(models.Model): parentCategory = models.ForeignKey(ItemCategory, on_delete=models.CASCADE) name = models.CharField(max_length=50) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now_add=True) class Meta: verbose_name = 'SubCategoryVert' verbose_name_plural … -
How to restore deleted files from a GitHub account
I accidentally deleted the code from my GitHub account using Github Interface and wanted to recover it through.Is there anyway I can run commands directly through my github account and not through github console? -
AttributeError: 'str' object has no attribute '_meta' Migrating django 4.1
Whenever I try to use the migrate command on django, this error pops up for the migration file in app "fonte". The model inside uses a ManyToMany field with the through argument on the model "FonteVariavel", which then connects to "Variavel". Applying fonte.0001_initial...Traceback (most recent call last): File "/APP/manage.py", line 22, in <module> main() File "/APP/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/.venv/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "/.venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self._migrate_all_forwards( File "/.venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "/.venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "/.venv/lib/python3.9/site-packages/django/db/migrations/migration.py", line 130, in apply operation.database_forwards( File "/.venv/lib/python3.9/site-packages/django/db/migrations/operations/models.py", line 96, in database_forwards schema_editor.create_model(model) File "/.venv/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 453, in create_model if field.remote_field.through._meta.auto_created: AttributeError: 'str' object has no attribute '_meta' Here is the relevant code from django.db.models import DateField, ManyToManyField, Model, TextField from core.fonte_variavel.models import FonteVariavelModel from core.variavel.models import VariavelModel from .managers import FonteManager from .querysets import FonteQuerySet class FonteModel(Model): nome … -
Send user's email to developers email django
Lets say i have an email when a user logs in . Could there a way to recieve an email that {user's email} has logged in and for log outs too. I have tried to do reaserch on this but didnt know how to start as i am a new to making websites -
Having an error 'AttributeError at /register/ '
Full of error : AttributeError at /register/ 'DataEbotUser' object has no attribute 'session' I abstracted the User and created a DataEbotUser as models then created a form which takes this as a model. But when I try to add user with using this form Im taking such an error. And there is also one more problem. When I try to add user with Django Administraion having an KeyError 'first_name' (if I delete the init function in forms it becomes normal). I need a proper register form which works properly. I cant understands the problems clearly. (I created the models in different app and imported) class DataEbotUser(AbstractUser): phone=models.CharField(max_length=20) LastClientLogin = models.DateTimeField(null=True , blank = True) LastServerLogin = models.DateTimeField(null=True , blank=True) AllowServerLogin = models.BooleanField(default=False) LoginType = models.IntegerField(null=True , blank=True) class DataLoginType(models.Model): user = models.ForeignKey(DataEbotUser, null=True , on_delete=models.CASCADE) name = models.CharField(max_length=200) detail = models.CharField(max_length=200) isActive = models.BooleanField(default=False) def __str__(self): return self.name class CustomUserCreationForm(UserCreationForm): class Meta: model = DataEbotUser fields = ['username','first_name','last_name','email','phone','password1','password2'] def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter username...'}) self.fields['first_name'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter First Name...'}) self.fields['last_name'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter Last Name ...'}) self.fields['email'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter Email...'}) self.fields['phone'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter Phone...'}) self.fields['password1'].widget.attrs.update( {'class': … -
Django - adding gamification features
I have a medium size Django REST app that I'm looking to add gamification features to. The application in question is a school webapp where students can create mockup quizzes, participate in exams that teachers publish, and write didactical content that gets voted by other students and teachers. I want to add some gamification features to make the app more interesting and to incentivize participation and usage of the various features: for example, each student will have a personal "reputation" score, and gain points upon completing certain actions--a student may gain points when completing a quiz with a high score, when submitting some content, or when receiving upvotes to such content. The tricky part is I want to be able to have this logic be as separate as possible from the existing codebase, for various reasons: separation of concerns, ability to plug the engine in/out if needed, ability to easily deactivate features for certain groups of users, etc. What I'm looking for here is some software engineering advice that's also Django-specific. Here's a high level description of what I'm thinking of doing--I'd like some advice on the approach. create a new gamification app. Here I will have models that describe … -
Django formset error for ID "Select a valid choice. That choice is not one of the available choices"
I am posting a formset in Django. The form on the client side is generated dynamically using a file uploaded by the user. I render it like this: <form method="post" id="add3"> {{ formset.management_form }} {% csrf_token %} <table id="forms"> <tbody> {% for lst in result %} <input type="hidden" name="form-{{ forloop.counter0 }}-id" value="{{ forloop.counter }}" id="id_form-{{ forloop.counter0 }}-id"> <tr> <td> <input type="hidden" name="form-{{ forloop.counter0 }}-expense" id="id_form-{{ forloop.counter0 }}-expense" value="{{lst.0}}"/> </td> <td> <input type="hidden" name="form-{{ forloop.counter0 }}-amount" id="id_form-{{ forloop.counter0 }}-amount" value="{{lst.1}}"/> </td> {% endfor %} </tbody> </table> </form> I get the following error on the server side when I receive the formset. Formset is_valid returns False and I get the error: id: Select a valid choice. That choice is not one of the available choices How can I fix this? What's the right way to pass an ID? Note: I am updating management_form total-forms using Javascript. If that matters. -
Django NoReverseMatch after deleting object
Im hard stuck here, everything is connected via pk, and on group of accounts can see only their data whiel an other group can see all data from the other group. But I have a model where ONLY the staff group can add update and delete while the other group can only update. While it works fine and all when the staff group deletes all 'teachers' in that case I get no reverse match error. The thing is, In the view the staff needs to see everything compact in their template like the school and teacher and so on. right now I either have atleast two type of teacher and the template works or the school is sorted normaly while the teachers are all shown under every school template hope you get what I mean. I only need something that dont break if a FK is deleted so that if staff makes a new teacher everything works template <ul> <li>{{Ansicht.Lehrer_FK.Leitung_der_Klasse}}</li> <a href="{% url 'LehrerAktualisierenVerwaltung' Ansicht.Lehrer_FK.pk %}" >Lehrer Aktualisieren</a> <a href="{% url 'LehrerEntfernenVerwaltung' Ansicht.Lehrer_FK.pk %}" >Lehrer L&ouml;schen</a> </ul> form class LehrerAktualisierenVerwaltung(LoginRequiredMixin, UpdateView): model = LehrerTabelle fields = '__all__' template_name = 'SCHUK/LehrerAktualisierenVerwaltung.html' context_object_name = 'LehrerAktualisierenVerwaltung' def get_success_url(self): return reverse('Dashboard') url path('LehrerAktualisierenVerwaltung/<int:pk>/', LehrerAktualisierenVerwaltung.as_view(success_url="Dashboard"), … -
How to build Django external URLs with differing protocols
I am soliciting and parsing user content for all types of URLs (starting with http|https|ftp as well as only www.xxx.xxx), e.g. http://www.foo.bar and www.google.com and https://guardian.co.uk. At a later stage I am presenting these URLs back in a template and want to create links that go straight to those destinations: <a href="//{{resource.text}}" target="_blank" role="button">{{resource.text}}</a> However, if I don't prefix with // I get relative URLs (which obviously isn't working), but if I do add the prefix and create absolute URLs, I'm up the creek as the protocols differ between the various URLs. Is there a way to tell Django to treat the URLs naively and let the browser sort out the context? -
How to set relation between Product Sales and Product Costs Tables in Django
probably basic question but I need help how to set up relations between my models. I have the first model SalesData, where I import from csv sales data of products for particular periods - so this table can contain a product multiple times with different dates, quantities and sales: class SalesData(models.Model): date = models.DateField("Date", null=True, blank=True) product = models.CharField("Product", max_length=150, null=True, blank=True) sales = models.DecimalField("Sales", max_digits=10, decimal_places=2, null=True, blank=True) quantity = models.IntegerField("Quantity", null=True, blank=True) I have the second model ProductCosts, where I have the product and its production costs. And one product can have only one specific production costs. class ProductCosts(models.Model): product = models.CharField("Product", max_length=150) costs = models.DecimalField("Costs", max_digits=10, decimal_places=2) And I need help with: how to connect these two tables to be able to get production costs for particular product to each row in SalesData table, so I will be able to calculate profit, margin etc. for particular rows? what to do, to be able to create form, where I can fill production costs for rows, where are these costs missing for new sales data inputed to table? And if it is possible to have the form as a table with products with missing costs in the first column … -
I want to collect visitors information on a website im building
I want to be able to get my web visitors email only when the signup and get notified when the logout. How should i go about this -
Django: How can I use inlineformset to save multiple forms that all share the same FK as another object being created on the same form page?
I have two models Animal and Gene_Animal_Bridge. I have a form page that allows a user to add a new animal to the database and attach any genes that they have. The genes are stored in Gene_Animal_Bridge which contains the FK of the animal it belongs to, and the FK of the Gene that is stored in the GeneInfo Model. Everything works fine but when it comes to iterating over the formset, only 1 gene will be saved and any other gene forms added on the page won't save. Models.py from django.db import models import datetime class Animal(models.Model): animal_id = models.AutoField(primary_key=True, editable=False, null=False) gender = models.CharField(max_length=6, choices=(('m','male'), ('f','female')), null=True) name = models.CharField(max_length=14) description = models.CharField(max_length=75,blank=True, null=False) dob = models.DateField(default=datetime.date.today, blank=True, null=True) purchase_date = models.DateField(default=datetime.date.today, blank=True, null=True) image = models.ImageField(blank=True, null=True) prey_type = models.CharField(max_length=20,choices=(('1','2XL Multi'),('2','Large Weaner'),('3','Live Multi'),('4','Small Rat'),('5','Small Weaner')),blank=True, null=True) last_feed = models.DateField(default=datetime.date.today, blank=True, null=True) last_shed = models.DateField(default=datetime.date.today, blank=True, null=True) weight = models.IntegerField(blank=True, null=True) class GeneInfo(models.Model): gene_id = models.AutoField(primary_key=True, editable=False, null=False) gene_name = models.CharField(max_length=20, null=False) type = models.CharField(max_length=20,choices=(('1','pos het'),('2','het'),('3','visual'),('4','co-dominant'),('5','super'),('6','dominant')),null=False) def __str__(self): return (self.gene_name) class Gene_Animal_Bridge(models.Model): animal_id = models.ForeignKey(Animal, on_delete=models.CASCADE, related_name="bridge_animal_id", null=True) gene_id = models.ForeignKey(GeneInfo, on_delete=models.CASCADE, related_name="bridge_gene_id", null=True) class Breeding(models.Model): sire_id = models.ForeignKey(Animal, on_delete=models.CASCADE, related_name="breeding_sire_id", null=True) dame_id = models.ForeignKey(Animal, on_delete=models.CASCADE, related_name="breeding_dame_id", null=True) … -
How to use form.as_table and crispy forms together?
I want to use form.as_table and crispy forms together, but it is generating an error as shown in the screenshot below :- Here is my code :- <form action="{% url 'create' %}" method="post"> {% csrf_token %} <table> {{form.as_table|crispy}}<br> </table> <input class="btn btn-outline-primary" type="submit" value="Create" id="create"> </form> -
Django: Get count of specific values by month in queryset
my model is like so: class Project(models.Model): name = models.CharField(max_length=1000, null=True, blank=True) date_created = models.DateTimeField(auto_now=True) status = models.CharField(max_length=1000, null=True, blank=True) The status field has about 5 different options (won, lost, open, pending, cancelled). I need to know how to get the number of projects with x status in each month in a given time range query. I was able to get the sum total of projects each month with the following annotation: Project.objects.all().annotate(month=TruncMonth('date_created')).values( 'month').annotate(total=Count('pk'), ).order_by('date_created') However, I am looking for an output like this: [{date: 'January 2020', total: 30, won: 10, lost:10, open: 10, pending: 0, cancelled: 0}, {date: 'February 2020', total: 30, won: 10, lost:10, open: 10, pending: 0, cancelled: 0}, {date: 'March 2020', total: 30, won: 10, lost:10, open: 10, pending: 0, cancelled: 0}] Ideally I would like the keys within the final output to be dynamic (i.e. if a new status is added, we won't need to hardcode a new key into the query) but I don't know if this is possible or not. Thanks for your time! -
How to add a custom button beside the list display in django admin panel? To edit the form from list display it self
Here is my admin.py code: `from django.contrib import admin from .models import * from django.utils import * import csv from django.http import HttpResponse class ProductAdmin(admin.ModelAdmin): search_fields = ('name',) list_display = ('name','price',) admin.site.register(Product,ProductAdmin)` [I have attached my admin panel screenshot][1] -
Django CheckConstraint not enforcing check on model field
I am using Django 3.2. Backend database used for testing: sqlite3 I have a model Foo: class Foo(models.Model): # some fields ... some_count = models.IntegerField() class Meta: models.constraints = [ models.CheckConstraint( check = ~models.Q(some_count=0), name = 'check_some_count', ), ] I also have a unit test like this: def test_Foo_some_count_field_zero_value(self): # Wrap up the db error in a transaction, so it doesn't get percolated up the stack with transaction.atomic(): with self.assertRaises(IntegrityError) as context: baker.make(Foo, some_count=0) When my unit tests are run, it fails at the test above, with the error message: baker.make(Foo, some_count=0) AssertionError: IntegrityError not raised I then changed the CheckConstraint attribute above to: class Meta: models.constraints = [ models.CheckConstraint( check = models.Q(some_count__lt=0) | models.Q(some_count__gt=0), name = 'check_some_count', ), ] The test still failed, with the same error message. I then tried this to check if constraints were being enforced at all: def test_Foo_some_count_field_zero_value(self): foo = baker.make(Foo, some_count=0) self.assertEqual(foo.some_count, 0) To my utter dismay, the test passed - clearly showing that the constraint check was being ignored. I've done a quick lookup online to see if this is a known issue with sqlite3, but I haven't picked up anything on my radar yet - so why is the constraint check … -
Django: Setting IntegerField after form submit
How do i increase the "availability" IntergerField after the form is submitted? Each new product_type is created in the admin panel since i'll only ever need a few of them. Each new product is created through a form. views.py def new_product(request): if request.method != 'POST': # No data submitted, create blank form form = ProductForm() else: # POST data submitted, process the data form = ProductForm(data=request.POST) if form.is_valid(): product = form.save(commit=False) product.owner = request.user #product.product_type.availability += 1 # This didn't work #product.product_type.add_product() # And this didn't work product.save() return redirect('store') context = {'form': form} return render(request, 'store/new_product.html', context) models.py class ProductType(models.Model): availability = models.IntegerField(default=0) ## How to increase this on the fly? price = models.DecimalField(max_digits=7, decimal_places=2, default=6.99) product_type = models.CharField(max_length=200, default="Tier1") cores = models.IntegerField(default=1) ram = models.IntegerField(default=2) disk = models.IntegerField(default=10) def __str__(self): return self.product_type def add_product(self): self.availability = self.availability + 1 print(self.availability) forms.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['host_name', 'host_password', 'product_type'] -
How to assign function to button in Django
I am designing a website based on django. I want to update the user information and delete the user if wanted in the same page. I created updating and it works properly. But when I address the delete user function to same html file , the button that I want it to delete user also updates just like the other button. I need both buttons to work for their own purposes. I thought that without changing anything assigning delete function to button might help thats why I wrote the title like that. Thank you! <div class="login--wrapper"> <form method="POST" class="form"> {% csrf_token %} <div class="center"> <h1>Kullanıcı Ayarları</h1> {% csrf_token %} {% for field in form %} <div class="mb-3"> <label for="exampleInputPassword1" class="from-label">{{field.label}}</label> {{field}} </div> {% endfor %} <button type="submit" class="btn btn-primary">Update Info</button> <button type="submit" class="btn btn-primary">Delete User </button> </div> def DeleteUser(request,pk): user=DataEbotUser.objects.get(id=pk) if request.method=='POST': user.delete() context={'user':user} return render(request,'home/DeleteUser.html',context) def users(request,pk): user=DataEbotUser.objects.get(id=pk) form=EditUserForm(instance=user) if request.method=='POST': form=EditUserForm(request.POST, instance=user) if form.is_valid(): form.save() context={'form':form , 'users':users} return render(request,'home/UsersPage.html',context) -
How to get cookie values when it's coming different subdomains?
I have a cookie value set in wordpress site and I would need to read this value when the page redirects to the app which is a django backend. How do I retrieve this value in the app? So this value should persist from www.example.com to app.example.com -
Django is_staff: when User registered he is staff but not have any Permissions i want when he register he will get all Permissions by default
hare i do the save what i need to add for he will get all Permissions by default myuser = User.objects.create_user(username, email, pass1,is_staff=True) myuser.first_name = fname myuser.last_name = lname myuser.is_active = False myuser.save() -
Django ImageField Form upload works in admin but not in actual user form
I am trying to upload an image within a form that has an animal type, description, and the image file. This should save to image in an "images" file within my project and this works fine when adding a model object from the admin page but when trying to use the actual form on my site, only the animal type and description gets saved to the admin page. model code: class Post(models.Model): BISON = 'Bison' WOLF = 'Wolf' ELK = 'Elk' BLACKBEAR = 'Black Bear' GRIZZLY = 'Grizzly Bear' MOOSE = 'Moose' MOUNTAINLION = 'Mountain Lion' COYOTE = 'Coyote' PRONGHORN = 'Pronghorn' BIGHORNSHEEP = 'Bighorn Sheep' BALDEAGLE = 'Bald Eagle' BOBCAT = 'Bobcat' REDFOX = 'Red Fox' TRUMPETERSWAN = 'Trumpeter Swan' YELLOWBELLIEDMARMOT = 'Yellow-bellied Marmot' RIVEROTTER = 'River Otter' LYNX = 'Lynx' SHREW = 'Shrew' PIKA = 'Pika' SQUIRREL = 'Squirrel' MULEDEER = 'Mule Deer' SANDHILLCRANE = 'Sandhill Crane' FLYINGSQUIRREL = 'Flying Squirrel' UINTAGROUNDSQUIRREL = 'Uinta Ground Squirrel' MONTANEVOLE = 'Montane Vole' EASTERNMEADOWVOLE = 'Eastern Meadow Vole' BUSHYTAILEDWOODRAT = 'Bushy-tailed Woodrat' CHIPMUNK = 'Chipmunk' UINTACHIPMUNK = 'Uinta Chipmunk' WHITETAILEDJACKRABBIT = 'White-tailed Jackrabbit' BEAVER = 'Beaver' AMERICANMARTEN = 'American Marten' MOUNTAINCHICKADEE = 'Mountain Chickadee' BOREALCHORUSFROG = 'Boreal Chorus Frog' CUTTHROATTROUT = … -
Django Rest: How to use user_get_model() in different apps created in a project?
As I'm creating one project which contain one core app and rest apps for different purpose and in core app models.py I've created Custom User model and I' using "from django.contrib.auth import get_user_model" for accessing current user but as I'm using this in other app apart from core app it is giving me error:'function' object has no attribute 'objects'. recipe myapp - core app recipe - project user - user app myapp/models.py- custom user model is created I want to access get_user_model() in user/views.py so that I can list users on the basis of admin or non admin users.