Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django restrict foreign key to common order
Below is an extract from my models.py. For the foreign key ce_hostname I am getting the options to include all ce_hostnames that exist within the database. What I actually want is the ce_hostname which only share the same order_reference. How can I achieve this? class Cx_Base(models.Model): order_reference = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) #Order reference cx_hostname = models.CharField(max_length=15, validators=[CX_HOSTNAME_REGEX]) #Hostname of router i.e. PENNER-DCNCE-01. Always required. ce_hostname = models.ForeignKey(Ce_Base, null=True, on_delete=models.CASCADE) #Hostname of router in which the module will be inserted. -
DRF, Firebase FCM. Sending push notifications
I am creating a DRF project and want to implement sending push notifications to devices. I have configured firebase in Django settings. But after that I faced a problem as I can't send test notification even from admin, I get an error: enter image description here I understand that FCM registration token is required, but there is no way I can get it on backend side. Please advise if anyone has come across how is it possible to generate registration token on backend. -
Django- How can I allow only a set number of duplications with UniqueConstraint?
I'm making a webpage - a rental place that can rent movies, music cd's and books. I've created a model of cd - class Cd(models.Model): cd_band=models.CharField(max_length=100) cd_title=models.CharField(max_length=100) CD_GENRE= ( ('POP', "POP"), ("HIP", "Hip-Hop"), ("ROC", "Rock"), ("BLU", "Blues"), ("SOU", "Soul"), ("COU", "Country"), ("JAZ", "Jazz"), ("CLA", "Classical music"), ) cd_genre=models.CharField(max_length=3, choices=CD_GENRE) cd_length=models.DurationField() cd_rental=models.ForeignKey(Rental, on_delete=models.CASCADE, default=1) def __str__(self): # return self.cd_title, '\n', self.cd_band, '\n' return "{} {} {}".format(self.cd_band,self.cd_title,self.cd_genre) But there is a rule that I have to apply here: -One band can offer cd's in up to 2 genres. So let's say I create a cd of Band1 - Band1 can have cd's in only 2 genres - f.e rock and blues. I have no idea how to implement that. I'm thinking about making a constraint, but I don't know what condition to implement: UniqueConstraint.condition(fields=['cd_band','cd_genre'],condition=??????, name='unique_cd') I've also thought of restructurizing my entire database - making a separate classes for bands and music genres, and then linking it with foreign keys, setting up validators. I think it should work, but I'd have to put in so much work. Is there any other way of doing it? -
Please help me to host django project [closed]
Please help me to know how to host a django. https://i.stack.imgur.com/VmCkz.jpg /home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/core/wsgi.py File line 24 , in setup " /home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/init.py " , apps.populate ( settings . INSTALLED APPS ) line 91 , in populate File " /home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/apps/registry.py " , app_config AppConfig.create ( entry ) ) File " /home/atmadevrt99/.virtualenvs/test/lib/python3.7/site-packages/django/apps/config.py " , line 239 , in create " % s must supply a name attribute . " % entry ********************************** you're seeing -
DRF - make query parameter's key case insensitive
is it possible in DRF to make url query keys case insensitive. food_id = self.request.query_params.get("food_id") get value of food_id even if it is passed as FOOD_ID or food_ID and etc. Thank you in advance. -
Django Access to font gives origin has been blocked by CORS policy:
I have been trying to load fonts in my django html template but I am always seeing this error. Access to font at 'https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Bold.woff2' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. small part of my html code is here. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> <style> @font-face { font-family: 'Noah-Medium'; src: url( 'https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.eot'); src: url('https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.eot?#iefix') format('embedded-opentype'), url('https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.woff2') format('woff2'), url('https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.woff') format('woff'), url('https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.ttf') format('truetype'), url('https://inson.s3.eu-central-1.amazonaws.com/fonts/Noah-Medium.svg#Noah-Medium') format('svg'); font-weight: 500; font-style: normal; font-display: swap; } my CORS config are here. CORS_ALLOWED_ORIGINS = ["http://127.0.0.1:8000"] CORS_ALLOW_HEADERS = list(default_headers) + [ "user-id", "phone-number", ] Any reason for the issue above? -
Is a heroku hobby dyno and hobby basic postgres a fixed monthly cost or can it become variable?
I'm interested in purchasing a heroku hobby dyno and hobby basic postgres for deploying my django app as it seems they are fixed prices which means I would have predictable pricing. My concern however is that since I am an amateur, I am worried about accidentally attracting a large bill which seems to happen with people using other modern deployment platforms. The cost should be $16 US per month. I get confused because it says charges are based on usage. Hasn't the price already been provided as a fixed cost? I simply want to deploy my django mvp web app and not have any surprise costs regardless of traffic or whatever could possibly incur extra charges. I'm quite confused can anyone help? -
Django-PayPal: I have 3 models and 3 signal receiver functions, but I’m unable to specify which should be called when a payment is received
I am using Django-Paypal to receive payments for 3 different services. Each service has a separate model (say, Service1, Service2 and Service3) but all are within the same app ‘payments’. I need to update the payment status of the correct model to ‘paid=True’ after receiving payment for the corresponding service. I have 3 payment processing views (each per service) which are working well, as all payments are completed successfully. Similarly, I have created 3 signals/receiver functions (each per model) and placed them in signals.py. When I test one signal at a time, it works well. The payment status is successfully updated to ‘paid=True’. However, when I include all the three signals in signals.py, things stop working. I noted that each time a payment is received, the first 2 receiver functions are fired, leading to an error. See the code at the bottom How do I specify which receiver function should be called when a payment is received from a specific model? Or which is the best way to implement the above successfully? When I am using inbuilt signals such as pre-save, it is possible to specify the model to be updated by adding the sender at the decorator e.g. @receiver(pre-save, … -
django allauth sign up error showing csrfmiddlewaretoken= in url
I am working on a project. I am using django allauth for authentication and I have properly configured the installation and application of django allauth. Login is working properly but when I go to signup form is takes the input but nothing happens on the screen but a little change appears on the url it shows : localhost:8000/accounts/signup/csrfmiddlewaretoken=... -
Django filter related objects use ORM
Imagine that, I have A Model and B Model. Class A (models.Model): a_name = models.CharField(max_length=100) Class B (models.Model): b_name = models.CharField(max_length=100) a_name = models.ForeignKey(A, on_delete=models.CASCADE, to_field="a_name", db_column="a_name") Then, I want to get A , and every A will have all related B A.filter(a_name="a_name").all() But I also want to filter B by b_name when I get the A result above, How can I do that? -
Objects don't upload the object in DB
I am trying to upload the object in DB, using django, but nothing happened. I run the command makemigration, migrate. admin.py from .models import Product admin.site.register(Product) models.py class Product(models.Model): user = models.OneToOneField(User, null = True, on_delete=models.CASCADE) #data = models.DateTimeField(verbose_name='date joined', auto_now_add=True) productC = ( ('apple', 'apple'), ('water', 'water'), ('tomato', 'tomato'), ) productChoose = models.CharField(max_length=10, blank=False, null= False, choices = productC) numbers= models.PositiveIntegerField() def __str__(self): return f"{self.user}" forms.py class ProductForm(forms.ModelForm): class Meta: model= Product fields =['productChoose', 'numbers',] productC = ( ('apple', 'apple'), ('water', 'water'), ('tomato', 'tomato'), ) widgets = { # 'data': forms.DateTimeField(attrs= {'class': 'form-control'}), 'productChoose': forms.Select(choices= productC, attrs= {'class': 'form-control'}), 'numbers': forms.NumberInput(attrs= {'class': 'form-control'}), } def clean_productChoose(self): if self.is_valid(): productChoose=self.cleaned_data['productChoose'] return productChoose def clean_numbers(self): if self.is_valid(): numbers=self.cleaned_data['numbers'] return numbers view.py def training_view(request, *args, **kwargs): if not request.user.is_authenticated: return redirect('/login') context = {} if request.method=="POST": products=ProductForm(request.POST, instance = request.user) if products.is_valid(): products.save() return redirect('/home') messages.info(request, 'Your training has been send with success!') else: products=ProductForm(instance = request.user) context['training_form']= prodcuts return render(request, 'product.html', context) product.html {% block content%} <form method="POST" action="."> {% csrf_token %} <h1>Products </h1> <div class="container"> {% csrf_token %} <p> <label for="productChoose"><b>Product </b></label> {{products.productChoose}} </p> <p> <label for="numbers"><b>Numbers: </b></label> {{training_form.numbers}} </p> <button type="submit" name="submit" > Submit </button> </div> </form> {% endblock%} … -
Is there a way to send messages from localhost to google [less secure]?
this question doesn't exist because there is new news about sending messages from Django using localhost to google. I know that to send messages from localhost to google I should launch the "less secure" button in google but it turns out this property is no longer available by google as you can see from the following link: https://support.google.com/accounts/answer/6010255?hl=en&utm_source=google-account&utm_medium=profile-less-secure-apps-card now I need to test my SMTP server if it was working or not by Django and if it was sending a message to google so, How can I accomplish that task by localhost in that case? -
How to serialize multi object in django?
I used ajax to fetch data from database. How can i fetch objects and send them? views.py def fetchdata(request): if request.method == 'GET': val1 = request.GET['param1'] val2 = request.GET['param2'] obj = Reserve.objects.filter(~Q(con__title = val1 ), dt__title=val2 ).values('dt__title','con__title') ser_instance = serializers.serialize('json', [obj,]) return JsonResponse({"instance": ser_instance}, status=200) else: return HttpResponse("Request method is not a GET") con and dt are foregn keys fields. -
Django nested viesets on router
In my urls.py file in some app i have the following code: from rest_framework import routers from .viewsets import (JournalViewSet, StatisticViewSet, FuelLogViewSet, MoveLogViewSet, RestLogViewSet, WinLogViewSet, GreatfulLogViewSet) router = routers.DefaultRouter() router.register(r'journal', JournalViewSet) router.register(r'journal/statistic', StatisticViewSet) router.register(r'journal/fuel', FuelLogViewSet) router.register(r'journal/move', MoveLogViewSet) router.register(r'journal/rest', RestLogViewSet) router.register(r'journal/win', WinLogViewSet) router.register(r'journal/greatful', GreatfulLogViewSet) urlpatterns = router.urls All vievsets above are not something specific, and use only serializer_class and queryset. Swagger generate correct scheme, but DRF says, that i have no POST method allowed (in viesets i actually have) and when i try to open url like 127.0.0.1:8000/journal/win, drf return scheme for journal. When registers were not nested like router.register(r'move', MoveLogViewSet), I get all correct. I understand, that DRF maybe don't provide nested routs like I have. What should I do? -
How to get my messages to show on Django for a registration form?
I am creating a registration form using the Django framework and I want to display some error messages to the user if they enter the wrong confirm password, or an email already taken etc. I have written the code and it seems to be working, but I can't seem to get the messages to show on screen upon redirecting to back to registration page if there is an error in the form. I have imported messages on the views.py page (from django.contrib import messages) and I think my setting.py is all configured correct: setting.py Here is my views.py code: def register(request): if request.method == "GET": register_form = RegisterForm() return render(request, "main/register.html", { 'form': register_form }) else: register_form = RegisterForm(request.POST) if register_form.is_valid(): first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] confirm_password = request.POST['confirm_password'] if password == confirm_password: if User.objects.filter(email=email).exists(): messages.info(request, 'Email or user name Already taking') return redirect('register') elif User.objects.filter(username=username).exists(): messages.info(request, 'username is taken') return redirect('register') else: User.objects.get_or_create(username=username, first_name=first_name, last_name=last_name, email=email, password=password) return redirect('main/login.html') else: messages.error(request, 'Password Not Match') return redirect('register') #return redirect ('/') else: return render(request, 'main/login.html') and this is my register.html form: <form action="{% url 'register' %}" method="POST"> {% csrf_token %} <fieldset> … -
Django multiupload error: 'list' object has no attribute 'name'
I'm trying to use multiupload in django form for upload several images at once. I'm using django ModelForm but when i'm calling form.is_valid() in function-base view or using generic.FormView, i'm getting 'list' object has no attribute 'name' error. in generic.FormView neither of form_valid and form_invalid methods aren't called. although when I use request.POST.get(some_data) it works without any errors but I want to use generic.FormView for some validations. I think the validation of the form makes the error happen. so what should I do? here is my code. models.py class Post(models.Model): post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="posts") text = models.TextField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) ... class Image(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="images") image = models.ImageField(upload_to="images/posts/") forms.py class PostForm(forms.ModelForm): images = MultiImageField(min_num=1, max_num=3) class Meta: model = models.Post fields = ("text", "images") views.py class CreatePostView(LoginRequiredMixin, generic.FormView): template_name = "posts/post_create.html" form_class = forms.PostForm def get_success_url(self): return redirect("profile", slug=self.request.kwargs.slug) def form_valid(self, form): ... # some codes ... return super(CreatePostView, self).form_valid(form) -
CSRF cookie not set in react native axios
I am trying to do my first app in react native and django rest framework. I created a simple server based on tutorial with default login page. I am trying to make a POST to this login page, but I am getting error: Forbidden (CSRF cookie not set.): /api-auth/login/ My POST looks like: const sendLoginCredencials = (data) => { axios.defaults.headers.common['X-CSRF-TOKEN'] = data.csrf_token; axios.post('http://127.0.0.1:8000/api-auth/login/', { username: 'username', password: 'passwd', }, ) .then((response) => { console.log(response) }) .catch(error => { console.error('error', error); }); } Settings.py has this lines: from corsheaders.defaults import default_headers CORS_ALLOW_HEADERS = list(default_headers) + [ 'X-CSRF-TOKEN', ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_NAME = "csrftoken" CSRF_HEADER_NAME = 'X-CSRF-TOKEN' I have tested many answers and combinations. None of them worked and I admit that I feel confused. Could anyone tell me how to set the header correctly and what excatly I should set in settings.py ? Best regards! -
Sending AJAX request Django to previous pages
So i have a project with Django to detect some deepfake video. But i have some trouble. I have to send some Background process (inside predict function) into previous pages (inside index function). Maybe it would be like this [https://i.stack.imgur.com/nYWWV.png] That "TEMPAT PROSESSING" is the place for the background process. and the background process i mean is kinda like this: [https://i.stack.imgur.com/EHGJJ.png] And somebody tell me that it needs to used AJAX.But i never use it before. Can anyone tell me tell me how to do that? Thank you. Below is the code for detection process that i need to send # def predict_page(request) Start: Video Splitting print("\n<=== | Started Videos Splitting | ===>") split_start = time.time() cap = cv2.VideoCapture(video_file) frames = [] while(cap.isOpened()): ret, frame = cap.read() if ret==True: frames.append(frame) if cv2.waitKey(1) & 0xFF == ord('q'): break else: break cap.release() for i in range(1, sequence_length+1): frame = frames[i] split_time = ((time.time() - split_start)) print("---- %.2f seconds ----" % split_time) print("<=== | Videos Splitting Done | ===>") # Start: Face Cropping print("\n<=== | Started Face Cropping | ===>") crop_start = time.time() faces_cropped_images = [] padding = 50 faces_found = 0 for i in range(1, sequence_length+1): frame = frames[i] face_locations = face_recognition.face_locations(frame) … -
Django sitemap.xml for millions of producs
We have a big amount of products. About 50 million items What is the best way to generate sitemaps in Django? At the moment we generate them the following way: sitemaps.py class BookSitemap1(Sitemap): protocol = 'https' changefreq = 'weekly' priority = 0.9 def items(self): return Book.objects.all().order_by('id')[0:25000] class BookSitemap2(Sitemap): protocol = 'https' changefreq = 'weekly' priority = 0.9 def items(self): return Book.objects.all().order_by('id')[25000:50000] ... Urls.py sitemap_books_1 = {'books1': BookSitemap1} sitemap_books_2 = {'books2': BookSitemap2} ... path('books-1.xml', sitemap, {'sitemaps': sitemap_books_1}, name='django.contrib.sitemaps.views.sitemap'), path('books-2.xml', sitemap, {'sitemaps': sitemap_books_2}, name='django.contrib.sitemaps.views.sitemap'), ... And so on for all our 50 million products. But this is 2000 sitemaps... We can put 50000 ulrs in each sitemap. But this will be 1000 sitemaps again Is there any other solution to generate sitemaps in Django? Because this solutions is very inconvenient as for me -
Cannot display DataTable in django-plotly-dash
I am trying to diaplay a DataTable in django-plotly-dash and it is not appearing. other types of components like dropdowns and graphs are appearing and working fine. This is my app.py file import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.graph_objs as go from django_plotly_dash import DjangoDash import pandas as pd import dash_table df = pd.read_csv('home/dash_apps/finished_apps/app3/data/50000 Sales Records.csv') print(df.columns) app = DjangoDash('SimpleExample3') app.layout = html.Div([ html.H1('BLABLABLA'), dcc.Dropdown( id='dropdown_rows', options=[ {'label': i, 'value': i} for i in list(df.columns) ], multi=True ), dcc.Dropdown( id='dropdokkwn_rows', options=[ {'label': i, 'value': i} for i in list(df.columns) ], multi=True ), dash_table.DataTable( id='table_rows', columns=["Rows"], data=[{"Rows": 89}, {"Rows": 88}] ) ]) This is my settings.py file """ Django settings for project8 project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-y@k8s1r#v%jddkv$qd2ctzd)s6+i_dm$9waec%^4y&cp9$b%d3' # SECURITY WARNING: don't run with debug turned … -
How to assign permissions to custom roles in custom User Model in Django?
I have defined a custom User Model that has 2 new roles beside superuser, staff and active, viz. candidate and voter. I want to assign permissions to these roles so that when I create the user with one of these 'True', I get the role-specific permissions assigned to the user automatically. My User model is below class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=254, null=True, blank=True) email = models.EmailField(max_length=254, unique=True) first_name = models.CharField(max_length=254, null=True, blank=True) last_name = models.CharField(max_length=254, null=True, blank=True) pbc_id = models.CharField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_candidate = models.BooleanField(default=False) is_voter = models.BooleanField(default=False) votes = models.IntegerField(default=0) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) My UserManager class is below: class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, is_candidate, is_voter, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( username=email, email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, is_candidate=is_candidate, is_voter=is_voter, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) user.pbc_id = "PBC-" + str(user.pk) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): user = self._create_user(email, password, False, False, False, False, **extra_fields) user.pbc_id = "PBC-" + … -
how to do arithmetic operations in django template
here I have two models Zone and DailyTask from that I made a template that looks like the below image and now I want to find the sum of a used task, unused tasks, and the total task of each time slot thanks in advance model Zone class Zone(models.Model): name = models.CharField(max_length=200) coordinates = models.TextField(null=True, blank=True) model DailyTask class DailyTask(models.Model): date = models.DateField() zone = models.ForeignKey(Zone, on_delete=models.SET_NULL, null=True) slot = models.ForeignKey(GeneralTimeSlot,related_name='daily_task', on_delete=models.CASCADE) total_tasks = models.IntegerField(default=0) used_tasks = models.IntegerField(default=0) unused_tasks = models.IntegerField(default=0) available_driver_slots = models.ManyToManyField(DriverTimeSlot) and current output image in the last three-row, I want the sum above columns ?????? its view is this class TimeSlotReportView(AdminOnlyMixin, generic.DetailView): template_name = 'reports/time_slot_report.html' def get(self, request, *args, **kwargs): zones = Zone.objects.all() # if request.is_ajax(): # # date_val = request.GET.get('date_val') # print(date_val) # daily_task = DailyTask.objects.filter(date=date_val) # html = render_to_string('tasks-zones/task-table-filter.html', {'daily_tasks': daily_task}, request) # return JsonResponse({'html': html}) # no_of_drivers = Driver.objects.all().count() today = datetime.date.today() daily_task = DailyTask.objects.filter(date="2022-06-04") used_tasks = DailyTask.objects.filter(date="2021-06-04").aggregate(Sum('used_tasks'))['used_tasks__sum'] print(used_tasks) unused_tasks = DailyTask.objects.filter(date="2021-06-04").aggregate(Sum('unused_tasks'))['unused_tasks__sum'] print(unused_tasks) # for zone in zones: # daily_tasks = DailyTask.objects.filter(zone=zone, date__gte=today) # for daily_task in daily_tasks: # dr_slots = DriverTimeSlot.objects.filter(driver__zone=daily_task.zone, # start_time=daily_task.slot.start_time) # daily_task.total_tasks = dr_slots.count() # daily_task.available_driver_slots.set(dr_slots) # daily_task.save() return render(request, self.template_name, {'zones': zones, 'daily_tasks': daily_task, 'total-used': used_tasks, 'total-unused': unused_tasks}) -
Django csrf for react
I have a Django backend api app as well as a frontend in React. I want to get csrf from backend to frontend (which I successfully did as per below). However, when I set the csrf token to the header on requests I keep getting that the CSRF token was invalid for various requests. Is there something else I'm supposed to do? I'm migrating the application from a Django view to React. It seems what im trying to do is possible but not working for me based on blogs and other SO posts. from django.middleware.csrf import get_token @require_http_methods(["GET"]) def csrf(request): return JsonResponse({'csrfToken': get_token(request)}) -
django.db.utils.IntegrityError: NOT NULL constraint failed: bankapp_userregistermodel.date_of_birth i m getting this error when i create the superuser
please help me how to solve this\ models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import BaseUserManager, AbstractBaseUser from django.contrib.auth.models import PermissionsMixin class MyuserManager(BaseUserManager): def create_user(self, mobile_number, password=None): if not mobile_number: raise ValueError("user must have an mobile number") user = self.model(mobile_number = mobile_number) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, mobile_number, password=None): user = self.create_user(mobile_number, password=password) user.is_admin = True user.save(using=self._db) return user class UserRegisterModel(AbstractBaseUser, PermissionsMixin): mobile_number = models.IntegerField(verbose_name="Mobile Number", unique=True) bank_ac = models.CharField(max_length=64) first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) user_name = models.CharField(max_length=64) email = models.EmailField() date_of_birth = models.DateField(null=False) address = models.CharField(max_length=160) pin_code = models.IntegerField() is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) is_admin = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) objects = MyuserManager() USERNAME_FIELD = "mobile_number" REQUIRED_FIELDS = [] def __str__(self): return self.mobile_number def has_perm(self, perm, obj=None): return True def has_module_perm(self, app_label): return True @property def is_superuser(self): return self.is_admin admin.py from django.contrib import admin from bankapp.models import UserRegisterModel from django.contrib.auth.admin import UserAdmin as BaseUserAdmin class UserAdmin(BaseUserAdmin): list_display = ['bank_ac','first_name','last_name','user_name','mobile_number','email','password','date_of_birth','address','pin_code'] list_filter = ['bank_ac'] search_fields = ['mobile_number'] ordering = ['mobile_number'] filter_horizontal = [] fieldsets = [] add_fieldssets = [ [None, { 'classes' : ['wide',], 'fields' : ['mobile_number','email','password'], }], ] admin.site.register(UserRegisterModel, UserAdmin) forms.py from django import forms from .models import UserRegisterModel import datetime from django.core.exceptions … -
does performing a `get` on a queryset evaluates the whole queryset or just one element of queryset?
pseudocode: class TestModel(models.Model): a = models.CharField() b = models.CharField() qs = Model.objects.filter(a="something") # returns qs containing 5 objects obj = qs.get(b='something_else') # evaluates the queryset and hits the db obj2 = qs.get(b='something_else_2') # evaluates again? hits db again? Now while assigning to obj2, will it hit db again? or even will it db while assigning to obj?