Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display multiple photos via API
models.py class UserRoom(models.Model): objects = None categoty = [ ('President Lux', 'President Lux'), ('Lux', 'Lux'), ('Double', 'Double'), ('Standard', 'Standard'), ] name = models.CharField(max_length=150, choices=categoty, verbose_name='Категория') room_num = models.CharField(max_length=150) about = models.TextField(verbose_name='Подробности') price = models.IntegerField(verbose_name='Цена') img360 = models.FileField(verbose_name='Фотография в 360') class Meta: verbose_name = 'Номер (About)' verbose_name_plural = 'Номера (About)' class UserImg(models.Model): name = models.ForeignKey(UserRoom, on_delete=models.CASCADE, verbose_name='img2') img = models.FileField(upload_to='User img', verbose_name='Фотография') how to write in serializers.py so that all data from the database is displayed? how to write in serializers.py so that all data from the database is displayed? now when I connect serializers.py it displays either only the first model or pictures from the second and ID of the attached model class UserRoomSer(ModelSerializer): class Meta: model = UserRoom fields = '__all__' -
sql query or django filter for string
hello i need a query that search in database and return a row that has most similarity from starting character with a value. imagine, given string is 'abcdefghijklmnop' our database table has a column named x and for this column, rows are: 1- 'a' 2- 'abc' 3- 'absde' 4- 'abcdef' 5- 'abcdefg' 6- '1abcdefg' and it should return the row number 5 -
Django select_related doesn't optimize query
I have a problem with select_related. I don't know what I'm doing wrong but it doesn't work. models.py class OrganizerUser(models.Model): """This user manage Agents""" user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.user.username class Agent(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) organizer = models.ForeignKey(OrganizerUser, blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.user.username class Lead(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) age = models.IntegerField(default=0) organizer = models.ForeignKey(OrganizerUser, on_delete=models.CASCADE) agent = models.ForeignKey(Agent, null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey( Category, related_name="categories", null=True, blank=True, on_delete=models.SET_NULL ) description = models.TextField() date_added = models.DateTimeField(auto_now_add=True) phone_number = models.CharField(max_length=20) email = models.EmailField() converted_date = models.DateTimeField(null=True, blank=True) def __str__(self): return f"{self.first_name} {self.last_name}" views.py class LeadsApiView(generics.ListCreateAPIView): serializer_class = LeadSerializer permission_classes = [IsAuthenticated, IsAdminOrOrganizer] def get_queryset(self): user = self.request.user #if user.is_staff: #return Lead.objects.select_related('organizer', 'agent').all() if user.is_organizer: return Lead.objects.select_related('organizer').filter( organizer=user.organizeruser) else: return Lead.objects.select_related('agent').filter(agent=user.agent) for agents everything is fine. Django makes 3 queries but for other users, it makes extra queries for each existing user. -
Cannot query "Product": Must be "Comment" instance
I'm trying to add a commenting and replying system to my products model but I can't add replies to comment. This is being done in the same page where the product details are being shown to the user. views.py class ProductFeedbackView(DetailView): model = Product template_name = 'store/product_feedback.html' def get_context_data(self , **kwargs): data = super().get_context_data(**kwargs) connected_comments = Comment.objects.filter(product=self.get_object()) number_of_comments = connected_comments.count() data['comments'] = connected_comments data['no_of_comments'] = number_of_comments data['comment_form'] = CommentForm() connected_replies = Reply.objects.filter(comment=self.get_object()) number_of_replies = connected_replies.count() data['replies'] = connected_replies data['no_of_replies'] = number_of_replies data['reply_form'] = ReplyForm() return data models.py class Product(models.Model): author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) title = models.CharField(max_length=120, unique=True) description = models.CharField(max_length=300, blank=True, null=True) class Comment(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,) content = models.CharField(max_length=200, null=True, blank=False) class Reply(models.Model): comment = models.ForeignKey(Comment, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,) content = models.TextField(null=True, blank=False) -
How implement django.views.generic if earlier used request[Django]
How implement Django.views.generic if earlier used request? from django.shortcuts import render,redirect from django.http import HttpResponse from .models import * from django.contrib.auth import login,logout,authenticate from .forms import * from django.views.generic import ListView Create your views here. New class HomePage(ListView): model = Book template_name = 'book/templates/home.html' Old def home(request): books=Book.objects.all() context={'books':books} if request.user.is_staff: return render(request,'book/templates/adminhome.html',context) else: return render(request,'book/templates/home.html',context) -
Django test uses wrong database in some cases
I try to setup my Django tests, and I noticed that when I run all tests TestRunner uses correct test database (for all aliases): docker-compose exec my_project python manage.py test --keepdb from django import db from django.test.runner import DiscoverRunner from apps.settings.models import Settings class KeepDBTestRunner(DiscoverRunner): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.verbosity = 2 self.keepdb = True self.db_base_name = 'test_postgresdevuser' def run_checks(self): super().run_checks() print(db.connections.databases) ---------------------------------------------- result ---------------------------------------------- {'default': {'NAME': 'test_postgresdevuser', 'USER': 'user', 'PASSWORD': '*******', 'HOST': 'postgres', 'PORT': 5432, 'ENGINE': 'apps.core.db_backends.open', 'TEST': {'SERIALIZE': False, 'DEPENDENCIES': [], 'CHARSET': None, 'COLLATION': None, 'NAME': None, 'MIRROR': None}, 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': None}, 'vk_master': {'NAME': 'test_postgresdevuser', 'USER': 'user', 'PASSWORD': '*******', 'HOST': 'postgres', 'PORT': 5432, 'ENGINE': 'apps.core.db_backends.open', 'TEST': {'SERIALIZE': False, 'DEPENDENCIES': [], 'CHARSET': None, 'COLLATION': None, 'NAME': None, 'MIRROR': None}, 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': None}, But when I run tests for specific module, it uses the original database: docker-compose exec my_project python manage.py test --keepdb apps.my_module ... print(db.connections.databases) ---------------------------------------------- result ---------------------------------------------- {'default': {'NAME': 'postgresdevuser', 'USER': 'user', 'PASSWORD': '*******', 'HOST': 'postgres', 'PORT': 5432, 'ENGINE': 'apps.core.db_backends.open', 'TEST': {'SERIALIZE': False, 'DEPENDENCIES': [], 'CHARSET': None, 'COLLATION': None, 'NAME': None, 'MIRROR': None}, 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': … -
How to check model fields type?
I have an API class that we use across our app that lets us to simplify HTTP request and create new API end points by just assining what model to use, without needing to write custom handler for each model request. However, I want to include wildcard searches in the requests, so I want to be able to check if the model field is a text field and if it is, check the given field for wild cards. I know how to do deal with wild cards and do wild card searches, but I want to know how I can check if the any given field is a text field? To give pseudocode example, what I roughly want to do: model = ModelWeAreUsing for field in search_terms: if model[field] is TextField: doTextField() else: doGenericField() -
model instance not getting created on triggering signals post save when tested with pytest
While i was trying to test my model, it was linked to a signals file where when.save() is called on that model, the signals file is triggered and then a instance on different model is also created in that signals file. But when i try to test with Py-test, factory boy and fixtures the instance that was getting created in the signals file for different model is not triggered. Below is the code for reference: signals.py @receiver(post_save, sender=Candidate, dispatch_uid="create_candidate_user") def create_candidate_user(instance, **kwargs): """ Create candidate user does not exist """ if instance.user is None: try: user = None if instance.email or instance.mobile: email_user = None mobile_user = None mobile = instance.mobile if instance.mobile and not instance.mobile.startswith("+"): mobile = f"+91{instance.mobile}" if instance.email: try: email_user = User.objects.get(email=instance.email) except User.DoesNotExist as ode: print(ode, f"for {instance.email}") if mobile: try: mobile_user = User.objects.get(mobile=mobile) except User.DoesNotExist as ode: print(ode, f"for {mobile}") if email_user and mobile_user: if email_user != mobile_user: raise Exception( f"Duplicate Users found! ids are: {email_user.id} and {mobile_user.id}" ) else: user = email_user elif email_user or mobile_user: if email_user is not None: user = email_user if mobile: user.mobile = mobile if mobile_user is not None: user = mobile_user if instance.email: user.email = instance.email else: query … -
Access delete method body send via axios.delete
I am building a react-django simple blog app and I am trying to delete blog post but I also want to send body with delete to backend But I have no idea, How can I access delete body ?. I can do with post like self.request.POST with how with delete ? App.js class BlogPost extends React.Component { deleteBlog = (blog_title) => { const body = ({title: blog_title}); const headers = { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json", } axios.delete("delete_blog/", blog_title, {headers:headers}).then(res => {console.log}) } render() { return ( <div> { this.state.blogs.map(res => <div> {res.blog_title} <button onClick={() => deleteBlog(res.blog_title)}></button> </div> } </div> )}} views.py class BlogPost(APIView): def post(self, *args, **kwargs): ....... def delete(self, *args, **kwargs): # Trying to access delete body here...... print(self.request.POST) # It printed empty dict like <[QueryDict = {}]> I have tried many times but it is still not showing. Any help would be much Appreciated. Thanks You in Advance. -
Best way to get cords of Html elements around canvas?
I am trying to make a dynamic graph that changes based on the numbers it receives and have the last 5 business days on the X axis and the prices on the y axis. This is all on the edge of a canvas I was wondering what the best approach to getting the coordinates of the html elements were to dynamically draw the lines. Here is my html <div class="homepage-relativePrices"> <p id="first_highest">{{ first_highest }}</p> <p id="second_highest">{{ second_highest }}</p> <p id="third_highest">{{ third_highest }}</p> <p id="fourth_highest">{{ fourth_highest }}</p> <p id="fifth_highest">{{ fifth_highest }}</p> </div> <canvas id="homepage-stockGraph" style="background-color: white;"></canvas> <!--Last 5 Business days from 4 days ago to today--> <div class="homepage-dayDisplays"> <p id="four_days">4D</p> <p id="three_days">3D</p> <p id="two_days">2D</p> <p id="one_days">1D</p> <p id="today">Today</p> </div> and the drawLine function I have been playing around with const canvas = document.getElementById('homepage-stockGraph'); const ctx = canvas.getContext('2d'); function drawLine(el, el2){ ctx.strokeStyle = 'black'; ctx.lineWidth = 1; ctx.beginPath(); ctx.lineTo(x, y); ctx.moveTo(x2, y2); ctx.stroke(); } Canvas with elements around it -
Django - Query with extra method that use python Function
I would like to make a query in Django that use a function that take parameters from db e from python program. The function is shown below: > def myFunc(a, b): > val = mathematical expression with a and b > return val I would like that: a comes from myTable (represent the field 'num') b comes from python Code class myTable(models.Model): num = models.IntegerField(default=0) I would like to do a query similar to this in views.py: b = 4 #it must be variable c = 10 #it must be variable myTable.objects.all().extra(select = {'new_param' : myFunc(num , b)}, where = ['new_param > %d'], params = [c]) How can I do that? Thanks -
I want to put django's object in the templapates JavaScript, but I can't What should I do?
class KcalDetailView(DetailView): model = User context_object_name = 'target_kcal' template_name = 'kcalculatorapp/detail.html' def get_context_data(self, **kwargs): kcl = self.request.user.kcal context = super().get_context_data(**kwargs) i = 0 kcal_list = [] while i < 13: i = i + 1; if kcl.goal == 'diet': kcal_list.append((kcl.weight -round((500/7000)*i,2) )) else: kcal_list.append((kcl.weight + round((500 / 7000) * i,2))) context['kcal_list'] = kcal_list return context https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/line-labels this chart use. templates.html . . . <script> . . . series: [{ name: 'a', data: {{ kcal_list }} // this !!! }] }); </script> For example kcal_list = [ 10, 13, 15, 16, 20 ] It's in the form of a list. And data: [10, 13, 15, 16, 20] Why does it look like this? data : {{kcal_list}} is not possible? What should I do? -
Django filter datetime with timezone field with date only
I have a field in django model: "created_at" which is datetime with timezone (example: 2022-08-09 14:03:18.467482+02). In my app, I have a form where user selects date only (example: 2022-06-09). I'm trying to filter that field in my view like this: res = MyObject.objects.all() res = res.filter(created_at = date) I'm getting the following error: RuntimeWarning: DateTimeField Mybject.created_at received a naive datetime (2022-06-09 00:00:00) while time zone support is active. What is the best way to to filter my object with user input date? Do I need to add timezone to user selected date and how? -
object to json including textfields and arrayfields
So we are storing from frontend to DB array of multiple selections as String with pipe seprator. To call it for API view we take all models to a textfield() and serialize it to JSON the problem with models that should be iterated in are still pipe separator and i'd like to have it as an array of string not as a total string pipe separated class PublishedInfo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) information= models.OneToOneField( Property, on_delete=models.CASCADE, primary_key=True, ) issue_date = models.DateTimeField(auto_now=True) info = models.TextField() class Meta: verbose_name = 'Published Info' verbose_name_plural = 'Published Info' def __str__(self): return self.information.information_name def user_is_authorized(self, user): """Checks if user allowed to edit this property""" if user.manager: user_properties = UserProperty.objects.filter(user=user).filter(property=self.information).first() return user_properties is not None return self.user == user then info are serialized class PublishedInfoSerializer(serializers.ModelSerializer): facts = StringJsonField() class Meta: model = info fields = '__all__' and lastly called from views @api_view(['GET', ]) @permission_classes([IsAuthenticated]) def get_published_info(request, property_id, info_type): selected_published_info = PublishedInfo.objects.filter(information__id=property_id).first() if info_type == 'json': serializer = PublishedFactsSerializer(selected_published_facts, many=False) return Response(serializer.data['info'], status=status.HTTP_200_OK) now json response always return some multiple fields like this FieldModel : "data | data | data | data" and i tried different solution to convert it in views or in serializer but then … -
Filtering and searching with Django Rest Framework
I'm doing my first DRF project and wondered if it's possible to use the DjangoFilterBackend for filtering specific fields and use a search Filter at the same time. So a request would look something like: http://localhost:8000/api/v1/test/?search=test&id=27&author=2672 Is it possible to do this with DjangoFilterBackend or would I have to write my own filter logic? If you need more information on the project itself or my code just let me know :) -
Django SystemCheckError templates.E003
All of a sudden I'm getting this weird error when trying to start a django app. Everything works fine, then I commit my code and app isn't working anymore. I couldn't find any helpful info, anyone know what could cause this? app_1 | ?: (templates.E003) 'admin_list' is used for multiple template tag modules: 'django.contrib.admin.templatetags.admin_list', 'django_admin_lightweight_date_hierarchy.templatetags.admin_list' -
Why does this django/react project not update
I'm currently following a tutorial for a django/react project. I'm using python .\manage.py runserver to run it and it works, but when i try to make changes to my code and save the files, the page dosen't update. Even if i close the server and run it again the page remains the way it was previously. I tried many solutions but nothing seems to work. I left the github repository if you need to see my code. https://github.com/Andreiosup/Music_app -
What is the best to way to add an already hosted web app on digital ocean to google cloud sdk appengine
Well am trying to host my Django 3.8 website app that's already hosted on digital ocean on the google app store. Which i would just want to host the app on google play store but wouldn't want to use any of the resource of the cloud app-engine sdk! since my data base in hosted on digital ocean , if am to use the google app-engine would it mean that I would have to upload my whole project on cloud app engine ? meaning I would have to set up another database since am using PostgreSQL to store users data, but google cloud currently offer datastore sql! which am thinking of how possible i could merge that two database, would it course a problem for my app since I've already started collecting users data on the PostgreSQL database. Is it possible to just link my app to the appstore without having to pushing the whole app into app engine ? to keep consistency with my current database ! Am puzzled on how to go about this since after reading some of the docs of google cloud app-engine ! I need help on this. -
Why my project uwsgi.ini is throwing Internal Server Error?
I am configuring a Django Nginx Server. Up to this stage: uwsgi --socket ProjetAgricole.sock --module ProjetAgricole.wsgi --chmod-socket=666 everything is working fine. However, after configuring the .ini file, and run the uwsgi --ini ProjetAgricole_uwsgi.ini file,I am getting this ouput [uWSGI] getting INI configuration from ProjetAgricole_uwsgi.ini. But when I open the app from the browser I am getting Internal Server Error Here is my .ini file: [uwsgi] # Django-related settings # the base directory (full path) chdir = /home/dnsae/my_project/ProjetAgricole/ # Django's wsgi file module = ProjetAgricole.wsgi # the virtualenv (full path) home = /home/dnsae/my_project/my_venv # process-related settings # master master = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe socket = /home/dnsae/my_project/ProjetAgricole/ProjetAgricole.sock # ... with appropriate permissions - may be needed chmod-socket = 666 # clear environment on exit vacuum = true # daemonize uwsgi and write message into given log daemonize = /home/dnsae/my_project/uwsgi-emperor.log I restarted the server but still I am getting the same error. Please assist me. -
Store data in Django server after redirect to linked in OAuth
I am developing an application with LinkedIn Log In with OAuth. In my view, I send a state (random string) in the linkedin request and then I want to compare it with the state received in the linkedin response. I tried to store the state on a session request.session['l_state'] = random_string but after the moment the web page went to the linkedin.com domain, to do the authentication, that data was lost. How can I store that value on the server without loosing it? -
Django CSRF verification failed with nginx reverse proxy
I am desperate. I have a https server that redirects traffic to my local https server. My university runs a reverse proxy that forwards the requests my nginx: The local https server is only visible from the vpn. They do that so that I do not have to care about the keys management and I can just plug some generic ones. When I on the VPN the external server works as expected but when I am out of the VPN the external server returns CSRF cookie not set. I have checked basically everything and read all the CSRF verification failed. Request aborted. posts here. The url in the external server is (anonymized): https://project.uni.edu/ The url of the internal server (anonymized): https://project_internal.uni.edux/ The configuration of the nginx: server { listen 443 ssl; server_name project.uni.edu localhost; ssl_certificate /code/staticfiles/cert/project_name.pem; ssl_certificate_key /code/staticfiles/cert/project_name_key.pem; location / { proxy_pass http://web:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; } location /static/ { alias /code/staticfiles/; } location /media/ { alias /code/mediafiles/; } } My settings in the django file are: CSRF_TRUSTED_ORIGINS = ["https://project.uni.edu/","https://project_internal.uni.edux/"] # SESSION_COOKIE_SECURE= True CSRF_COOKIE_HTTPONLY = False SESSION_COOKIE_DOMAIN= "project_internal.uni.edux" -
How to access model's verbose name in a serializer?
I want to access verbose name of models to put it as a key in serializer. But I can't find a way to do it. My models are: class ProductCategory(models.Model): name = models.CharField(max_length=150, unique=True) created_at = models.DateTimeField(default=timezone.now) modified_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.name class DeviceTypeCategory(ProductCategory): product_category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE, related_name="device_types") class Meta: verbose_name = _("Device type") verbose_name_plural = _("Device types") class DeviceBrandCategory(ProductCategory): product_category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE, related_name="device_brands") class PartTypeCategory(ProductCategory): product_category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE, related_name="part_types") And my serializer: class ProductCategorySerializer(serializers.ModelSerializer): device_types = serializers.StringRelatedField(many=True) device_brands = serializers.StringRelatedField(many=True) part_types = serializers.StringRelatedField(many=True) class Meta: model = ProductCategory fields = ('name', 'device_types', 'device_brands', 'part_types') Any suggestions would help. I would also be glad to hear out other ideas on how to create categories model. I've tried django-mptt, but I need product to belong to multiple subcategories. The django-polymorphic-mptt could have help. But I couldn't find proper documentation. -
What did mean by AttributeError at /login_user/?
My target is to get all the products a user added to the cart, that's why I decided to fetch the ShopingCart model from the context processor. And I added it to the context processor, and it worked well. But the problem is when I try to log out, then I get an error. Where did the actual problem occur? help me😢... models.py: class ShopingCart(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='UserShoppingCartRelatedName',on_delete=models.CASCADE) Product = models.ForeignKey(Products, related_name='ShoppingCartRelatedName',on_delete=models.CASCADE) context_processors: def ShoppingCart(request): return {"ShoppingCart":request.user.UserShoppingCartRelatedName.all()} error: AttributeError at /login_user/ 'AnonymousUser' object has no attribute 'UserShoppingCartRelatedName' Request Method: GET Request URL: http://127.0.0.1:8000/login_user/ Django Version: 4.0.4 Exception Type: AttributeError Exception Value: 'AnonymousUser' object has no attribute 'UserShoppingCartRelatedName' Exception Location: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\django\utils\functional.py, line 259, in inner Python Executable: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\Scripts\python.exe Python Version: 3.9.5 Python Path: ['D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\python39.zip', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\DLLs', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\lib', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39', 'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site\\env', 'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce ' 'site\\env\\lib\\site-packages'] Server time: Tue, 09 Aug 2022 11:48:23 +0000 -
django.core.exceptions.ValidationError: ['“1” is not a valid UUID.']
Whenever I am running the server I am getting the error django.core.exceptions.ValidationError: ['“1” is not a valid UUID.'] I have used UUID v4 to change the user id to a random id. But my code is not working. I have deleted and re-migrated migrations many times. But no improvement at all? how can I fix the probelm? #models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin,BaseUserManager import uuid class CustomUserManager(BaseUserManager): def _create_user(self, email, password, first_name, last_name, mobile, **extra_fields): if not email: raise ValueError("Email must be provided") if not password: raise ValueError('Password is not provided') user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, mobile = mobile, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name, mobile, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_active',True) extra_fields.setdefault('is_superuser',False) return self._create_user(email, password, first_name, last_name, mobile, password, **extra_fields) def create_superuser(self, email, password, first_name, last_name, mobile, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_active',True) extra_fields.setdefault('is_superuser',True) return self._create_user(email, password, first_name, last_name, mobile, **extra_fields) # Create your User Model here. class User(AbstractBaseUser,PermissionsMixin): # Abstractbaseuser has password, last_login, is_active by default id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(db_index=True, unique=True, max_length=254) first_name = models.CharField(max_length=240) last_name = models.CharField(max_length=255) mobile = models.CharField(max_length=50) address = models.CharField( max_length=250) is_staff = models.BooleanField(default=True) # must needed, otherwise you won't … -
Send message to all Users in Django
i was about to create a function that sends message to all members Using forloop but then i thought that this method gonna take alot of time in process if there is a plenty of members... so i came to ask if is there any better method to ignore forloop and smooth the process. Model: class TblExamNotification(models.Model): exam = ForeignKey(TblExam,on_delete=models.CASCADE,blank=True, null=True) user = ForeignKey(Members,on_delete=models.CASCADE,blank=True, null=True) is_seen = BooleanField(default=False) def __str__(self): return str(self.id) Views: for member in memebers.exclude(member = request.user): notif_obj = Members.objects.create(user=member , exam=exam_obj) notif_obj .save()