Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework non_atomic_requests based on HTTP method
I am using Django Rest Framework and its class-based view, with database connection set to ATOMIC_REQUESTS=True. To optimize the application, I would like to have it so that only PUT and POST requests are under transaction, but not GET. Since I have ATOMIC_REQUESTS on, the documentation says to use the decorator on the dispatch() method in the view. So this is what I tried: class MyView(APIView): def get(): print("I am in a transaction:", not transaction.get_autocommit()) return Response({}) def post(): print("I am in a transaction:", not transaction.get_autocommit()) return Response({}) def put(): print("I am in a transaction:", not transaction.get_autocommit()) return Response({}) def dispatch(self, request, *args, **kwargs): """Override dispatch method and selectively apply non_atomic_requests""" if request.method.lower() == "get": return self.non_atomic_dispatch(request, *args, **kwargs) else: return super().dispatch(request, *args, **kwargs) @transaction.non_atomic_requests def non_atomic_dispatch(self, request, *args, **kwargs): """Special dispatch method decorated with non_atomic_requests""" return super().dispatch(request, *args, **kwargs) This does not work, since the get method still reports itself as under transaction, however, if I switch the decorator to look like this: ... @transaction.non_atomic_requests def dispatch(self, request, *args, **kwargs): if request.method.lower() == "get": return self.non_atomic_dispatch(request, *args, **kwargs) else: return super().dispatch(request, *args, **kwargs) def non_atomic_dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) ... This works, though obviously it's not … -
Why are data from json and inputted string different in my REST API SERVER?
I made a rest api with django. They are django server codes in urls.py urlpatterns = [ path('getchatid/<str:client_pk>/', giveCHAT_ID), ] And my client code by python give requests to my server with these codes.. def getChatid(pk): url = BASE_URL_FOR_GET_CHAT_ID + pk response = requests.get(url) if response.status_code == 200: temp = response.json()['chat_id'] modifyJson('BASIC_INFO', 'CHAT_ID', str(temp)) return True else: return False and json_data = readjson(isfileindoc()) client_pk = json_data["BASIC_INFO"]["PK_CLINET"] getChatid(client_pk) so I tested the code, getChatid like this ('1234QWER is a example of client_pk data') getChatid('1234QWER') it works in server, but It doesn't work with data read from json file... and I tried like this... but it didn't work temp = client_pk.replace('\t', '').replace('\n', '').replace(' ', '') getChatid(temp) how can i fix it? -
How do I achieve the equivalent of LEFT JOIN in Django - Nested Serializers in Django
I have the model specification below. MailingList is a reference table/model between Customer and Email. It has several other attributes, that will be useful in applying filters. My goal is to apply some filters then return serialized results. The results should include the customer's orders. models.py class Email(models.Model): name = models.CharField(max_length=300, unique=True) class Item(models.Model): name = models.CharField(max_length=50) class Customer(models.Model): passport_number = models.CharField(max_length=20, unique=True) name = models.CharField(max_length=20) class Order(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) class MailingList(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) email = models.ForeignKey(Email, on_delete=models.CASCADE) serializer.py class CustomerSerializer(serializers.ModelSerializer): passport = serializers.CharField(source='customer.passport_number') customer_name = serializers.CharField(source='customer.name') # I want to add the orders for each customer too class Meta: model = MailingList fields = ['passport', 'customer_name'] views.py class CustomerViewSet(viewsets.ViewSet): def list(self, request): queryset = MailingList.objects.filter(some_filters).prefetch_related('customer') serializer = CustomerSerializer(queryset, many=True) return serializer.data Here's the response I'm currently getting [ {passport: 48, name: "Collins"}, {passport: 32, name: "Kate"} ] And here's the response I'm trying to get [ {passport: 48, name: "Collins", orders: {"1": "Hp EliteDisplay", "2": "Sony a7iii"}}, {passport: 32, name: "Kate" orders: {}} ] QUESTION: How do I embed orders within the same response? -
Notion type table save to database
As some of you may be aware, notion has the ability for users to create their own table with speicific fields. With the project that I am interested in doing, I am finding it hard to find a tutorial or for somebody to have the same question as me. What I am asking is: How would I go about creating a table that the end-user can create and add different dynamic colums to a table and for that to save on the database??? I have tried using a chrome web extension to show me the technologies that notion used to maybe get some idea but to be honest, I have none. Anyone with any answer will be much appreciated. Thanks in advance :) -
What is the correct way to post images on django-rest-framework server using javascript?
I have a POST API view that accepts an image and a style sting and returns a styled image. It works on postman just fine but I cannot get it to work using fetch API. Serializer: class GetImageSerializer(serializers.Serializer): image = serializers.ImageField() style = serializers.CharField() DRF view: class PostImage(APIView): serializer_class = GetImageSerializer parser_classes = [MultiPartParser] def post(self, request, format=None): print(request.data) # Debug img = request.data.get('image') # Process response = FileResponse(img) return response The fetch call: json = {} json["image"] = this.state.image json["style"] = "models\\wave\\wave200.pth" console.log("sending --- ", json) //debug fetch('/style_transfer/style/', { headers: { "Content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" }, body: json, method: "POST" } ).then(response => { if (!response.ok) { console.log("couldn't fetch image") } return response.json() }) .then(data => { console.log("fetched data") console.log(data) outputs of console logs. This shows that the correct data is in json dictionary But the data isn't received by DRF server. The print(request.data) from the view returns <QueryDict: {}>. The strange part is that the same code works with postman. Things I've tried: Remove the headers from fetch request - This throws unsupported media type error Set content-type to "application/json" - This reads the string parameter but image key is empty. this is what request.data looks like {'image': {}, … -
django chart.js can't use {{% for loop%}}
I am a newbie to django, I don’t know why I can use for loop in javascript in other people’s teaching, but I can’t use for loop in javascript like this. Hope someone can tell me why. enter image description here -
Django Default user model TypeError at /auth/users/ create_user() missing 1 required positional argument: 'username'
When I request to create a user using djoser Endpoint /user/. But it says create_user() missing 1 required positional argument: 'username' I am using postman to post the request and I am passing the username as you can see below: I don't know where the problem lies. I have also changed "username" to "name" but it did not work. Any help would be highly appreciated .Thank you very much 😊❤️❤️❤️. I will show you what you will ask me to show. -
Unknown error while retrieving django queryset objects from redis
In the below code snippet, I am trying to bring the cached objects from redis , while doing it facing the below error The use case is caching the top 30 comment objects at the 1st API call , so the when the API is called for 2 nd time, the cached objects will be passed to serialzers , avoiding the querysets Caching the comments objects featured=StockUserComments.objects.filter(some condition) qs=StockUserComments.objects.filter(some condition) latest=StockUserComments.objects.filter(some condition) all =list(chain(featured,qs,latest)) redis_client.set("feeds:top_comments", str(all[:30]),ex=1800) retrieving the objects top_comments = redis_client.get("feeds:top_comments") if top_comments: print("from cache") all = ast.literal_eval(top_comments.decode("utf-8")) error Traceback (most recent call last): File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "E:\stocktalk-api-platform\apps\stock_dashboard\views.py", line 748, in get all = ast.literal_eval(top_comments.decode("utf-8")) File "C:\Users\Fleetstudio\AppData\Local\Programs\Python\Python38\lib\ast.py", line 59, in literal_eval node_or_string = parse(node_or_string, mode='eval') File "C:\Users\Fleetstudio\AppData\Local\Programs\Python\Python38\lib\ast.py", … -
Django queryset filter by 6 hour interval
I have a model class TestRequest(models.Model): created_at = models.DateTimeField(auto_now_add=True) is_accepted = models.BooleanField(default=False) What i want is to send an email to admin if the TestRequest is not accepted in every 6 hours once request created. How can i query the data in the cron function (which is running every minute) where i can fetch all the TestRequest which fall in the 6 hour interval and email to admin. -
Store Auto Generated Username into Database DJango
I am creating a registration form that accepts the end-user's Firstname, Lastname, email, and password. the program is designed to auto-generate a username. I have created a function that auto generates a unique username; however, I am new to Django and unsure how to get my auto-generated username to store into the database along with the user's info. Currently, the program is storing the user's manually input info. -
display data in multiple columns with for loop
I'm sure this is a simple answer but for the life of me I cant figure / find out how to go about this. I want to display blog posts from my data base in three equal columns. When I start looking into the bootstrap docs this is the code given. <div class="container"> <div class="row"> <div class="col-sm"> One of three columns </div> <div class="col-sm"> One of three columns </div> <div class="col-sm"> One of three columns </div> </div> </div> However If I go to implement it I dont understand how i would be able to put the for loop on it without it repeating everything 3 times. IE: {% for post in posts.all %} <div class="row"> <div class="col-sm"> <img class="post-image" src="{{ post.image.url }}" /> </div> <div class="col-sm"> <img class="post-image" src="{{ post.image.url }}" /> </div> <div class="col-sm"> <img class="post-image" src="{{ post.image.url }}" /> </div> </div> {% endfor %} If you could please point me in the right direction on how to go about this it would be very much appreciated bootstrap is not a requirement. -
Django deployment Failed to load resource: the server responded with a status of 404 (Not Found)
I have some product pictures uploaded in media folder that displays fine in development server, but after deployment I receive the 404 ressource not found error. In settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'node_modules')] STATIC_ROOT = os.path.join(BASE_DIR, 'productionStatic') STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' In urls.py from django.contrib import admin from django.urls import path from index import views from index.views import indexPage, hdnytorv from webshopRestaurant.views import hd2900_webshop_Main, AddressCheckForDeliverability, ChangeItemQuantity from webshopCustomer.views import TakeawayCheckout, totalPriceDeliveryPossible, DeliveryForm, PickUpForm, localDeliveryCheckoutAddressCheck, Payment, PaymentComplete from django.conf import settings from django.conf.urls.static import static admin.autodiscover() urlpatterns = [ path('admin/', admin.site.urls), path('', indexPage.as_view(), name = 'index'), path('hdnytorv', hdnytorv.as_view(), name='hdnytorv'), path('hd2900', views.hd2900.as_view(), name='hd2900'), path('hd2900_takeaway_webshop', hd2900_webshop_Main.as_view(), name="hd2900_takeaway_webshop"), path('check-address-for-deliverable', AddressCheckForDeliverability.as_view()), path('changeItemQuantityInBasket', ChangeItemQuantity.as_view()), path('isPriceAboveDeliveryLimit', totalPriceDeliveryPossible.as_view()), path('hdbynight', views.hdbynight.as_view(), name='hdbynight'), path('takeawayCheckout', TakeawayCheckout.as_view()), path('deliveryFormCheckout', DeliveryForm.as_view()), path('pickupFormCheckout', PickUpForm.as_view()), path('local_delivery_checkout_is_address_deliverable', localDeliveryCheckoutAddressCheck.as_view()), path('localDeliveryPayment', Payment.as_view()), path('paymentComplete', PaymentComplete.as_view()), ] #When in production medida url must always be added to urlpatterns #if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) To display the product in view I have in my html template <img class="card-img embed-responsive-item" src="{% get_media_prefix %}{{ item.product.image_path }}" alt="{{item.meta_description}}"> The pictures are uploaded to this location django_project_folder/media/productImages. I have assured that it is owned by www-data group and also media and all … -
function create_user in CustomUserManager didn't work
I create a custom user model and manager but the create_user function in manager doesn't work. what is my fault? this is my model: class User(AbstractUser): email = models.EmailField(null = True, blank = True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) phone_number = models.BigIntegerField(unique=True) is_owner = models.BooleanField(default=False) is_advisor = models.BooleanField(default=False) name = models.CharField(max_length=40, null = True, blank = True) image = models.ImageField(blank = True, null=True) data_join = models.DateTimeField(default = timezone.now) code_agency = models.IntegerField(null=True, blank=True, default=0) opt = models.IntegerField(null = True, blank = True) is_verified = models.BooleanField(default = False) USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = [] objects = UserCustomManager() def __str__(self): return str(self.phone_number) class Meta: verbose_name = 'user' verbose_name_plural = 'users' and this is my manager: class UserCustomManager(BaseUserManager): use_in_migrations = True def _create_user(self, phone_number, **extra_fields): if not phone_number: raise ValueError('The given phonenumber must be set') print(""" ======================== ======================== ======================== """) user = self.model(phone_number=phone_number, username=phone_number, **extra_fields) user.set_password("green") # Token.objects.create(user=user) user.save(using=self._db) return user def create_user(self, phone_number, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) digits = "0123456789" print(""" ======================== ======================== ======================== """) OTP = "" for i in range(4) : OTP += digits[math.floor(random.random() * 10)] extra_fields.setdefault('opt', OTP) return self._create_user(phone_number, **extra_fields) def create_superuser(self, phone_number, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser … -
Angular app keeps saying _user is not defined
I'm building a chat app with Angular and Django using the get stream tutorial. https://getstream.io/blog/realtime-chat-django-angular/ However, I'm trying to run the app to test the join page but it keeps saying property not defined in the constructor which is from the state.service.ts file. import { Injectable } from '@angular/core'; export declare interface User { token: string; apiKey: string; username: string; } @Injectable({ providedIn: 'root', }) export class StateService { constructor() {} private _user: User; get user(): User { return this._user; } set user(user: User) { this._user = user; } } -
i got an error stating that === Cannot assign "'12'": "Cart.product" must be a "Product" instance. please do help me out in solving the issue
I have attached an image of my code where you can find the add-to-cart function and the error is on line===23 -
Django google books API totalItems is changing
I am creating an application that retrieves data from the google books API. At the very beginning I download a number of books from JSON ["totalItems"] and iterate through the for loop, calling the API in order to get another 40 items. The problem is that the number of books increases and decreases during iteration, so when, for example, on a 550 book, I get a list index out of range error. Anyone please help me download all the books? My request looks like this: requests.get(f'https://www.googleapis.com/books/v1/volumes?q={search}\ &maxResults=40&startIndex={end_range}') end_range is increased by 40 each time data is downloaded. -
Go import from specific branch github in the same repository where it is hosted
I have a repository with a golang project in github, I need to import in a module a specific branch, to make relevant modifications. It looks like this: package events_entity import ( "github.com/repository/utils/date_utils" "github.com/repository/utils/utils/error_utils" "github.com/repository/utils/utils/hour_utils" "strconv" "strings" ) The importation is always done directly from the master. I just need this module to import from a different branch. Thanks!!! -
Unable to lookup 'placedorder' on Restaurants or RestrauntsAdmin
My error : Unable to lookup 'placedorder' on Restaurants or RestrauntsAdmin i am getting this error in admin panel, i havent entered any data in placed order yet and neither in restaurants class Restaurants(models.Model): name = models.CharField(max_length=50, blank=False) address = models.CharField(max_length=50, blank=False) city = models.ForeignKey(City, on_delete=models.CASCADE) mob_no = models.IntegerField() opening_time = models.TimeField() closing_time = models.TimeField() website = models.URLField(blank=True) cover = models.ImageField(upload_to='restraunts/cover') # Create your models here. class PlacedOrder(models.Model): order_id= models.CharField(max_length=255) restraunt = models.ForeignKey(to='restaurants.Restaurants', on_delete=models.CASCADE) order_time = models.TimeField( auto_now_add=True) estimated_delivery_time = models.TimeField() actual_delivery_time = models.TimeField() food_ready_time = models.TimeField() total_price = models.DecimalField(max_digits=12, decimal_places=2) -
Custom User Primary Key - Django
I have a Django website and a format similar to google sheets in which people can add data and it shows up in a row. To the left is the number associated with that row of data. Normally I used pk which worked great because when one data row was deleted no other ones changed. Now I have 2 users and I'm separating the data based on ForeignKey fields in all of my models. The problem with this is, for example, User1 adds 1 row of data then User2 adds one row of data then User1 adds another row of data, then when User1's data is being displayed it will show 2 rows labeled 1 and 3. I need them to be specific to the user and in numerical order. It is as if I need a separate pk for each user in the same model. I temporarily fixed this by {{ forloop.revcounter }} in the forloops of the rows. This now keeps the row number in numerical order and specific to the user. The problem is that if User1 now deletes the first data row labeled #1 then now the table only shows 1 row and the data row … -
Ordering by multiple fields
I'm wanting to order a queryset based on a couple of different related fields Models.py class Appointment(models.Model): start_time = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) class Event(models.Model): start_time = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) class Job(models.Model): event = models.ForeignKey(Event, on_delete=models.SET_NULL) appointment = models.ForeignKey(appointment, on_delete=models.SET_NULL) views.py qs = Job.objects.all().order_by('event__start_time','appointment__start_time') Is this the correct way to do this? Will this always order all of the jobs in the correct order based on the associated star time? Thanks! -
The view basket.views.basket_remove didn't return an HttpResponse object. It returned None instead
Can someone explain me why am i getting this error? I am creating online store in which basket functionality depends on sessionid in cookies. Look, I have a function basked_add on every product in store, which adds specified product to basket and it works correctly without any issues. I have also a function basket_delete in basket to remove specified product from basket, and somehow it doesn't work correctly. And this is the main reason why i made this question. Function basket_delete is called by JQuery like that (equal to basked_add): 1. basket.html $(document).on('click', '#remove-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "basket:basket_delete" %}', data: { productid: $('#add-button').val(), csrfmiddlewaretoken: "{{csrf_token}}", action: 'post', }, success: function (json) { }, error: function (xhr, errmsg, err) {} }); }) 2. basket > urls.py app_name = 'basket' urlpatterns = [ path('', views.basket, name='basket'), path('add/', views.basket_add, name='basket_add'), path('delete/', views.basket_delete, name='basket_delete'), ] 3. Then function is getting executed basket > views.py from django.http.response import JsonResponse from basket.basket import Basket def basket_delete(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) basket.delete(product=product_id) response = JsonResponse({'Success': True}) return response basket > context_processors.py from .basket import Basket def basket(request): return {'basket': Basket(request)} basket > basket.py class … -
GET http://localhost:3000/product/[object%20Object] 404 (Not Found) [object%20Object]:1
I am trying to fetch image data from django using api calls, redux state is updated successfully with api call data's But the image is not loading on the page Its giving below error in console and in python terminal Not Found: /product/[object Object] [31/Jul/2021 14:44:36] "GET /api/products/image/7 HTTP/1.1" 301 0 [31/Jul/2021 14:44:36] "GET /product/[object%20Object] HTTP/1.1" 404 2724 productAction.js export const listProductImage = (id) => async (dispatch) => { try{ dispatch({ type: PRODUCT_IMAGE_REQUEST }) const {data} = await axios.get(`http://127.0.0.1:8000/api/products/image/${id}`) dispatch({type: PRODUCT_IMAGE_SUCCESS, payload: data}) }catch(error){ dispatch({ type: PRODUCT_IMAGE_FAIL, payload: error.response && error.response.data.detail ? error.response.data.detail : error.message, }) } } productReducers.js export const productImagesReducers = (state={pImage:[]}, action) => { switch(action.type) { case PRODUCT_IMAGE_REQUEST: return {loading:true, pImage:[] } case PRODUCT_IMAGE_SUCCESS: return {loading:false, pImage:action.payload } case PRODUCT_IMAGE_FAIL: return {loading:false, error: action.payload } default: return state } } ProductImageGallery.js (Template) Dispatching Code const dispatch = useDispatch() const ProductImageGallery = ({ match, productID }) => { const dispatch = useDispatch() const productImage = useSelector(state => state.productImage) const {pImage} = productImage useEffect(()=>{ dispatch(listProductImage(productID)) }, [dispatch, productID]) } models.py class Product(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200,null=True,blank=True) image = models.ImageField(null=True,blank=True) brand = models.CharField(max_length=200,null=True,blank=True) category = models.CharField(max_length=200,null=True,blank=True) description = models.TextField(null=True,blank=True) rating = models.DecimalField(max_digits=7, decimal_places=2,null=True, blank=True) numReviews = … -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/hello only admin/ path is defined
i am following the django instructions to build a web application hello i have done everthing after the document but this happens Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/hello Using the URLconf defined in PythonWeb.urls, Django tried these URL patterns, in this order: admin/ The current path, hello, didn’t match any of these. there must be another path as hello/ this is my code: views.py/hello: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello.") urls.py/pythonweb(my app): from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('hello/', include('hello.urls')) ] urls.py/hello: from django.urls import path from . import views urlpatterns = [ path('', views.index, name =('index')) ] settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello/', ] -
create user function doesn't work in UserCustomManager django
I write a custom user and UserCustomManager but my user don't create. this is my code of models and UserCustomManager: class UserCustomManager(BaseUserManager): use_in_migrations = True def _create_user(self, phone_number, **extra_fields): if not phone_number: raise ValueError('The given phonenumber must be set') user = self.model(phone_number=phone_number, username=phone_number, **extra_fields) user.set_password("default") Token.objects.create(user=user) user.save(using=self._db) return user def create_user(self, phone_number, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) digits = "0123456789" OTP = "" for i in range(4) : OTP += digits[math.floor(random.random() * 10)] extra_fields.setdefault('otp', OTP) return self._create_user(phone_number, **extra_fields) def create_superuser(self, phone_number, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(phone_number, **extra_fields) class User(AbstractUser): email = models.EmailField(null = True, blank = True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) phone_number = models.BigIntegerField(unique=True) is_owner = models.BooleanField(default=False) is_advisor = models.BooleanField(default=False) name = models.CharField(max_length=40) image = models.ImageField(blank = True, null=True) data_join = models.DateTimeField(default = timezone.now) code_agency = models.IntegerField(null=True, blank=True, default=0) otp = models.IntegerField(null = True, blank = True) is_verified = models.BooleanField(default = False) USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = [] objects = UserCustomManager() def __str__(self): return str(self.phone_number) class Meta: verbose_name = 'user' verbose_name_plural = 'users' about user.set_password("default") it is ok and I wanna my custom … -
customize django model meta ordering option
I want to set ordering according to condition something like this. if self.name_format == "First name Last name": class Meta: ordering = ['first_name', 'last_name'] elif self.name_format == "Last name First name": class Meta: ordering = ["last_name","first_name"] elif self.name_format == "Last name, First name": class Meta: ordering = ["last_name","first_name"] else: class Meta: ordering = ["first_name","last_name"] How can i achieve that?