Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
How to invoke table-valued function defined in django
I have created table-valued function instead of stored procedure on database for fetching data on certain condition. How will I invoke that function in django? - 
        
Multiple choice of instances of another model
I have a Car model where one of the properties is horsepower. I also have a Horsepower model. I want my car model to choose from a list of Horsepower instances. class Horsepower(models.Model): title = models.CharField(max_length=255) ... class Car(models.Model): ... horsepower = models.ManyToManyField(Horsepower) I don't want to use ManytoManyField because there should only be one selection. - 
        
How to add related table column in sql to_tsvector?
I am working on a django API in which I need to implement a search-as-you-type feature. At first I wanted to use Django SearchVector and SearchQuery but they seem to perform poorly when query terms are incomplete (which is not ideal for the "as-you-type" part) so I went for the SQL approach. I need to be able to search on first_name and last_name of a contact as well as on the email of the user related to that contact. I used the following to create a search_vector on contact and to add an index on this column. This works great to search on first and last name. ALTER TABLE contact_contact ADD COLUMN search_vector tsvector; UPDATE contact_contact SET search_vector = to_tsvector('english', coalesce(first_name, '') || ' ' || coalesce(last_name, '')); CREATE INDEX mc_idx2 ON contact_contact USING GIN (search_vector); I would like to add the user email to this search_vector, something like: ... SET search_vector = to_tsvector('english', coalesce(first_name, '') || ' ' || coalesce(last_name, '') || coalesce(user.email::text, ''); ... I cannnot figure out the correct syntax or process to do that. Any help is greatly appreciated! - 
        
When i create usercreationform in django the username field is auto selected and how can i fix it
Greeting, I am new in django. Username is auto selected when i reload the page why is this and how can i fix it. - 
        
update_or_create django admin imports
I have an app contains these models class Transaction(models.Model): chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = .. income_period = .. property_market_rent =.. number_of_family_group = .. cruser = .. prop_id = .. state = .. group =.. class FamilyGroup(models.Model): name = models.CharField(.. transaction =models.ForeignKey(Transaction,.. ... class FamilyMember(models.Model): transaction = models.ForeignKey(Transaction, .. family_group = models.ForeignKey(FamilyGroup.. name = models.CharField.. date_of_birth = models.DateField.. .... Im trying to make Imports app that will accept xlsx files with some certain format. after i imported the models from the other apps, therefore i've created a model that have a field for each field i n the above models , i removed a lot so it look readable. im trying to make it update_or_create since i think its the best approach to do, since maybe in future maybe i want to update some fields. I have created the first update_or_create for Transaction but since family_group and family_member are childs of Transaction and Inlines i cant figure out how to apply this. the main idea is i have a transaction contains family_groups and family_members inside it . class Batch(models.Model): batch = models.CharField(max_length=50) transaction_chp_reference = models.CharField(unique=True) transaction_rent_effective_date = models.DateField(.. transaction_property_market_rent = models.DecimalField(.. transaction_number_of_family_group = models.PositiveSmallIntegerField(.. family_group_name = models.CharField(.. family_group_family_type = models.CharField(.. … - 
        
How to set default values in Forms
I am Building a BlogApp and i am stuck on a Problem. What i am trying to do :- I am trying to set the Default Value in forms.py for a Form. views.py def new_topic(request,user_id): profiles = get_object_or_404(Profile,user_id=user_id) if request.method != 'POST': form = TopicForm() else: form = TopicForm(data=request.POST) new_topic = form.save(commit=False) new_topic.owner = profile new_topic.save() return redirect('mains:topics',user_id=user_id) #Display a blank or invalid form. context = {'form':form} return render(request, 'mains/new_topic.html', context) forms.py class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['topic_no','topic_title'] What have i tried :- I also did by using initial , BUT this didn't work for me. form = DairyForm(request.POST,request.FILES,initial={'topic_title': 'Hello World'}) The Problem Default value is not showing when i open form in browser. I don't know what to do Any help would be appreciated. Thank You in Advance - 
        
Django Duplicate Values in ChoiceField
I am new to Django and am having issues with the forms.py. I am pulling values from a database via Models.Py and then using those objects as a dropdown list on my Django page. For example, I have Car Data stored in a database: Honda | Accord | Black | 2016 Toyota | Camry | Red | 2014 Ford | Fusion | White | 2018 Honda | Civic | Silver | 2020 Toyota | Corolla | Black | 2010 And so on. In models.py, I have: class MyCars(models.Model): make_name = models.CharField(max_length=50, blank=True, null=True) model_name = models.CharField(max_length=50, blank=True, null=True) color = models.CharField(max_length=15, blank=True, null=True) year = models.CharField(max_length=15, blank=True, null=True) def __str__(self): all_cars = [] return self.make_name class Meta: managed = False db_table = 'my_cars' Then in my form.py I do something along the line of: all_cars = forms.ModelChoiceField(queryset=MyCars.objects.all()) The problem is I will then have duplicate values for Honda, Toyota etc, when I only need Honda to appear once on the dropdown. Any suggestions/ideas to filter through this? - 
        
Is there a mutlinomial function that allows for floats?
I have been searching around for functions similar to numpy function multinomial For my current use case it was working, although in an update I require to allow for floating points such as 1.5 etc. I am working with data to display on a table over 24 hours (00:00-23:00), which is 24 entries. I have a block called "time period" which is pulled from a database. Example of how this looks now and performs now: v = int(period.volume_for_period) n = int(round((float(period.period_time)*1))) x = [1/n]*n volume = multinomial(v, x) volume_ls = [x/3600 for x in volume] Assuming period.period_time is inside of a loop to loop over database entries. There is 6 entries with period_time as follows 8, 8, 3, 1.5, 2, 1.5 Sample data for volume_for_period would look like 5330880.0, 3902400.0, 1171800.0, 971460.0, 1332720.0, 971460.0 The output is giving me samples to show on a graph. I am thinking of a multinomial function that allows for a floating point to give for example 1.5 of a result instead of rounding up to 2 as I need 24 results not 25. Is it possible or would there be a better way? I would appreciate any help if anyone is willing to even … - 
        
No Reverse Match when using Slugify
Model field: url_slug = models.SlugField(default='', max_length=200, null=False) Model methods: def get_absolute_url(self): new_kwargs = { 'pk': self.pk, 'url_slug': self.url_slug } return reverse('post-detail', kwargs=new_kwargs) def save(self, *args, **kwargs): value = self.title self.url_slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) urls.py: path('blogs/<str:url_slug>-<int:pk>/', BlogDetailView.as_view(), name='post-detail'), template url: "{% url 'post-detail' blog.url_slug|slugify blog.pk %}" Error: Reverse for 'post-detail' with arguments '(56,)' not found. 1 pattern(s) tried: ['blogs\\/(?P<url_slug>[^/]+)\\-(?P<pk>[0-9]+)\\/$'] Can't figure out what the issue is here? Edit: It may be worth noting that I created the slugify method after several model objects were already created, however I went back and added url_slug fields for all of them. - 
        
mail chimp subscription not working with django
Hi everyone I integrate my Django Web app with mail chimp . in my admin panel when I open marketing preference it give me error . and it do not subscribe my users when I click on subscribe my user remain unsubscribe when i hit save .the error I got is {'type': 'https://mailchimp.com/developer/marketing/docs/errors/', 'title': 'Invalid Resource', 'status': 400, 'detail': "The resource submitted could not be validated. For field-specific details, see the 'errors' array.", 'instance': '2b647b4f-6e58-439f-8c91-31a3223600a9', 'errors': [{'field': 'email_address', 'message': 'This value should not be blank.'}]} my models.py file is: class MarketingPreference(models.Model): user =models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) subscribed =models.BooleanField(default=True) mailchimp_subscribed = models.NullBooleanField(blank=True) mailchimp_msg =models.TextField(null=True , blank=True) timestamp =models.DateTimeField(auto_now_add=True) updated =models.DateTimeField(auto_now=True) def __str__(self): return self.user.email def marketing_pref_create_reciever(sender, instance, created, *args, **kwargs): if created: status_code, response_data = Mailchimp().subscribe(instance.user.email) print(status_code, response_data) post_save.connect(marketing_pref_create_reciever, sender=MarketingPreference) def marketing_pref_update_reciever(sender, instance, *args, **kwargs): if instance.subscribed != instance.mailchimp_subscribed: if instance.subscribed: #subscribing user status_code, response_data = Mailchimp().subscribe(instance.user.email) else: #unsubscribing user status_code, response_data = Mailchimp().unsubscribe(instance.user.email) if response_data['status'] =='subscribed': instance.subscribed = True instance.mailchimp_subscribed = True instance.mailchimp_msg = response_data else: instance.subscribed = False instance.mailchimp_subscribed = False instance.mailchimp_msg = response_data pre_save.connect(marketing_pref_update_reciever, sender=MarketingPreference) def make_marketing_pref_reciever(sender, instance, created, *args, **kwargs): if created: MarketingPreference.objects.get_or_create(user=instance) post_save.connect(make_marketing_pref_reciever , sender=settings.AUTH_USER_MODEL) my utils.py is: MAILCHIMP_API_KEY = getattr(settings, "MAILCHIMP_API_KEY" , None) MAILCHIMP_DATA_CENTER = getattr(settings, "MAILCHIMP_DATA_CENTER" … - 
        
How to use Django form elements in jQuery
I have a django app that allows users to add other users in a table via a front end. Is there anyway to use django {{form_fields}} in JQuery? The code below just prints '{{ form.users }}' as text instead of the form, which contains a list of users. var row = '<tr>' + '<td><div class="form-group ">{{ form.users }}</div></td>' + '<td>' + actions + '</td>' + '</tr>'; $("table").append(row); Thanks, - 
        
Anonmyous web chat help Roadmap
I am trying to create a web chat app in which a just has to enter his/her name and join the chat room. But the problem is I don't know how to approach/start this self-learning project. I would like to use the Python Django framework since I know the basics of i I am not an experienced developer. I read a lot of blogs and I came to know for the successful delivery of data I have to use Socket programming in it. Can anyone please tell me the steps/technologies/roadmap which I need to learn in order to give this idea a reality. It's fine if you can't help me in detail but giving just a small idea, tech stack, etc will be a great help. Thank you for giving your valuable towards my request. - 
        
Passing static image paths to templates dinamcally as statements in DJANGO
I am new to Django and still struggling to grasp static files and media files. IF i want have images that are stored in models with mode.FilePathField on my website that are static then how should i call them properly in my templates: using static tag Like that:{% static project.image.path %} or that just by calling it: {{ project.image.path }} When reading tutorial i got answers that the first one but then it doesn't work. It gives me wrong paths i will get 'static/MyApp/static/Myapp/img.jpg' instead of MyApp/static/Myapp/img.jpg I would be really glad for an example of static files called dinamacally. - 
        
How to link two forms (wagtail form and django form) with a foreign key?
I'm using a django form in conjunction with a wagtail form. The django form will record some fields that will be on any form of this type: name, email and the wagtail form will record extra data defined by the form page creator specific to that instance. I've overloaded the serve method to capture both sets of data and I can process both forms, but I'm stuck when trying to add the logic to relate the form contents to each other so that when one submission set is deleted, the other set will be as well. I think what I need is a foreign key. The following code fails at form_submission.event_submission = a.id where I'd like to take the id from the wagtail form submission and add that as a foreign key to the django form, so that when the wagtail form portion is deleted, the other is deleted as well, and so that I can have a usable link between the two form submissions. def serve(self, request, *args, **kwargs): if request.method == 'POST': form = EventSignupForm(request.POST) wagtail_form = self.get_form(request.POST, request.FILES, page=self, user=request.user) if form.is_valid() and wagtail_form.is_valid(): a = self.process_form_submission(wagtail_form) form_submission = form.save(commit=False) form_submission.event_submission = a.id form_submission.save() return self.render_landing_page(request, form_submission, … - 
        
Unable to fetch parameters from Django URL
I am a beginner in Django REST Framework and I want to fetch the two parameters entered in the URL. My URL is: http://127.0.0.1:8000/api/v1/colleges/slug2/courses/sug1/ where 'slug2' and 'sug1' are the two slug parameters entered. I want to retrieve those two parameters in my ModelViewSet views.py class CollegeCourseViewSet(viewsets.ReadOnlyModelViewSet): queryset = Course.objects.all() lookup_field = 'slug' def get_serializer(self, *args, **kwargs): if self.action == 'retrieve': slug1 = self.kwargs.get('slug1') slug2 = self.kwargs.get('slug2') print(slug2) queryset = Course.objects.filter(slug=slug2) return Response(CollegeCourseSerializer(queryset, many=True).data, status=status.HTTP_200_OK) urls.py router = routers.DefaultRouter() router.register(r'courses', CollegeCourseViewSet, basename='college_course_list') urlpatterns = [ path('api/v1/colleges/<slug:slug>/', include(router.urls)), ] But slug2 outputs None and hence the problem. Is there any specific way to obtain those parameters. Thanks in advance. - 
        
How i can change password on Django
i wanna change django password without using the default view , i passed the PasswordChangeForm to the view but i didnt know how to post it class UpdateUserView(UpdateView): model = User template_name = 'test.html' form_class = UserUpdateForm success_url = '/' def get_context_data(self, *args, **kwargs): data = super().get_context_data(**kwargs) data['PasswordChangeForm'] = PasswordChangeForm(self.request.user) return data def post(self, request, *args, **kwargs): change_pw = User(password=request.POST.get('id_new_password1')) change_pw.save() def get_object(self): return self.request.user - 
        
Django Model method test
I have model like this: class Users(models.Model): pin = models.CharField(max_length=16, unique=True) name = models.CharField(max_length=64) surname = models.CharField(max_length=64, blank=True, null=True) patronymic = models.CharField(max_length=64, blank=True, null=True) def get_full_name(self): name = self.name surname = self.surname if self.surname is None: surname = '' if self.name is None: name = '' return str(name) + ' ' + str(surname) I want to write a test case for get_full_name method. Currently I wrote something like this: class TestUsersModel(TestCase): def setUp(self): self.data1 = Users.objects.create(name='Bob', pin='1') self.data2 = Users.objects.create(surname='Alex', pin='2') def test_users_model_entry(self): data = self.data1 self.assertTrue(isinstance(data, Users)) def test_users_full_name_only_name(self): data = self.data1.get_full_name() self.assertEquals(data,'Bob ') def test_users_full_name_only_surname(self): data = self.data2.get_full_name() self.assertEquals(data,' Alex') but when I check with coverage it says me that I have to write test case for this: What I am missing here? - 
        
Have to display data, from django using form and optional value
I am trying to display data from my models to HTML page by using form and field optional(value). Bat noting is displaying to my HTML page and the filter is not working: This is my modles.py file: from django.contrib.auth.models import User from django.db import models class TaskCategory(models.Model): category_title = models.CharField(max_length=50) def __str__(self): return self.category_title class Post(models.Model): task_title = models.CharField(max_length=250) task_discription = models.CharField(max_length=250) task_category = models.ForeignKey(TaskCategory, on_delete=models.CASCADE) recommended_tools = models.CharField(max_length=250) budget = models.CharField(max_length=250) def __str__(self): return self.task_title + ' | ' + self.task_discription + ' | ' + str(self.task_category) + ' | ' + self.recommended_tools + ' | ' + self.budget urls.py file: from django.urls import path from .views import PostPageView urlpatterns = [ path('PostPage/', PostPageView, name ='post_page'), ] view.py file: from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView,DetailView from .models import Post, TaskCategory from django.shortcuts import render, get_object_or_404 def is_valid_queryparam(param): return param != '' and param is not None def PostPageView(request): post = Post.objects.all() category = TaskCategory.objects.all() category = request.GET.get('category') if is_valid_queryparam(category) and category != 'Choose...': post = post.filter(category_title=category) context = { 'post': Post.objects.all(), 'category': TaskCategory.objects.all() } return render(request, "post_page.html", context) - 
        
Access to users update and delete views in allauth is accessible to other users
Just followed through all the allauth documentation setting up a site with user registration. Subclassed it to extend the fields. All working fine except that I can signup with a new account and delete/update any other account just by changing the url to supply their user id instead the logged in user. I must be missing a setting that I can't find documented anywhere - I'm really surprised this is the default behaviour. I've added a slug field to the user model with a random alphanumeric and changed the views to use this - mostly because I hate using pk's in urls, particularly in a situation that potentially exposes user accounts like this. This mitigates the risk at least but it's still open. Any allauth developers out there know what solution to this would be? - 
        
Django After LDAP Authentication leads to {"detail":"Authentication credentials were not provided."}
I know that issue around '"detail": "Authentication credentials were not provided.' was in a similar way already posted several times. However, the answers I found o far did help me. I have a Django app that I would like to deploy. In this App I have several Rest-APIs defined such as class MyViewSet(ReadOnlyModelViewSet): ... permission_classes = (permissions.IsAuthenticated,) AS Authentification Backend I use "django_python3_ldap.auth.LDAPBackend" with the following setting in the setting.py file AUTHENTICATION_BACKENDS = ( 'django_python3_ldap.auth.LDAPBackend', ) LDAP_AUTH_URL = "ldaps://XXX.XXX.XXX.XXX:XXX" LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory_principal" # The LDAP search base for looking up users. LDAP_AUTH_SEARCH_BASE = "ou=XXX,dc=XXX,dc=XXX" # LDAP Credtials LDAP_AUTH_CONNECTION_USERNAME = XXX LDAP_AUTH_CONNECTION_PASSWORD = XXX # Adapt filter def custom_format_search_filters(ldap_fields): search_filters = [("(&(objectClass=user)(sAMAccountName=" + '{user}' + "))").format(user=user_id)] return search_filters LDAP_AUTH_FORMAT_SEARCH_FILTERS = custom_format_search_filters On my locale windows machine, everything works well. After successful authentication, I can trigger the events that raise the rest-get call. I then deployed the project on an EC2 Amazon Linux 2 AMI machine. Here I added to the nginx setting the following code: server { # URL that is communicating with the client listen XXX.XXX.XXX.XXX:9000; server_name XXX.XXX.XXX.XXX; # Locatio for the logs access_log /data/webapp_project/logs/nginx-access.log; error_log /data/webapp_project/logs/nginx-error.log; # Gunicorn IP+Proxy location / { proxy_pass http://127.0.0.1:8001; proxy_set_header Host $http_host; } location … - 
        
how to find the distance between 1 user and other users in django rest framework
i am making an app which tracks the users location when they login, when they search for other users in their area i want to be able to calculate the distance between the users location and other users and only display users who are in a certain mile radius which the user can choose . I would like to put it in a class based list api view as a filter but i don't know how to do it. I have probably not explained it in the best way so please let me know if you don't understand my question - 
        
No 'Access-Control-Allow-Origin' header is present on the requested resource Occurs only when send video as request data Django + React
I am using django for backend/rest api and React for frontend. Both are on different servers. My Django Settings: CORS_ALLOWED_ORIGINS = [ "http://localhost:8000", "http://localhost:3000", "http://127.0.0.1:3000", "https://example.com" ] CORS_ORIGIN_WHITELIST = ( "http://localhost:8000", "http://localhost:3000", "http://127.0.0.1:3000", "https://example.com" ) On example.com / React Frontend, when I send a request to the API, it gives me status code 200, unless expected errors. But when I send video as request data to the API, it is giving me the following error Access to XMLHttpRequest at 'https://backdoor.example.com/api/content/post/' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. This error only occurs if I try to send video as request data if the video is null it gives me no error - 
        
Wrong links inside django app behind nginx reverse proxy
I am having this issue where i want to deploy my django app following way. Imagine some intranet virtual machine with some nginx configuration where all requests to https://something.smth/django/ will be forwarded to docker container where i have another nginx and django app. Home page is fine and django app normaly loads but when i click on some link django will set url to https://something.smth/some-link/ instead of https://something.smth/django/some-link/. I have seen lot of questions here but none of them solved my problem. I have very little knowledge about nginx and I would be very grateful if you could help me. Thank you! Here is my nginx configuration inside docker container (i dont have control over nginx in VM) upstream app { server web:8000; } server { listen 80; if ($http_x_forwarded_proto = 'http'){ return 301 https://$host$request_uri; } client_max_body_size 5000M; location / { proxy_pass http://app; proxy_read_timeout 10h; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header SCRIPT_NAME /ecg; } location /static/ { alias /usr/src/app/static/; } location /media/ { alias /usr/src/app/media/; } } and docker-compose if that helps version: '3.7' services: web: build: ./app command: daphne -b 0.0.0.0 -p 8000 django.asgi:application volumes: … - 
        
TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method Django
How to solve this error : TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method'? I want to return cart length in json. def add_cart(request, product_id): cart = Cart(request) product = Product.objects.get(id=id) produit = serializers.serialize('json', [produit]) form = CartProductForm(request.POST) if request.method == 'POST' and request.is_ajax(): if form.is_valid(): cd = form.cleaned_data cart.add(product=product, qty=cd['qty'], update_qty=cd['update_qt'] ) card = serializers.serialize('json', cart) return JsonResponse({'status': 'success', 'cart_length': card}) Error: Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\decorators\http.py", line 40, in inner return func(request, *args, **kwargs) File "C:\Users\HP\Desktop\sama-marche\cart\views.py", line 26, in ajouter_cart produit = Produit.objects.get(id=id) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 399, in get clone = self.filter(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 892, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 910, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\query.py", line 1290, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\query.py", line 1315, in _add_q child_clause, needed_inner = self.build_filter( File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\query.py", line 1251, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\query.py", line 1116, in build_lookup … - 
        
How to access request.user with AbstractUser class
I am trying to create an order object and assign the order's customer field (which is a foreign key for User) to the current user. Even though it passes the if statement and it can authenticate the request.user, it assigns customer as a blank value. When I print customer it prints a blank line, however when I print customer.id, it prints the ID of the customer. This happens in all views in the project so its a global issue I belive this has something to do with the fact that my user class is inheriting from AbstractUser utils.py def cartData(request): if request.user.is_authenticated: print('This will print') customer = request.user print(customer) print(customer.id) order, created = Order.objects.get_or_create(customer=customer, complete=False) models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): author = models.BooleanField(default=False) settings.py AUTH_USER_MODEL = 'main.User' I feel like this may be an easy one but I can't figure it out! Thanks.