Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix Django Duplicate key form from being valid and saved?
This is my views.py file and Im getting this message DETAIL: Key (member_id, match_id)=(4, 20) already exists. However is see that Valid is printing so its obvious the is_valid() method doesnt catch this duplicate key. def update_batter_form(request, match_id, batting_id): """Edit existing batter form view.""" obj = Batting.objects.get(pk=batting_id) form = BattingForm(instance=obj) batting_list_bn = Batting.objects.order_by('batter_number') \ .filter(match_id=match_id) match = Match.objects.get(pk=match_id) if request.method == 'POST': print("Printing POST") form = BattingForm(request.POST, instance=obj) print(obj) if form.is_valid(): print("Valid") form.save() return redirect('/club/match/'+match_id+'/batter/'+batting_id) else: print(form.errors) return redirect('/club/match/' + match_id + '/batter/' + batting_id) context = { 'form': form, 'batting_list_bn': batting_list_bn, 'match': match } return render(request, 'club/batter_update.html', context) How is it I catch this issue? -
Django unit test failing, but if I manually test a view in browser it works
I am working on a page to create an order when a customer post address details. When I test the view in the browser it works. I want to test if an order was created. I submit a form with address details, After submiting the data the order is created. I check in the admin site to verify the order has been created. I find it has been created. When I run python manage.py test order it fails. No order is found when I make a query for that recently created order. Below is the code for the order_create view. from django.shortcuts import render, redirect from django.urls import reverse from django.conf import settings from .forms import AddressForm from users.models import Customer from .models import Delivery, Order, OrderItem, Address from cart.cart import Cart from django.utils.translation import ugettext_lazy as _ from django.core.exceptions import ValidationError from django.conf import settings # Create your views here. def order_create(request): form = AddressForm() # Get the cart from the session cart = Cart(request) for item in cart: print(item) # If the cart does not exist then redirect to shops so the # user can start shopping if not cart: return redirect(reverse("core:product_list")) # Check if it is POST … -
How do I run Django Management > Commands as cron jobs in Elastic Beanstalk running nginx
I'm upgrading a Django application from Elastic Beanstalk Python 3.6 running on 64bit Amazon Linux to Python 3.8 running on 64bit Amazon Linux 2 and moving from the Apache server to Nginx. I'm trying to set up the cron jobs. On Linux 1 I had 03_files.config container_commands: ... 02_cron_job: command: "cp .ebextensions/crontab.txt /etc/cron.d/autumna_cron_jobs && chmod 644 /etc/cron.d/autumna_cron_jobs" #leader_only: true ... with crontab.txt # Set the cron to run with utf8 encoding PYTHONIOENCODING=utf8 ... 30 0 * * * root source /opt/python/current/env && nice /opt/python/current/app/src/manage.py test_cron ... # this file needs a blank space as the last line otherwise it will fail I've converted this to 03_cron.config container_commands: 01_cron_job: command: "cp .ebextensions/crontab.txt /etc/cron.d/autumna_cron_jobs && chmod 644 /etc/cron.d/autumna_cron_jobs" #leader_only: true with crontab.txt # Set the cron to run with utf8 encoding PYTHONIOENCODING=utf8 ... 30 0 * * * root source /var/app/venv/staging-LQM1lest/bin/activate && nice /var/app/current/manage.py test_cron ... # this file needs a blank space as the last line otherwise it will fail I've actually got it running every 10 minutes to try and understand what is happening. When I look in the logs, withing \var\log\cron I have: Apr 9 09:10:01 ip-172-31-41-78 CROND[22745]: (root) CMD (source /var/app/venv/staging-LQM1lest/bin/activate && nice /var/app/current/manage.py test_cron >> /var/log/test_cron.log.log 2>&1) … -
for loop is showing single object in javascript
I am building a Social media webapp. AND i am stuck on a Problem. What i am trying to do :- I build story feature in webapp ( like instagram stories ). The Problem is :- When two different users post images in stories then images are showing in single story BUT i am trying to show if two users post two images in stories then show in different stories.- There are two stories posted by different users BUT they both are showing in one story. I think loop is not working correctly.I tried many time but nothing worked for me. <script> var currentSkin = getCurrentSkin(); var stories = new Zuck('stories', { backNative: true, previousTap: true, skin: currentSkin['name'], autoFullScreen: currentSkin['params']['autoFullScreen'], avatars: currentSkin['params']['avatars'], paginationArrows: currentSkin['params']['paginationArrows'], list: currentSkin['params']['list'], cubeEffect: currentSkin['params']['cubeEffect'], localStorage: true, stories: [ // {% for story in stories %} Zuck.buildTimelineItem( 'ramon', '{{ user.profile.file.url }}', '{{ story.user }}', 'https://ramon.codes', timestamp(), [ [ 'ramon-1', 'photo', 3, // '{% for img in story.images.all %}' '{{ img.img.url }}', '{{ img.img.url }}', // '{% endfor %}' '', false, false, timestamp(), ], ] ), // {% endfor %} ], }); </script> I have no idea what to do. Any help would be Appreciated. Thank You in … -
Django .query attribute behavior
I have been trying to see raw SQL queries, which Django ORM makes and here is a problem. When I am typing print(User.objects.filter(username='adm').query), I get SQL query, but if I type previous statement without print function, I get <django.db.models.sql.query.Query object at 0x000002AA92E6DB88>. I can suppose, it happens because .query attribute mutates Django ORM query into just query object (how we can see above). So, is there one, who can tell me what happens under the hood? -
How to debug Python Django Errno 54 'Connection reset by peer'
I am doing a successful ajax call and then refresh the page (using window.location.reload()) to show the changes made in the database. Doing this throws an error: Exception happened during processing of request from ('127.0.0.1', 49257) Traceback (most recent call last): File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/socketserver.py", line 720, in __init__ self.handle() File "4_Code/Floq_Django/venv/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "4_Code/Floq_Django/venv/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer I am a bit lost, why this is happening?! As soon as I remove window.location.reload() and only do the ajax call I do not get any errors... Any suggestions/hints/tipps? Thanks a lot. -
Django, how to hold different time in database (not UTC)
I have a working website made in django that contains models with DateTimeField, it's a simple timestamp holding time of creation, it looks like this: timestamp = models.DateTimeField(auto_now=True) And also DateTimeField that I update later on: **MODEL.PY** data_zal = models.DateTimeField() **VIEWS.PY** t = Zam(data_zal=timezone.now()) t.save() My settings are as follows: TIME_ZONE = 'Europe/Warsaw' USE_I18N = True USE_L10N = True USE_TZ = True Everything works perfectly, time is displayed correctly (UTC+2). But in database (I checked sqlite and mysql- development/production) it is seen as UTC. Thanks to SELECT now(); I can see the UTC+2 time. It wouldn't be a problem but I have a program that connects to my database and fetches data to process it further. It is starting to cause some problems coz of the mismatch of what client sees and what program sees. Is there any way I can format time in database to correct value (UTC+2)? -
How can I add data to each entry of a ManyToMany field in an object?
I'm kind of new to Django and databases. I'm working on a database that will save the type and mass of meals in a tray, in public restauration. For instance, a tray will be linked to a specific service and could contain 100g pasta and 80g cake. I'd like a model "MenuItems", storing various informations on each recipe, this is pretty easy, it works fine. Then I created "Service", which stores the date of a service, and a ManyToManyField registering the menu, that is to say the MenuItems that were offered on that date. This works fine too. But the tricky part for me is this: In a third model, called "Trays", I'd like to: -first, choose the Service this tray was taken from (ex: 09/04/2021) -then choose the MenuItems that were in this specific tray, among those on the menu for that service (ex: say on that service there was pasta, cake, meat and fruits, I'd like not to be suggested any other item) -and finally, for each of the MenuItems in the tray, add the mass of each item. (ex: if there was only meat and cake in this specific tray, I'd like to add pasta and fruits … -
jAutoCalc wildcard for element name with number index
So I want to use jAutoCalc for my website that will do a calculation for some of its elements. The jAutoCalc do the calculation by inserting an element with some formula, for ex: <input type="text" name="item_total" value="" jAutoCalc="{qty} * {price}"> Here, the formula is the jAutoCalc="{qty} * {price} part In my case, I'm using Django Framework that creates a table automatically that will gives number index to each of it item elements based on the row of the table, for ex: FormName-1-FieldName1 | FormName-1-FieldName2 FormName-2-FieldName1 | FormName-2-FieldName2 FormName-3-FieldName1 | FormName-3-FieldName2 FormName-4-FieldName1 | FormName-4-FieldName2 Now is there any method that I can do to iterate the multiplication based on the index of the element? For example how to do a multiplication based on the index number of the element? I'm thinking of using a wildcard to iterate through the elements that I want to calculate but is it possible to put it inside the name in the formula -
Django-q how to delete scheduled tasks
I'm using django-q to schedule monthly event for sending emails. After several testing runs, I realized that each time I execute the: Schedule.objects.create(func='app.email.send_monthly_email',schedule_type=Schedule.MONTHLY,repeats=-1) this schedule event is cached and it will run the next time I start qcluster. How to I delete all the scheduled tasks in django-q? Or how can I have a clean start every time I run qcluster? -
How to get the url parameters and display it in the template file?
For instance my url ../home/regular will return a list of all accounts that are of regular accounts. How can I include the "regular" into the context data that is returned to my template file from my get_queryset? Alternatively I tried to use the request.path like from this post in my template file but I don't know how to get only the last last parameter. **Note that the url might not include the 'home/regular' and I have set the default to "regular" accounts. -
results_picker returning none when input is incorrect and then corrected
import random def user_input_checker(data): if data not in ["rock","paper","scissors"]: print("something went wrong...") user_input_da() else: return data def user_input_da(): user_data = input("Please enter either rock,paper or scissors") user_input = user_input_checker(user_data) return user_input def computer_input(): computer_choices = ["rock","paper","scissors"] computer_picks = random.choice(computer_choices) # picking random value from array return computer_picks def results_picker(): user = user_input_da() comp = computer_input() if user == comp: print("The game is a draw") else: print("One of yous won ou said =>",user,"\n""The computer said =>",comp)`enter code here` Hi i am new to the python program language. The issue I am facing is that when I run the program with the correct input the programs works fine, but when I run the program with an incorrect input in the firsttime and reenter the new the new value it returns none How do I solve this please? -
When running my django project in python3 manage.py run server i get this error ModuleNotFoundError: No module named 'pip._vendor.urllib3.connection'
After i run python3 manage.py runserver i get the following error: Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line File "/Users/luiseduardo/Practice/nova/nova_venv/lib/python3.8/site-packages/django/core/management/init.py", line 12, in from django.conf import settings ImportError: cannot import name 'settings' from 'django.conf' (unknown location) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? (nova_venv) Luiss-MacBook-Pro:novadjango luiseduardo$ pip install django Traceback (most recent call last): File "/Users/luiseduardo/Practice/nova/nova_venv/bin/pip", line 6, in <module> from pip._internal import main File "/Users/luiseduardo/Practice/nova/nova_venv/lib/python3.8/site-packages/pip/_internal/__init__.py", line 19, in <module> from pip._vendor.urllib3.exceptions import DependencyWarning File "/Users/luiseduardo/Practice/nova/nova_venv/lib/python3.8/site-packages/pip/_vendor/urllib3/__init__.py", line 7, in <module> from .connectionpool import ( File "/Users/luiseduardo/Practice/nova/nova_venv/lib/python3.8/site-packages/pip/_vendor/urllib3/connectionpool.py", line 30, in <module> from .connection import ( ModuleNotFoundError: No module named 'pip._vendor.urllib3.connection' Im using mac and i do have my virtualenv activated. -
Django Rest Framework group and count POST
I am new to DRF and am trying to create some kind of dynamic serializer to calculate the objects posted but I cannot find out how to do it. models.py class Company(TimeStampedModel): name = models.CharField(max_length=200, blank=True) description = models.TextField(blank=True) date_founded = models.DateField(null=True, blank=True) def get_year (self): return self.date_founded.strftime("%Y") def get_quarter (self): x = self.date_founded if int(x.strftime("%m")) <= 3: return '1' elif int(x.strftime("%m")) <= 6 and int(x.strftime("%m")) > 3: return '2' elif int(x.strftime("%m")) <= 9 and int(x.strftime("%m")) > 6: return '3' else: return '4' def __unicode__(self): return u'{0}'.format(self.name) serializers.py class StatsSerializer(serializers.ModelSerializer): year = serializers.DateField(source='get_year') quarter = serializers.CharField(source='get_quarter') # total = serializers.SerializerMethodField() class Meta: model = Company fields = ['year', 'quarter', #'total'] views.py class CompanyStatsView(generics.ListCreateAPIView): queryset = Company.objects.all() serializer_class = StatsSerializer So far my results are: [ { "year": "2018", "quarter": "2" }, { "year": "2018", "quarter": "2" }, { "year": "2018", "quarter": "2" }, { "year": "2018", "quarter": "2" }, { "year": "2018", "quarter": "3" }, { "year": "2018", "quarter": "3" }, ] however I am looking for something like this: [ { "year": "2018", "quarter": "2" "total": 4 }, { "year": "2018", "quarter": "3" "total": 2 }, ] How can I group and count this values? Any help is much … -
admin_order_field not ordering in descending order
Am trying to order items in the column in descending order, but it's not working , below is my model : class Person(models.Model): first_name = models.CharField(max_length=50) color_code = models.CharField(max_length=6) count_num = models.IntegerField() def __str__(self): return self.first_name Then, in the admin.py file I have this : @admin.register(Person) class PersonAdmin(admin.ModelAdmin): list_display = ('first_name', 'color_code', 'counting') def counting(self, obj): return obj.count_num counting.admin_order_field = '-count_num' But the column counting seems not to be sorted , below is the screenshot : -
Type error __str__ returned non-string (type employeeName)
I am trying to make a one to many database with name and time in time out fields but when I enter value to the child table by using the admin site it gives me this error __str__ returned non-string (type employeeName) here is my model: from django.db import models from datetime import datetime, date from django.utils.timezone import localtime #Create your models here. class employeeName(models.Model): employee = models.CharField(max_length=200) def __str__(self): return self.employee class Name(models.Model): name = models.ForeignKey(employeeName, null=True,on_delete=models.CASCADE) timeIn = models.TimeField() timeOut = models.TimeField(default=datetime.now()) date = models.DateField(auto_now=True) def __str__(self): return self.name admin : from django.contrib import admin from .models import Name, employeeName from .forms import CreateNewList class ComputerAdmin(admin.ModelAdmin): list_display = ["name", "date","timeIn", "timeOut"] admin.site.register(Name, ComputerAdmin) admin.site.register(employeeName) I have also tried using def __str__(self): return str(self.name) It still gives me the same error -
TypeError: Field 'price' expected a number but got <django.db.models.fields.FloatField>
I have that exception"TypeError: float() argument must be a string or a number, not 'FloatField'" even thought i deleted the price field and runned makemigrations , how??? -
Trigger multimple events from one click button - write to database & render an HTML
Here is my scenario. I am building a website where I have created a dependent dropdown menu. Say select A(first dropdown) then select A2 (second Dropdown) ----> Submit Then I am writing the values to databse (A-A2). Below is the flow. Submit button in JS --> Call funciton in views.py --> writing to database. In JS, I have used 2 event handlers on same itemForm object: itemForm.addEventListener('submit', e=>{ e.preventDefault() console.log('submitted') $.ajax({ type: 'POST', url: '/create/', data: { 'csrfmiddlewaretoken': csrf[0].value, 'firstItem': firstitemText.textContent, 'secondItem': seconditemText.textContent, }, success: function(response){ console.log(response) alertBox.innerHTML = `<div class="ui positive message"> <div class="header"> Success </div> <p>Your order has been placed</p> </div>` }, error: function(error){ console.log(error) alertBox.innerHTML = `<div class="ui negative message"> <div class="header"> Ops </div> <p>Something went wrong</p> </div>` } }) itemForm.addEventListener('submit', e=>{ e.preventDefault() console.log('submitted') $.ajax({ type: 'POST', url: `orders/${seconditemText.textContent}`, data: { 'csrfmiddlewaretoken': csrf[0].value, 'firstItem': firstitemText.textContent, 'secondItem': seconditemText.textContent, }, success: function(response){ console.log(response) }, error: function(error){ console.log(error) } }) }) Now from second event handler, I want to call same html file and render a plot as shown below: In views.py: def main_view(request): qs = FirstItem.objects.all() return render(request, 'orders/main.html', {'qs':qs}) #Some other views funtion for writing data to dropdown, which might not be relevant def create_order(request): if request.is_ajax(): secondItem … -
Change the client-site "pattern" for URL-"input" using Django
I have a model which contains link = URLField(). The problem is, I don't want the client-side to do any kind of validation (i'm doing that in the clean_link). I have tried using django-widget-tweaks such as mytemplate.html {% load widget_tweaks %} <div class="form-group"> {{form.link|attr:"pattern:.*"|as_crispy_field}} </div> which has no effect. I can include novalidate in my <form> but then that'll remove validations for all my fields, and not only for link. How do we properly manage the attributes/properties for <input> when we are using the Django-form? -
Python - Django - How to write log to an existing Kibana from Django framework?
Well my team is currently having a Kibana working. I am building a source by Django Framework. I was told to write log into that existing Kibana. I was provided : LOGSTASH_HOST=172******** LOGSTASH_PORT=5***** INDEX=platform-staging After looking up for some resources: I did this in my settings.py 'logstash':{ 'level':'DEBUG', 'class': 'logstash.LogstashHandler', 'host': '172******, 'port': 5000, 'version':1, 'message_type' : 'logstash', 'fqdn':False , 'tags': ['tag1', 'tag2'] } 'loggers': { 'django.request':{ 'handlers': ['logstash'], 'level': 'DEBUG', 'propagate': True }, When I build my app: I got an error like this: raise ValueError('Unable to configure handler ' ValueError: Unable to configure handler 'logstash' Well please help me out of this situation, and it would be nice if you can me a detailed document. -
I have coded some python program and I want it to implement on website so that everyone with the link can use it by providing necessary arguments
I have a python program and I want to make it online as a website so that anyone can visit that site fill the required information and run the program , I don't know how I can implement it on a website so can anyone please help me out ? Can I do with Django, If yes then how? -
How to validate a subscription in google play store using receipt in python
I need to validate a receipt received from the android app while a subscription is taken. I have tried using the python package for validating in-app purchases, but end up in error. I have used pyinapp for this... link(https://pypi.org/project/pyinapp/#description) from pyinapp import GooglePlayValidator, InAppValidationError bundle_id = 'com.yourcompany.yourapp' api_key = 'API key from the developer console' validator = GooglePlayValidator(bundle_id, api_key) receipt = json.dumps({"orderId": "GPA.3371-6663-9953-88022", "packageName": "com.yourcompany", "productId": "com.yourcompany.basic.five.annually", "purchaseTime": 1617944948660, "purchaseState": 0, "purchaseToken": "fkefffonlgkfapblnahlokjp.AOJ1OzvaGGwTt24bMs47c98hpPQI62qdITM- uphoHzK4HQkW5locx9xDILRasO7eQTTRoGr0LwyflO2mqvnfn0fNVkZ0ipPgQ", "autoRenewing": true, "acknowledged": true}) signature = '' (signature from android app) purchases = validator.validate(receipt, signature) process_purchases(purchases) but always ended up in bad signature error at line validator.validate(receipt, signature) Can you please help....don't know what is wrong -
Different images of two users are showing in one story
I am building a Social Media app. AND i stuck on a Problem. What i am trying to do :- I have build a story feature ( users can make their story like instagram ) everything is working fine BUT When two different users post images in stories then images are showing in single story BUT i am trying to show if two users post two images in stories then show in different stories.- As you can see in first picture that first story is by user_1 and another is by user_2, They are showing in same story but i want them to show in different stories. stories.html <script> var currentSkin = getCurrentSkin(); var stories = new Zuck('stories', { backNative: true, previousTap: true, skin: currentSkin['name'], autoFullScreen: currentSkin['params']['autoFullScreen'], avatars: currentSkin['params']['avatars'], paginationArrows: currentSkin['params']['paginationArrows'], list: currentSkin['params']['list'], cubeEffect: currentSkin['params']['cubeEffect'], localStorage: true, stories: [ // {% for story in stories %} Zuck.buildTimelineItem( 'ramon', '{{ user.profile.file.url }}', '{{ story.user }}', 'https://ramon.codes', timestamp(), [ [ 'ramon-1', 'photo', 3, // '{% for img in story.images.all %}' '{{ img.img.url }}', '{{ img.img.url }}', // '{% endfor %}' '', false, false, timestamp(), ], ] ), // {% endfor %} ], }); </script> </body> </html> models.py class ImgModel(models.Model): img = models.ImageField(upload_to='status_images',null=True) … -
Filtered left outer join in Django that gives access to related Model, not its fields via values()
I am trying to build a list of products for further use in view template. This list is based on filtered Product model that are referred by ForeignKeys in ProductInfo and Image models. Final QuerySet should include all Products that are fall under given criteria and one or zero (depending on additional filters) objects from ProductInfo and Image. If I use annotate() and FilteredRelation() like this: ll = Product.objects.filter(Category=category) \ .annotate(pi=FilteredRelation('productinfo', condition=Q(productinfo__Language=language.id))) \ .annotate(im=FilteredRelation('image', condition=Q(image__IsPrimary=True))) then I need to use values() to access data from jointed Models, and some of custom template tags that I use (for example django-imagekit) will fail because they expect an instance, not just field. I don't expect that the products list will be more than 100 items, and I am thinking that it will be easier to retrieve 3 correctly filtered sets (Product, ProductInfo, Image) and try to join them in code. However I cannot pass it correctly to template engine via context. -
how to unit test custom product models with Foregienkey in unittest in django with pytest
I am trying to unit test a specific model which has a foregienkey with pytest , but after lot of effort I am still facing error and I am new to unit test . error : @pytest.mark.django_db def test_create_pg(client): user=PPuseers.objects.create(Uid='6fa459ea-ee8a-3ca4-894e-db77e160355e') make_pg=PG() > assert PG.objects.count==0 E assert <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.db.models.manager.Manager object at 0x04E8D220>> == 0 E + where <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.db.models.manager.Manager object at 0x04E8D220>> = <django.db.models.manager.Manager object at 0x04E8D220>.count E + where <django.db.models.manager.Manager object at 0x04E8D220> = PG.objects PPpgOwner\test\test_views.py:41: AssertionError My MODELS.PY class PG(models.Model): pg_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) pg_Owner = models.ForeignKey(PPuseers, on_delete=models.CASCADE) pg_name = models.CharField(max_length=255,default='Null') location = models.CharField(max_length=50,default='Null') describtion = models.CharField(max_length=10000, default='Null') pg_main_price = models.IntegerField(default=0) pg_discount_price = models.IntegerField(default=0,blank=True,null=True) ...... ....... this model is liked with a PPusers model PPusers MODEL class PPuseers(AbstractBaseUser, PermissionsMixin): Uid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(verbose_name="email", max_length=554, unique=True) username = models.CharField(max_length=500, unique=False) date_joined = models.DateTimeField(verbose_name="Date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) ...... ...... ...... MY Pytest : from django import urls from django.contrib.auth import get_user_model from django.http import response from django.urls.base import reverse from PPCustomer.models import PPuseers from PPpgOwner.models import PG @pytest.mark.django_db def test_create_ppuser(client,ppuser_data): user=PPuseers.objects.create(Uid='6fa459ea-ee8a-3ca4-894e-db77e160355e') assert PPuseers.objects.count()==1 @pytest.mark.django_db def test_create_pg(client): user=PPuseers.objects.create(Uid='6fa459ea-ee8a-3ca4-894e-db77e160355e') make_pg=PG() assert PG.objects.count==0 pg_tester=PG.objects.create( pg_id='6fa459ea-ee8a-3ca4-894e-db77e160355e', pg_Owner …