Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : How to get month data in week wise format in django
class Car(models.Model): name= models.CharField() model = models.CharField() date = models.DateTimeField(default=datetime.now) This is my Model ( Car ) If I pass date params ( 2021-07-09 ), I need last 1 month of data from this date. ( Eg : 2021-07-9 - 30 DAYS ). I'm using Django Rest framework. I need 30 days of data's in week format ( 7 days data in one set like wise..) can anyone help me to come out of this situation.. Thank you...!! -
Filter django model using Dictionary Comprehension
I have a model, called cards, which contains a number of elements I want to loop through. So I was trying to use some dictionary comprehension as follows: cards = Card.objects.filter(device=device) output = { c.id : [c.generateData(), c.sensor.getLatestTime()] for c in cards} While running that code, it breaks on the output statement with the following error: The QuerySet value for an exact lookup must be limited to one result using slicing. Most of the pre-existing answers I found for that exact error were for cases where the queryset is being confused with a single field, as in 1, 2. However in my case, I am expecting, and handling it as a queryset by looping through it. I have also seen a question that is similar in here about using dictionary comprehension on the models, however as far as I can see, my format is almost the same (Unless the list as a second parameter is causing an issue somehow?) -
daphne run in supervisor returns an error django.core.exceptions.ImproperlyConfigured
why daphne returns an error to me via supervisor django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure () before accessing settings. But when I run it out of supervisorctl, it works. I have a system variable defined. Is it a mistake to run it in venv?. supervisor conf [fcgi-program:asgi] # TCP socket used by Nginx backend upstream socket=tcp://localhost:8099 # Directory where your site's project files are located directory=/srv/app/ # Each process needs to have a separate socket file, so we use process_num # Make sure to update "mysite.asgi" to match your project name command=/srv/venv/bin/daphne -u /srv/run/daphne/daphne%(process_num)d.sock --fd 0 --access-log - --proxy-headers mysite.asgi:application # Number of processes to startup, roughly the number of CPUs you have numprocs=1 # Give each process a unique name so they can be told apart process_name=asgi%(process_num)d # Automatically start and recover processes autostart=true autorestart=true # Choose where you want your log to go stdout_logfile=/srv/log/daphne.log redirect_stderr=true -
Django-filer upload location change
How do I access image URLs for Filer-fields also how to change the upload location Class CustomFilters(models.Model): input_file = models.ImageField( upload_to='input/images/', blank=True, null=True) bg_image_one = FilerFileField(null = True,on_delete = models.CASCADE) name = models.CharField(max_length=50) action = models.CharField(max_length=150, choices=ACTION_CHOICES) is_active = models.BooleanField(default=False) Currently, i am trying this bg_image_one.image.url -
What is the best WAY to create a django model instance with a model form with blank and null set true on certain fields?
I have the following model: class Foo(models.Model): field1 = models.CharField(max_length=100) field2 = models.ForeignKey(AnotherModel, on_delete=models.CASCADE) field3 = models.ImageField(blank=True, null=True) field4 = models.CharField(max_length=15, blank=True, null=True) And here is my view: def myView(request): form = FooForm(request.POST or None) if form.is_valid(): # What is the best to extract to filled fields by the user # so that I will know what to pass the objects.create() method field2 = form.cleaned_data.get('field1) # how to know if that's empty since it is not required Foo.objects.create(field1="do not want it to be empty" ) What is the best way to check if the value of the fields is not empty and pass it to the create method? -
I get this django error 421, b'service not available (connection refused, too many connections when signing up for my account, i dont really know?
SMTPConnectError at /investor/signup (421, b'service not available (connection refused, too many connections)') This Error has been delaying for days now, i'm really stuck while sending email with django and i'm a beginner in django that why i do not have many idea on how to solve this issue please can anyone help? Setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'xxxxxxxxxxxxxxxx@gmail.com' EMAIL_HOST_PASSWORD = 'xxxxxxxxxxxxxxxxxxxxxx!?' EMAIL_USE_TLS = True -
buffer = _builtin_open(filename, 'rb') PermissionError: [Errno 13] Permission denied: 'C:/Users/Users/OneDrive/Desktop/projects/Barracuda'
Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1.2\plugins\python-ce\helpers\pydev\pydevd.py", line 1483, in _exec pydev_imports.execfile(file, globals, locals) # execute the script File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1.2\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 11, in execfile stream = tokenize.open(file) # @UndefinedVariable File "C:\Users\bbuug\AppData\Local\Programs\Python\Python39\lib\tokenize.py", line 392, in open buffer = _builtin_open(filename, 'rb') PermissionError: [Errno 13] Permission denied: 'C:/Users/bbuug/OneDrive/Desktop/projects/Barracuda' Process finished with exit code 1 -
On what level in the django MTV architecture does the Django Rest Framework work?
I understand that django is an MTV architecture. I also understand that M is models, T is templates (which are views in MVC) and V is views (which are controllers in MVC). I want to understand if the django serializers and views are views or templates according to the MTV when using Django Rest Framework. -
Django StreamHttpRequest running multiple cameras
I am building an App using opencv and django with multiple cameras attached. I intend to build a preview feature which allows to open 1 camera after another to check their focus. However, I have tried with streamhttpresponse and does not find a way to close the stream manually, in which case even if I close the window and try to open another camera, it always failed. I will have to refresh the webpage and open a new camera. The question is, can I turn off the streamhttpresponse? (afaik it might not be possible) Or as an alternative way, open a new response that can somehow replace the existing one. Hope someone can help. Thanks. -
Django websocket ValueError [closed]
When I access a websocket on a non-existent put, django raises an error Is this normal behavior or should I handle this case? Traceback (most recent call last): File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/routing.py", line 168, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'ws/dgd/'.``` -
Django api function for total of branches in POS
Below is my code for an api function, I want to return each branch of a bakery with their sub total, tax amount and grand total. I've been given this task to do this function only. The other parts like models etc are already completed. ''' #branches tax report and total - FBR def branch_report(request, params): try: orders = Order.objects.filter(is_removed=False).values_list('id') branch = BusinessBranch.objects.filter(is_removed=False).values_list('id') for each in branch: total = int(orders.objects.aggregate(total=sum('sub_total'))['total']) g_total = int(orders.objects.aggregate(g_total=sum('grand_total'))['g_total']) fbr_tax = int(orders.objects.aggregate(fbr_tax=sum('tax_amount'))['fbr_tax']) ctx['g_total'] = g_total ctx['fbr_tax'] = fbr_tax ctx['total'] = total for each in branch: return response_format(SUCCESS_CODE, SUCCESSFUL_RESPONSE_MESSAGE, g_total, fbr_tax, total) except Exception as e: return response_format(ERR_GENERIC, str(e)) ''' -
Got error when implementing two jquery plugins? please, help me to work this function
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous"> <title>Hello, world!</title> <!--Slick--> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.css"> <link rel="stylesheet" type="text/css" href="http://kenwheeler.github.io/slick/slick/slick-theme.css"/> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css"> <style> .slider-item { width:50%; } .slider-nav { width:50%; } </style> </head> <body style="background-color: rgb(151, 148, 144);"> <h1>Hello, world!</h1> <div class="col-md-6"> <div class="d-flex flex-column align-content-center justify-content-center"> <div class="slider-for m-2"> <img src="product1.png" width="80" id="showcase"> <img src="product2.png" width="80" id="showcase1"> <img src="product3.png" width="80" id="showcase2"> <img src="product2.png" width="80" id="showcase3"> <img src="product3.png" width="80" id="showcase4"> <img src="product1.png" width="80" id="showcase5"> </div> <div class="ms-3 px-2 mt-5 d-flex justify-content-center"> <div class="slider-nav"> <div class="slider-item"><img src="product1.png" width="80"></div> <div class="slider-item"><img src="product2.png" width="80"></div> <div class="slider-item"><img src="product3.png" width="80"></div> <div class="slider-item"><img src="product2.png" width="80"></div> <div class="slider-item"><img src="product3.png" width="80"></div> <div class="slider-item"><img src="product1.png" width="80"></div> </div> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <!--Jquery--> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!--slick--> <script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.js"></script> <!--zoom--> <script src="ddpowerzoomer.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('.slider-for').slick({ slidesToShow: 1, slidesToScroll: 1, arrows: false, fade: true, asNavFor: '.slider-nav' }); $('.slider-nav').slick({ slidesToShow: 3, slidesToScroll: 1, asNavFor: '.slider-for', dots: false, arrows: true, centerMode: false, focusOnSelect: true, }); }); jQuery(document).ready(function($){ //fire on DOM ready $('#showcase').addpowerzoom() //add zoom effect to images with CSS class … -
else function is not working in views.py django
My if condition is working but my else condition is not working. Even if we provide condition for else it is returning the response of except block. import json from owner.models import Owner @csrf_exempt def register(request): if request.method == 'POST': payload = json.loads(request.body) username = payload['username'] password = payload['password'] contact = payload['contact'] company_name = payload['company_name'] owner = Owner(username=username, password=password, contact=contact, company_name=company_name) global response response = 0 try: if Owner.objects.get(username__exact = username): response = json.dumps([{'Error': 'Username already taken'}]) else: owner.save() response = json.dumps([{'Success':'Owner added successfully'}]) except: response = json.dumps([{'Error': 'Owner could not be added!'}]) return HttpResponse(response, content_type='text/json') -
Django: Multiple Select Form (Widget)
I would like to create a form to a model with m2m relation to another one (~10k data). It's a multiple-choice field, so how to adjust the form to show already selected options? User should also has a possibility to remove one from any from the already selected options without deleting all of them. Any search bar is possible to be attached to that form? Currently it looks like: Form field Thanks in advance. -
Using multiprocessing in a django administration command script is yielding unexpected error
I am trying to build a custom administration command in my django project. I started using concurrent.futures.ThreadPoolExecutor() for executing my code parallely. This works well as shown here: def my_function(param_1=None): # this function needs to be executed parallely class Command(BaseCommand): def handle(self, *args, **options): status = True while status: my_model_data = my_model.objects.exclude( some_id__isnull=True ).exclude( some_id__exact='0' ).exclude( other_id__exact=0 ).filter( status="pending" )[0:2] if not my_model_data: continue with concurrent.futures.ThreadPoolExecutor() as executor: futures = [] for row_data in my_model_data: futures.append( executor.submit( my_function, param_1=row_data ) ) for future in concurrent.futures.as_completed(futures): try: print(future.result()) except Exception as e: print(e) I was looking for other alternatives for this, where I tried following 2 approaches: Approach 1: with Pool() as p: try: for row_data in my_model_data: p.starmap( my_function, list(row_data) ) except Exception as e: print(e) Approach 2 (Referred from here): def subprocess_setup(): django.setup() with ProcessPoolExecutor(max_workers=5, initializer=subprocess_setup) as executor: try: for row_data in my_model_data: executor.map( my_function, list(row_data) ) except Exception as e: print(e) In both these approaches I get the following error: 'my_model' object is not iterable Any help would be great! -
Django Virtual Environment - No module named 'gunicorn'
I've followed this guide (https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04), but I'm presently seeing the following when trying to run gunicorn via the gunicorn service file (/etc/systemd/system/gunicorn.service): Oct 04 11:30:22 ukgcdeploy01 gunicorn[8095]: File "/opt/envs/automation-console-env/bin/gunicorn", line 5, in <module> Oct 04 11:30:22 ukgcdeploy01 gunicorn[8095]: from gunicorn.app.wsgiapp import run Oct 04 11:30:22 ukgcdeploy01 gunicorn[8095]: ModuleNotFoundError: No module named 'gunicorn' The gunicorn.service file contains the following: [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/opt/envs/automation-console-env ExecStart=/opt/envs/automation-console-env/bin/gunicorn --timeout 600 --log-level debug --error-log /var/log/automation-console-env_error.log --access-logfile /var/log/automation-console-env_access.log --workers 3 --bind unix:/opt/envs/automation-console-env/automation-console-env.sock django_forms.wsgi:application [Install] WantedBy=multi-user.target Running gunicorn manually works fine: gunicorn --bind 0.0.0.0:8000 myproject.wsgi This was previously working before I had to upgrade my Python version from 3.5.2 to 3.9, and due to some issues I ended up having to recreate the virtual environment, so I don't think it's necessarily an issue with the service file, but rather my Python/Gunicorn installation. If anyone could offer some advice, it would be greatly appreciated :) -
What is the best way to pass django form data to javascript ajax call?
I have a form with a certain number of fields and using a ajax call to communicate with the server. And I was wondering what is the best way to pass the data that I get from the request.post of the form and pass it back to the javascript success property of the ajax. Here is an example: def ajaxView(request): form = MyForm(request.POST or None) if request.is_ajax() and form.is_valid(): #1 I used to use render_to_string and Parse it in the js #2 or get field by field using the request.POST.get method and return it return JsonResponse({}) return "" In the js file: function CreateAjax(e) { e.preventDefault(); $.ajax({ url: "/ajaxViewUrl/", type: "post", data: $("#idForm").serialize(), success: function (data) { // if the first option retreive fields by field after parse }, error: () => { } }); } Now this would not be an issue if the form has a small number of fields, my concern is when the form has a considerable number of fields and in any cases I would like to reduce repetition of getting the value of the inputs in the form. -
How to exclude deleted objects in a clean() function on a model/form using inline_formsety
I have a model with a custom clean function to make sure no two DateRange overlap: class MyModel(models.Model): date_range = DateRangeField() def clean(self): error_dict = {} if MyModel.objects.exclude(id=self.id).filter( date_range__overlap=self.date_range): error_dict['date_range'] = ValidationError( 'Range can not overlap with an existing period.', code='overlap_period') if error_dict: raise ValidationError(error_dict) This works, but if I use inline_formset to submit more than one record at a time and delete a record that would remove the conflict (whilst updating others), the ValidationError still raises. This is because the filter function is done on the existing records, not the new updated ones. How can I amend the filter to exclude deleted objects in the inline_formset? Should I be doing a clean on the form instead? If so, how do I reference deleted objects? -
Concurrent Rotating File Handler is not creating new file on reaching maxByteSize
I hope all are fine and well. I am working on Concurrent Rotating File Handler, As per the requirement I have to create a new log when an existing log file crosses the specified size and also the log file should not delete old log data when it is reloaded/restarted. Please find the below code and let me know if you require any information. from logging import getLogger, INFO from concurrent_log_handler import ConcurrentRotatingFileHandler log = getLogger() logfile = os.path.abspath("app.log") rotatehandler = ConcurrentRotatingFileHandler(logfile, "a", 100, 5) log.addHandler(rotatehandler) log.setLevel(INFO) router.get('/demo_api/v1') def default_rd(db: Session = Depends(get_db)): try: category_data = db.query(models.table1.id, models.table1.Label).filter(models.table1.classCode=='Category').all() except Exception: log.info("Database Error") else: log.info("Fetched Categoty data") -
Some images not appearing in google news
I wanted our website articles to be appear in google news. I went to publisher center and filled all the necessary info. In sections, I selected feed and added the feed URL (my back-end is django). Everything looks ok. All the latest news appear in the way I wanted. The issue here is images. Images for some articles are not appearing. Why do some images appear and some don't. What are the things influencing this result. All images are of same size 920x520 . The image formats are jpg or png. Please help me out. Thanks. Sample item tag in the feed is <item><title>Sample title</title><link>https://sample.com/smaple-link/</link><description>Sample decription</description><guid>https://sample.com/smaple-link/</guid><content:encoded><figure><img src="https://sample.com/link-to-image" class="type:primaryImage"></img></figure></content:encoded><media:thumbnail width="300" url="https://sample.com/link-to-image" height="300"></media:thumbnail><figure type="image/jpeg"><image src="https://sample.com/link-to-image" caption="Strength and Clarity: Why Following Crowds Will Leave You Lost In The Noise"></image></figure></item> -
printing text in vertical align in django
here my code is working fine with html code and if placed in my project its not wotking here is my views.py import pdfkit class PrintLabels(View): def get(self, request, id, value): client = request.user.client order = OtherOrder.objects.get(client=client, id=id) items = order.otherorderitem_set.all() item_quantity = OtherOrderItem.objects.filter(other_order_id=id) url = '' for c in items: item = c.item if c.item.qr_code: s3 = boto3.client('s3') url = s3.generate_presigned_url('get_object', Params={ 'Bucket': 'AAAAAAAAAAA', 'Key': c.item.qr_code.name, }, ExpiresIn=1800) url = str(url) template = loader.get_template('index.html') context_dict = { 'items' : items, 'item': item, 'order' : order, 'item_quantity': item_quantity, 'qrcode_url': url, } context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdfkit.from_string(html, 'applicationpdf.pdf') pdf = open("applicationpdf.pdf") response = HttpResponse(pdf.read(), content_type='application/pdf') return response here is my index.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Light Degree</title> <style> html { background-color:#f4f4f4; } body { margin:0px; } @media print { @page { margin: 0; } body { margin: 0cm; } } </style> </head> <body> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td style="border-left: 1px solid #cccccc;"> <div class="" style="width:94.48px; height:861.73px;"> <table border="0" cellspacing="0" cellpadding="0" style="width:94.48px; height:861.73px;"> <tr> <td style="width:94.48px; height:861.73px; vertical-align: text-top;"> <div style="transform:rotate(90deg); width: 94.48px !important;"> <table width="100%" border="0" cellspacing="0" cellpadding="0" style="width:861.73px; height:94.48px;"> <tr> <td rowspan="2" … -
Django cors middleware not working when using GET on static image url
Hi I have ran into a problem with Django CORS configuration, I have tried using django-cors-headers and configured it properly in my settings, it works for making GET/POST requests to the api from my react frontend but anytime I try loading an image using image.src with "127.0.0.1:8000/path_to_my_image" the image loads properly in the network tab BUT it gives me a CORS same origin error right after for every image. DJANGO_APPS = [ ..., 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'config.settings.middleware.middleware.CorsFixMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) To clarify the loading of the image is working (the image is found, and I can access it without problems if I go to the image url in my browser, the only thing that fails is loading the image with ".src" from an element because of the CORS error. I tried to bypass the configuration by setting the response in a middleware, the middleware is correctly executed each time there's a response but it still doesn't work and the image is not showing any … -
Django how to add members to groups through signals?
my others signals working such as updating and creating instance but I am not understanding why it's not adding members to group? @receiver(post_save,sender=settings.AUTH_USER_MODEL) def update_user_profile_from_User_model(sender,instance,created,**kwargs): if instance.email: MyAuthors.objects.filter(user=instance).update(user=instance,first_name=instance.first_name) author = MyAuthors.objects.filter(user=instance) if not author and instance.is_blog_author and instance.email: MyAuthors.objects.create(user=instance,is_blog_author=instance.is_blog_author,first_name=instance.first_name,last_name=instance.last_name,email=instance.email) my_group = Group.objects.get(name='myauthors') my_group.user_set.add(instance) instance.save() I also tried this but didn't work. group = Group.objects.get(name='myauthors') if instance.is_blog_author: instance.groups.add(group) instance.save() -
Saving sql query in runtime Django
I use Django ORM to create complex sql queries dynamically, I want to save ---while running--- the sql query that Django builds for future use, I have not found a proper way to do it. As explained here there are two ways to access a query but only connection.queries contains a valid query, and needed to set debug=True. Because I want to do it in the product environment, debug=True are not really a solution for me, and i don't want to change the Django source code. Any solution/comment can help i use Django 2.2 -
Need to add auth token to graphene-django test using pytest
I am trying to add token to graphene-django headers using pytest. But It always return that user is anonymous as shown at the end but it should return user as token is added in fixture @pytest.fixture def creat_user(): user = User.objects.create(username="abc", email="x@x.com", password="abc123") token, __ = Token.objects.get_or_create(user=user) return user @pytest.mark.django_db def test_get_login_user(client_query, creat_user): headers = {"Authorization": f"Token {creat_user.auth_token}"} response = client_query( """ query { loginUser{ id, } } """, headers=headers, ) result = json.loads(response.content) print(result) Output {'errors': [{'message': "'AnonymousUser' object is not iterable", 'locations': [{'line': 3, 'column': 11}], 'path': ['loginUser']}], 'data': {'loginUser': None}}