Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can I get an id from request.POST of the form that I'm submitting now
I'm building a clinic Management System and in the section that you add a new doctor, I want the admin to be able to add the days that the doctor is available at, so that means the days' field is a list but Django doesn't have a list field in its models so I created CharField-> days days = models.CharField(max_length=200,null=True) and then I've created a multi-select input field inside the form <select name="days" class="form-select" multiple aria-label="multiple select example"> <option value="mon">Mon</option> <option value="sun">sun</option> <option value="wed">wed</option> <option value="etc">etc</option> </select> so I took the Selected data by using this code for i in request.POST.getlist("days"): d= str(i)+" "+d print(d) # result gonna be the days in string value splited by spaces eg : mon sun wed so I can use it later by using split() but the thing is I'm not able to add this data into the form while submitting it so I thought that I can save the form data and then alter the field days like that def add_doctor(request): form = Add_doctorForm() if request.method == "POST": form = Add_doctorForm(request.POST) if form.is_valid(): form.save() d = "" for i in request.POST.getlist("days"): d= str(i)+' '+d print(d) formdata = Doctors.objects.get(id = request.POST.get("id") formdata.days = d … -
how to link two models in one form in CreateView?
There are two models. Attachment must bind to Post. models.py class Post(models.Model): title = models.CharField(verbose_name='Название', max_length=300) slug = models.SlugField(verbose_name='Ссылка', max_length=300, blank=True, db_index=True) category = models.ForeignKey('Category', verbose_name='Категория', on_delete=models.CASCADE) content = models.TextField(verbose_name='Описание') created_by = models.ForeignKey(User, verbose_name='Материал добавил', on_delete=models.SET_DEFAULT, default=1, related_name='post_created_by') updated_by = models.ForeignKey(User, verbose_name='Материал обновил', on_delete=models.SET_DEFAULT, default=1, null=True, related_name='post_updated_by') is_published = models.BooleanField(verbose_name='Опубликовать', default=True) views = models.PositiveIntegerField(verbose_name='Просмотры', default=0, blank=True) time_create = models.DateTimeField(verbose_name='Дата создания', auto_now_add=True) time_update = models.DateTimeField(verbose_name='Дата обновления', auto_now=True) # META author = models.CharField(max_length=255, verbose_name='Автор', blank=True) source = models.URLField(max_length=255, verbose_name='Ссылка на источник', blank=True) def get_absolute_url(self): return reverse('post', kwargs={'cat_slug': self.category.slug, 'slug': self.slug, 'pk': self.pk}) class Attachment(models.Model): post = models.ForeignKey('Post', verbose_name='Прикрепить файл', on_delete=models.SET_NULL, null=True, related_name='post_attachment') link = models.URLField(verbose_name='Основная ссылка', blank=True) meta_link = models.CharField(verbose_name='Информация', max_length=255, blank=True) load = models.PositiveIntegerField(verbose_name='Загрузки', default=0, blank=True) type = models.ManyToManyField('Type', related_name='type_post') version = models.CharField(verbose_name='Версия материала', max_length=255, blank=True) forms.py class PostForm(ModelForm): class Meta: model = Post fields = '__all__' class AttachmentForm(ModelForm): class Meta: model = Attachment fields = '__all__' exclude = ('post',) How to connect them in CreatView in views.py? I just tried different ways, errors came out. I don't understand a little how to make a formsets. -
I am trying make a custom user signup form and getting following error while making this
I am trying to extend the user model from django.db import models # Create your models here. class RegisterUser(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=50, unique=True) phone_number = models.CharField(max_length=20) sector = models.CharField(max_length=50) and tried to create a form for the signup from django.contrib.auth.forms import UserCreationForm from .models import RegisterUser class CreateUserForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = RegisterUser fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email', 'phone_number', 'sector') ** These are the only changes I made I am getting the following error:** raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (username) specified for RegisterUser -
MultipleObjectsReturned: get() returned more than one Post -- it returned 2
This error only happens if multiple users have the same title for their posts. For example, if john has a page with a title 'mypage' this is the error shown if another user has the same title for their page as john. `MultipleObjectsReturned at /john/mypage/update/` get() returned more than one Post -- it returned 2! but if no one else has it, no error is shown when trying to update the post. class PostUpdateView(LoginRequiredMixin, UpdateView): model = Post form_class = PostForm def form_valid(self, form): form.instance.author = self.request.user ##author = current logged in user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post success_url = '/' def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False Model class Post(models.Model): title = models.CharField(max_length=100, default=None) slug = AutoSlugField(populate_from='title', null=True) def get_absolute_url(self): return reverse('post-detail', kwargs={'slug': self.slug, 'author': self.author}) urls urlpatterns = [ path('landingpage/new/', PostCreateView.as_view(), name='post-create'), path('<str:author>/<slug:slug>/', PostDetailView.as_view(), name='post-detail'), path('<str:author>/<slug:slug>/update/', PostUpdateView.as_view(), name='post-update'), path('<str:author>/<slug:slug>/delete/', PostDeleteView.as_view(), name='post-delete'), ] + static(settings.M EDIA_URL, document_root=settings.MEDIA_ROOT) -
Can't display SVG images
I can't manage to display and SVG image in an HTML template. I'm working with Django, and this is how my HTML looks like: <svg><use xlink:href="{% static 'user_template_2/assets/test.svg' %}"></use></svg> The path and the filename are correct, I'm loading other static assets using that same directory. I've already added this to my settings file: import mimetypes mimetypes.add_type("image/svg+xml", ".svg", True) mimetypes.add_type("image/svg+xml", ".svgz", True) Any idea what I might be missing? -
Embed Linux screen Terminal in webpage
I am want to embed Linux screen session to embed in django website. Is there is any way to do embed only specific screen in webpage. -
Django tests fails with <model> has not attribute 'object' error
I have the following two models: class Resource(models.Model): identifier = models.UUIDField(default=uuid.uuid4, unique=True) date_added = models.DateTimeField(default=now) def __repr__(self): return f'Resource: {self.identifier}, Time added: {self.date_added}' class URLResource(Resource): url = models.URLField() def __repr__(self): return f'{self.identifier} URL: {self.url}' When I run the following commands in the django shell, everything works fine: > from user_page.models import URLResource > URLResource.objects.create(url='abc') # outputs: `a3157372-7191-4d70-a4b1-c6252a2a139c URL: abc` > URLResource.objects.get(url='abc') # outputs: `a3157372-7191-4d70-a4b1-c6252a2a139c URL: abc` However, my seemingly trivial test case fails, even though the similar execution succeeds in the django shell: from django.test import TestCase from users.models import CustomUser from .models import Resource, URLResource, Record class URLResource(TestCase): def setUp(self): url_resource = URLResource.objects.create(url='abc') print(repr(url_resource)) def test_url(self): print(repr(URLResource.objects.get(url='abc'))) I get the following error: ====================================================================== ERROR: test_url (user_page.tests.URLResource) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/admin/Desktop/readrrr/user_page/tests.py", line 26, in setUp url_resource = URLResource.objects.create(url='abc') AttributeError: type object 'URLResource' has no attribute 'objects' ---------------------------------------------------------------------- -
configuration has an unknown property 'devDependencies'
When I run my django server and try 'npm run dev', it gives me an error stating that there is no property called devDependencies. Is there something wrong with my JSON file? This is my package.json file: { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development --watch", "build": "webpack --mode production" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.13.13", "@babel/preset-env": "^7.13.12", "@babel/preset-react": "^7.13.13", "babel-loader": "^8.2.2", "react": "^17.0.2", "react-dom": "^17.0.2", "webpack": "^5.28.0", "webpack-cli": "^4.6.0" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.13.0", "@material-ui/core": "^4.11.3", "@material-ui/icons": "^4.11.2", "react-router-dom": "^5.2.0" } } -
Get index info in postgres usin Django ORM
I'm using Postgres with Django and I want to get the info of an index I made on a table, specifically I want to see the size of the index. -
RelatedManager' object has no attribute 'description
I perform request http://167.71.57.114/api2/workout-exercises/3 I want to receive data about WorkoutExercise object number 3 (detail view) Got AttributeError when attempting to get a value for field description on serializer ExerciseSerializer. The serializer field might be named incorrectly and not match any attribute or key on the RelatedManager instance. Original exception text was: 'RelatedManager' object has no attribute 'description'. serializers.py class WorkoutExerciseSerializer(serializers.ModelSerializer): exercises = ExerciseSerializer() class Meta: model = WorkoutExercise fields = ('week', 'exercises') views.py class WorkoutExerciseViewSet(viewsets.ModelViewSet): queryset = WorkoutExercise.objects.all() serializer_class = WorkoutExerciseSerializer http_method_names = ['get', 'post'] models.py class WorkoutExercise(models.Model): workout_program = models.ForeignKey(WorkoutProgram, on_delete=models.CASCADE, related_name='workout_exercises') week = models.PositiveIntegerField(default=1) day = models.PositiveIntegerField(default=1) order = models.PositiveIntegerField(default=1) def save(self, *args, **kwargs): if not self.pk: last_order = WorkoutExercise.objects.all().aggregate(largest=models.Max('order'))['largest'] if last_order is not None: self.order = last_order + 1 return super(WorkoutExercise, self).save(*args, **kwargs) def get_workout_programs(self): return self.workout_program.name def get_exercises(self): pass def __str__(self): return self.workout_program.name class Meta: ordering = ('week', 'day') -
'django.db.models' has no attribute 'StdImageField'
I'm trying to use django-stdimage to resize my picture but i'm getting this error AttributeError: module 'django.db.models' has no attribute 'StdImageField' Model from django.db import models from django.contrib.auth.models import AbstractUser from django.views.generic import TemplateView from django.db.models import Q from cloudinary.models import CloudinaryField from .validators import validate_file_size from stdimage.models import StdImageField class CustomUser(AbstractUser): picture = models.StdImageField(null=True, blank=True, upload_to="images", validators=[validate_file_size], size=(256, 256)) -
How to fetch data from database and show it in bootstrap's modal box ( pop up ) in django respectively?
Technologies I'm using --> Back-end --> Python, Web Framework --> Django, Front-end --> HTML5, CSS3, Bootstrap 4, Database --> SQLite3. What I want --> To display the data of each object in each bootstrap's modal box( popup ). The problem --> Data of the first object is only being shown in all the modal boxes( popups ). Files are as follows: HTML template --> manage_requisition.html 👇 {% extends 'hod_template/base_template.html' %} {% block page_title %} Manage Requisitions {% endblock page_title %} {% block main_content %} <!-- Main content --> <section class="content"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <!-- general form elements --> <div class="card card-primary"> <div class="card-header"> <h3 class="card-title">Manage Requisitions</h3> </div> <!-- /.card-header --> <!-- form start --> <div class="table"> <table class="table"> <tr> <th style="text-align: center;">Action</th> <th>View Requisition</th> </tr> {% for requisition in requisitions %} <tr> <td style="text-align: center; vertical-align: middle;"> {% if requisition.requisition_status == 0 %} <a style="width: 85px;" href="{% url 'supervisor_approve_requisition' requisition_id=requisition.id %}" class="btn btn-success inline" >Approve</a> <a style="width: 85px;" class="btn btn-danger inline" href="{% url 'supervisor_rejected_requisition' requisition_id=requisition.id %}" >Reject</a> {% elif requisition.requisition_status == 1 %} <button class="btn btn-warning" disabled="disabled" data-toggle="modal" data-target="#reply_modal">Approved</button> {% else %} <button class="btn btn-danger" disabled="disabled" data-toggle="modal" data-target="#reply_modal">Rejected</button> {% endif %} </td> <td> <button type="button" class="btn btn-warning" … -
How do I Autocomplete using JSON response
I am making a mock trading website and I need to populate an autocomplete dropbox with options, gotten from a JSON response. Here is some background, I am using Django for the backend and Materialize framework for the front end. And I am getting the JSON response from the IEX cloud API. I am using their search functionality. The problem: When a user enters the name of the company they don't always necessarily know the right symbol as well, so if I can make a drop-down box that makes it easier for them that would be awesome. The solution I envision: As the user types the name of the company it starts to give us autocomplete suggestions just like this: What I need: If you could give me a direction, a starting point, a resource I would be very happy. I have been roaming around the interwebs but I seem to find a solution, so if you can point me in the right direction that would be very much appriciated. -
Insert lat and lon in model fields after user fills in address
Is it possible to call an API (eg. Google Maps API) on submit (or even before submit?) and insert lat and lon values in the model's fields so they are saved to the DB my app is connected to? I want to re-use those values later in a view on the front-end outside the admin to plot them an a map. models.py: from django.db import models from django.db.models import Q class Address(models.Model): street = models.CharField(max_length=100) number = models.IntegerField(null=True) postal = models.IntegerField(null=True) city = models.CharField(max_length=100) country = models.CharField(max_length=100) is_primary = models.BooleanField(null=False) geo_lat = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) geo_lon = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) customer = models.ForeignKey("Customer", on_delete=models.CASCADE, related_name="addresses") class Meta: verbose_name_plural = 'Addresses' constraints = [ models.UniqueConstraint( fields=['customer'], condition=Q(is_primary=True), name='unique_primary_per_customer' ) ] def save(self, *args, **kwargs): if self.is_primary: self.__class__._default_manager.filter(customer=self.customer, is_primary=True).update(is_primary=False) super().save(*args, **kwargs) def __str__(self): return f"{self.street} {self.number}, {self.postal} {self.city}, {self.country}" class Customer(models.Model): name = models.CharField(max_length=100) email = models.EmailField(unique=True) vat = models.CharField(max_length=100) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.name}" -
I don't know why instance is not working in form django
views.py @login_required def put(request, id): question = get_object_or_404(Question, id=id) poll_form = PollForm(request.POST, instance=question) print(poll_form) choice_forms = [ChoiceForm(request.POST, prefix=str( choice.id), instance=choice) for choice in question.choice_set.all()] if poll_form.is_valid() and all([cf.is_valid() for cf in choice_forms]): new_poll = poll_form.save(commit=False) new_poll.created_by = request.user new_poll.save() for cf in choice_forms: new_choice = cf.save(commit=False) new_choice.question = new_poll new_choice.save() return redirect('poll:index') context = {'poll_form': poll_form, 'choice_forms': choice_forms} return render(request, 'polls/edit_poll.html', context) html template {{poll_form.as_table}} {% for form in choice_forms %} {{form.as_table}} {% endfor %} models.py class Question(models.Model): title = models.TextField(null=True, blank=True) created_by = models.ForeignKey(User, null=True, blank=True, related_name="created", on_delete=models.CASCADE) forms.py class PollForm(forms.ModelForm): title = forms.CharField(max_length=333, label='Question') class Meta: model = Question fields = ['title'] class ChoiceForm(forms.ModelForm): text = forms.CharField(max_length=255, label='Choice') class Meta: model = Choice exclude = ('question',) when i inspect the element <td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="title" maxlength="333" required="" id="id_title"></td> fields are empty (but instead it should be filled by existing id questions and choice ) but i see errorlist class i dont know please help me but when i fill edit form and try to update things it worked -
For loop in django templates using Integerfield in model object
I have a model like this: class Testimonial(models.Model): rating = models.IntegerField(_("Rating")) I'm looping over all testimonials in Django templates using one for loop, now how do I display the ratings for each testimonial object. My stars class in HTML looks like this: <ul class="list-unstyled"> <li class="list-inline-item"><i class="fas fa-star"></i></li> <li class="list-inline-item"><i class="fas fa-star"></i></li> <li class="list-inline-item"><i class="fas fa-star"></i></li> <li class="list-inline-item"><i class="fas fa-star"></i></li> <li class="list-inline-item"><i class="fas fa-star-half-alt"></i></li> </ul> How do I solve this issue? -
Implement f-string like magic to pimp Django's format_html()
I would like to pimp format_html() of Django. It already works quite nicely, but my IDE (PyCharm) thinks the variables are not used and paints them in light-gray color: AFAIK f-strings use some magic rewriting. Is there a way to implement this, so that the IDE knows that the variables get used? Related: Implement f-string like syntax, with Django SafeString support -
Send to the frontend what permissions user have
I'm building an app that have React on the frontend and Django on the backend. My problem is that I need to restrict CRUD operations by user permissions. I need to send some information to the frontend Example when I request something to the backend API to receive something like this: { data: [], permissions: [ read: true, write: true, upload: false, delete: false, ] } Can anyone have some idea how to do that? Or is a better way? -
Make edit funcion without conflict on edit booking django
i make bus reservation system which have filtering to prevent double booking on same bus at same date.. here's the code on forms.py : class BookingEditForm(forms.ModelForm): class Meta: model = Booking fields = '__all__' widgets = { 'idbooking': forms.HiddenInput(attrs={'class': 'form-control', 'id': 'id_booking', 'style':'text-transform: uppercase'}), 'BusId': forms.Select(attrs={'class': 'form-control', 'id': 'bus_id'}), 'start' : forms.DateInput(format=('%Y-%m-%d'), attrs={'type': 'date', 'class': 'form-control', 'required':'true'}), 'end_date' : forms.DateInput(format=('%Y-%m-%d'), attrs={'type': 'date', 'class': 'form-control', 'required':'true'}), } def clean(self): start = self.cleaned_data['start'] end_date = self.cleaned_data['end_date'] BusId = self.cleaned_data['BusId'] res_all = Booking.objects.all().filter(BusId=BusId) for item in res_all: if start <= item.start and item.start <= end_date or start <= item.end_date and item.end_date <= end_date: raise forms.ValidationError("Bus already reserved on same date!") Now, i need help to run this filtering on edit function, because that works on create booking but when i try implement on edit, its not work I think there is something to do on idbooking -
How to extract text from an HTML div tag file with BeautifulSoup?
My python code is as below import requests from bs4 import BeautifulSoup flipurl = "https://www.flipkart.com/search?q=realme+7&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=off&as=off" r = requests.get(flipurl) htmlContent = r.content soup = BeautifulSoup(htmlContent,'html.parser') #i scrap flipkart product price price= soup.find_all("div",class_="_30jeq3 _1_WHN1") print(price.get_text()) #**i got this error how i get text:** "ResultSet object has no attribute '%s'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?" % key AttributeError: ResultSet object has no attribute 'get_text'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()? As you can see from the above snippet i have tried to extract all the text but all i get an error and None. please solve this -
Iam a beginner in data mining and Iam using Django for a project. How can i perform social media data mining?
iam a beginner in data mining. Iam working on a project that has to collect data from various social media for predicting events like disease outbreak, sports, etc... using machine learning models I am working on django. how can i collect data from various social media sites(mainly social medias like twitter) at the same time? -
Django- Display queries in Django admin with group, max count and timestamp all together
models.py(App: Article) from django.contrib.auth.models import User class Article(models.Model): # code... url_title = models.CharField(max_length=80, unique=True, db_index=True) HATE_SPEECH = 'HS' SPAM = 'SP' FAKE_INFO = 'FI' REPORT_REASON = ( (FAKE_INFO, 'Fake Information'), (HATE_SPEECH, 'Hate Speech'), (SPAM, 'Spam')) class Report(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) article_id = models.ForeignKey(Article, on_delete=models.PROTECT) user_id = models.ForeignKey(User, on_delete=models.PROTECT) reason = models.CharField(max_length=2, choices=REPORT_REASON) solved_status = models.BooleanField(default=False) date_created = models.DateTimeField(auto_now_add=now) admin.py(App: Article) class ArticleAdmin(admin.ModelAdmin): pass # code... class ReportAdmin(admin.ModelAdmin): list_display = ('id', 'article_id', 'user_id', 'reason', 'solved_status', 'date_created') admin.site.register(Article, ArticleAdmin) admin.site.register(Report, ReportAdmin) In django admin I want to display all these records in such a manner. Unsolved queries should display first (which i am able to achieve using ordering = ['solved_status']) The article which is (i) not solved and (ii) reported highest number of times should come first(Here article a1: because it is reported 3 times. Do NOT consider a2 because in last record, it is considered as solved Highest Number of same reason from same article (Here Hate Speech is coming 2 times, so it should come first and then spam should come) NOTE: Do not consider Spam as 4 times because we have to fulfill condition 2 first. The article which is reported first should display first according to … -
Django's Memcache VS Database Cache. Which is better?
I am trying to develop a site using django framework which might have a mid level traffic and I have hit a wall. I want to include sessions in my pages but to implement session I need to employ caches. There are two different types of cache based sessions as given here. My site will be on only for a certain time in a year during which I expect mid level traffic of say around 200 visitors per day. What kind of cache system should I use for this? I understand that database cache means that every time a user visits my site, the backend will have to search the database which means more processing power, but for my requirements I think this would not matter so much. Any help and advice appreciated -
Django Rest Framework Include ManyToMany attributes in slash with all features
I'm using Django Rest Framework, here's my code: models.py class Course(models.Model): name = models.CharField(max_length=200) class Formation(models.Model): name = models.CharField(max_length=200) courses = models.ManyToManyField(Course, blank=True) serializers.py class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = '__all__' class FormationSerializer(serializers.ModelSerializer): class Meta: model = Formation fields = '__all__' courses = CourseSerializer(many=True) views.py class FormationView(viewsets.ReadOnlyModelViewSet): queryset = Formation.objects.all() serializer_class = FormationSerializer class CourseView(viewsets.ReadOnlyModelViewSet): queryset = Course.objects.all() serializer_class = CourseSerializer urls.py router = routers.DefaultRouter() router.register('formations', views.FormationView) router.register('courses', views.CourseView) urlpatterns = [ path('api/', include(router.urls)), ] When I use http://localhost:8000/api/formations/{id} it works just fine, and I can benefit from all its features (like PATCH), what I can't do though is http://localhost:8000/api/formations/{id}/courses, so also no localhost:8000/api/formations/{id}/courses/{id} and no features. I feel like the solution is not that far, or complicated So What is the solution for this? -
Item id and order_variants id stored as null while creating an order in django rest framework
I created an order-create API where I am creating order by creating order items objects and billing details objects at the same time. Everything was working fine a few days back, but when I try today to call the order api from the postman, item id and order_variants are stored as null in the database, although I am passing item id and variants id and the objects exist as well. I am sending raw JSON data like this. I have sent the item id and order_varaints id as shown above. But the result I get is null as shown below. My models: class Order(models.Model): ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) #items = models.ManyToManyField(OrderItem,blank=True, null=True,related_name="order_items") #start_date = models.DateTimeField(auto_now_add=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) total_price = models.CharField(max_length=50,blank=True,null=True) #billing_details = models.OneToOneField('BillingDetails',on_delete=models.CASCADE,null=True,blank=True,related_name="order") def __str__(self): return self.user.email class OrderItem(models.Model): #user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants,on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) total_item_price = models.PositiveIntegerField(blank=True,null=True,) def __str__(self): return f"{self.quantity} items of {self.item} of {self.order.user}" class Meta: verbose_name_plural = "Cart Items" ordering = ('-id',) class BillingDetails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order = models.OneToOneField(Order, …