Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django channels is auto disconnecting after sending message
I am working on a personal chat application in django using django channels. The problem is that after sending message from user1 to user2, the channels of user1(all connected channels) is auto disconnecting after sending message to chat room, although the message is passed successfully to user2 and appeared in screen. There is no particular error message. In console it shows, HTTP GET /? 200 [0.22, 127.0.0.1:52178] WebSocket DISCONNECT /chat/3/ [127.0.0.1:58587] consumers.py: class PersonalChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_id'] self.room_id = self.room_name print(f'Room id: {self.room_id}') self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() self.send(json.dumps({ "join": str(self.room_name), })) def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): print("ChatConsumer: receive_json") text_data = json.loads(text_data) command = text_data.get("command", None) # message = text_data_json['message'] if command == 'send_message': self.send_room(text_data["room_id"], text_data["message"], text_data['type']) def send_room(self, room_id, message_content, message_type): user = self.scope['user'] room = self.get_room_or_error(room_id, user) if message_type.startswith('message'): message_obj = ChatRoomMessage.objects.create(room=room, user=user, content=message_content, message_type=message_type) message = {} message['user_id'] = str(user.id) message['username'] = str(user.username) message['profile_pic_url'] = str(user.profile_image.url) message['timestamp'] = str(message_obj.timestamp) message['msg_type'] = message_obj.message_type message['content'] = message_obj.content async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, … -
not able to save data from bootstrap form to data base in Django
I have created a form that takes 3 inputs from a user and saves user input to DataBase but I am not able to load data from the form to Sqlite dataBase there isn't any error shown on the screen but not able to store data in Db from the user input form. Please Help me I am stuck in here from last 24 hours Thank you views.py from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.http import HttpResponse from .forms import EmployeeForm from .models import Person def index(request): return render(request, 'base.html') def employee(request): if request.method == 'POST': data = request.POST first_name = data['first_name'] last_name = data['last_name'] email = data['email'] obj = Person.objects.create( first_name=first_name, last_name=last_name, email=email) if obj: return redirect('/') return HttpResponse("employee is not created") else: person = Person.objects.all() context = { 'person': person } return render(request, 'employee/employee.html', context) models.py from django.db import models class Person(models.Model): first_name = models.CharField(max_length=10) last_name = models.CharField(max_length=110) email = models.EmailField() employee.html {% extends "base.html" %} {% block main %} <div class="context"> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Add new </button> <div class="card"> <div class="card-header"> Employee Details </div> </div> </div> <form method=="POST" > {% csrf_token %} <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria- labelledby="exampleModalLabel" … -
Referral application in Django
I want to create a Django application referral system for profiles created by user upon login whenever a people login they get a option to create a profile and in that create profile form their is input for referral code which eventually add some point to referred by person here is my Profile Model class Profile(models.Model): owner = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,default='') name = models.CharField(max_length=200,null=True,blank=True) number = models.CharField(max_length=11,default=None,null=True) text = models.TextField(max_length=520) facebook = models.URLField(name='facebook',default=None,null=True) linkedin = models.URLField(name='linkedin',default=None,null=True) instagram = models.URLField(name='instagram',default=None,null=True) profile_picture = models.ImageField(upload_to='profile_pic/', max_length=None) published_date = models.DateTimeField(auto_now_add=True, null=True) updated_date = models.DateTimeField(blank=True, null=True) is_active = models.BooleanField(default=False) def __str__(self): return self.name what should be added to this profile for referral code ?? and how to create a referral class ??? -
How to remove use_for_related_fields since it's deprecated?
Since use_for_related_fields is deprecated, I see the following warning when start up tests: "RemovedInDjango20Warning: use_for_related_fields is deprecated, instead set Meta.base_manager_name on 'info.PersonLink'" but it appears on custom manager, inherited from models.Manager: class PersonLinkManager(models.Manager.from_queryset(PersonLinkQuerySet)): use_for_related_fields = True where PersonLinkQuerySet: class PersonLinkQuerySet(models.QuerySet): def filter_active(self): return self.filter(person__is_active=True) How to rewrite it to avoid this warning in the future? -
How can get current field from form in Django UpdateView like cleaned_data.get('some_field') when use a function?
I need to take one field from the form, make calculations and insert the result into the second field. If you use a function, you can use cleaned _data.get ('first_field') for this, but how to do this using UpdateView? Thank you! -
Django loop pre fetch versus new query
I cant work out in my application that looping a new queryset would loop much faster than a prefetched queryset. I am trying to cut down on queries but I am left with no option atm that to create a new one. answers = ( ReportUserAnswers.objects.filter(...) ) If i loop the above its fast. answers = question.reportuseranswers_set.all() This is really slow. Is there logic i am missing which might which makes this expected behaviour? matched_answers = [ans for ans in answers if choice = "Yes"] Loop that is being used to see the difference above. Queryset lengths are the same new query: 206 loop: 206 -
Facing 502 Bad Gateway/nginx while trying to scrape and insert data in Django
I've implemented a robot inside a Django project that receives a movie URL from IMDB within a form, scrapes some pieces of information from movies, and inserts them into the Postgres Database. It works pretty fine for almost 50% of movies and does the job without heading into errors. But it gives the error 502 Bad Gateway / nginx on some movies while trying to scrape them. I've read some articles about it and I guess the issue is kind of related to server timeout but I'm not sure if that's the case right now. Does anyone have any idea where the problem lies? Thanks in advance for your help. -
Importing csv/excel file in django admin which has inlines
I have tried django-import-export but I couldn't see any way to import inline data using it. I would like to import data from admin which has inlines(more than 1). Example: I have a Course Model, Course Details and Course Deadlines class Course(models.Model): pass class CourseDetails(models.Model): course= models.ForeignKey(course) class CourseDeadlines(models.Model): course= models.ForeignKey(course) On the admin side: class CourseAdmin(admin.ModelAdmin): inlines=[CourseDetailsInline, CourseDeadlinesInline] I would like to import Course Details and coursedeadlines as well when importing courses. Right now I am using django-import-export using which I am not able to import inlines.Any suggestions on the right way to achieve importing data with inlines will be helpful -
How to test Django model using Django test and pytest?
I am using Django to build a website but I don't know how to test my model using Django test and pytest. This is my model. class Payment(models.Model): fund = models.ForeignKey( Funds, verbose_name=_("Fund"), on_delete=models.CASCADE ) currency = models.ForeignKey( Currency, verbose_name=_("Currency"), on_delete=models.CASCADE ) amount = models.DecimalField( verbose_name=_("Amount"), max_digits=10, decimal_places=2 ) date = models.DateField( verbose_name=_("Payment Date"), auto_now_add=True ) status = models.CharField( verbose_name=_("Payment Status"), max_length=20, choices=payment_status_choices, default='pending' ) recipient = models.CharField( verbose_name=_("Recipient"), max_length=50, unique=True ) remark = models.TextField( verbose_name=_("Remark"), blank=True, null=True ) created_by = models.ForeignKey( User, default=1, verbose_name=_("Created By"), on_delete=models.PROTECT, related_name="%(class)s_createdby" ) created_date = models.DateTimeField( verbose_name=_("Created Date"), auto_now_add=True ) modified_by = models.ForeignKey( User, default=1, verbose_name=_("Update By"), on_delete=models.PROTECT, related_name="%(class)s_modifiedby", ) modified_date = models.DateTimeField( verbose_name=_("Modified Date"), auto_now_add=True ) deleted = models.BooleanField( default=False, verbose_name=_("Deleted") ) def __str__(self): return str(self.amount) Please help me doing the rest for this model. Also What is the different between Django test and pytest and which one should I use to test Django model, form and view -
How to prevent Django's prefetch_related from caching a queryset
I have the following queryset function for an Argument model: class ArgumentQuerySet(QuerySet): def prefetch_related_objects(self): from views.models import View return self.prefetch_related( Prefetch( 'argument_reactions', queryset=View.objects.filter(type=ViewType.ARGUMENT_REACTION.name, reaction_type=ReactionType.ENDORSE.name), to_attr='endorsement_reactions' ), Prefetch( 'argument_reactions', queryset=View.objects.filter(type=ViewType.ARGUMENT_REACTION.name, reaction_type=ReactionType.DISAGREE.name), to_attr='disagreement_reactions' ), ) As you can see I'm trying to prefetch the same relation using different querysets and I'm also using the to_attr parameter of the Prefetch object. The problem is the second prefetch is not working properly, the disagreement_reactions list is empty. But it works if I remove the first prefetch. I believe the first queryset, i.e., View.objects is being cached somehow. How can I prevent that? -
Render image to a choice/char field in Django admin
I have a CharField in my model like this: simbol_oznaka = models.CharField(choices=CHOICES_SIMBOLI, null=True, blank=True, verbose_name="Simbol", max_length=512) with a choice tuple like this: CHOICES_SIMBOLI=( ('', 'No Image'), ('media/simboli/2.png', 'Image 1'),). I was wondering how can I render the image in the django admin change/add form, because I don't want the user to see the "Image 1" text but rather the image itself. This is what it currently looks like: Use case: I want the users to be able to choose only one image from a few that would be displayed in the drop down (not necessarily drop down) -
How to validate all the fields at once by making a default validator in django restframework?
I don't want to use Field level or object level validation. While doing POST API call in django restframework, I want to call a default validator by is_valid() method. No arguments should be passed while calling this method and all the fields should be validated. It should be fully generic, so that I can add as many validations as possible. -
Not able to save data in database using django form
I am trying to save data in database using django form but it not saving it this is my forms.py class PlanForm(forms.ModelForm): class Meta: model = Plans fields = ['plan_name', 'plan_note', 'plan_price', 'access_to'] plan_name = forms.CharField(max_length=255, widget=forms.TextInput( attrs={ 'class':'form-control', 'id':'plan_name' } )) plan_note = forms.CharField(max_length=255, widget=forms.TextInput( attrs={ 'class':'form-control', 'id':'plan_note' } )) plan_price = forms.CharField(max_length=255, widget=forms.TextInput( attrs={ 'class':'form-control', 'id':'plan_price' } )) can_access = forms.ModelMultipleChoiceField( queryset=Add_e_office.objects.all(), widget=forms.CheckboxSelectMultiple ) and this my views.py def add_plan(request): if request.method == 'POST': form = PlanForm(request.POST) if form.is_valid(): form.save(commit=False) form.user = request.user form.save() messages.success(request,"Plan created successfully.") return redirect(request.path) return render(request, 'backend/add_plan.html',{'form':form}) else: form = PlanForm() return render(request, 'backend/add_plan.html',{'form':form}) when i submit my form i receive POST request but it did not save data in data base actualy it ignore form.is_valid() part. -
Comments in the admin panel are added, but they are not visible on the site
Based on this tutorial https://www.youtube.com/watch?v=An4hW4TjKhE&ab_channel=AbhishekVerma I'm trying to add the ability to add comments under posts, add a comment in the admin panel, everything is ok, but the site does not display anything under the post here is models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType class Post(models.Model): published = None title = models.CharField(max_length=200) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() header_image = models.ImageField(blank=True, null=True, upload_to="images/", default='fox.jpeg') def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_post') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_user') content = models.TextField(max_length=160) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}'.format(self.post.title, str(self.user.username)) views.py from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Post, Comment from django import forms from .forms import * class BlogListView(ListView): model = Post template_name = 'home.html' context_object_name = 'posts' paginate_by = 2 queryset = Post.objects.all() class BlogDetailView(DetailView): model = Post template_name = 'post_detail.html' class BlogCreateView(CreateView): model = Post template_name = 'post_new.html' fields = ['title', 'author', 'body', 'header_image'] class BlogUpdateView(UpdateView): model = Post template_name = 'post_edit.html' fields = ['title', 'body', 'header_image'] … -
Can we use queryset.first() instead of catching exception?
I normally use MyModel.objects.filter(pk=1).first() instead of MyModel.objects.get(pk=1) when I am not entirely sure whether there is any object with pk=1 or not. Is it a bad practice doing so for this scenario or I need to try: MyModel.objects.get(pk=1) except MyModel.DoesNotExist: print('not found') I normally do MyModel.objects.filter(pk=1).first() for the less code. -
Why can't I add my app in the setting.py before making it? (Django)
I've been following tutorials and messing around with Django lately. I'm trying to revise what I've learned and There's a question I would like to ask: Can someone explain to me why I can't go to my setting.py and add the name of my app in the installed_apps before actually making it? I'm a bit confused about the concept. Why is the other way around allowed in the terminal flawlessly and not in this way? Thanks in advance! -
how to not apply jwt to every app in django
I am working to make a simple ecommerce app. It work with Django as a backend and React for frontend. The trouble I am facing is when I tried to enter some product information (like title, price, image, description) through admin panel , It does not show in home page. When I tried to access its json form using Rest-framework api, it shows this HTTP 401 Unauthorized Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: JWT realm="api" { "detail": "Authentication credentials were not provided." } here is the screenshot I have successfully added user model just following the tutorial but I think this is the cause. I think I have two authentication backends and jwt is not allowing me as admin user to add products. I searched it on google but could not figure what to do? This is my settings.py """ Django settings for UsamaComputers project. Generated by 'django-admin startproject' using Django 3.2. 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/ """ from pathlib import Path import os from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent … -
Is there a way to generate random integers using django forms.py?
I just started learning Django and have a problem: I initially used a class-based view to save information from the front end or user. I then decided to switch to forms.py. My problem is I cannot generate a random number to be saved using forms.py. I do not know if I should recreate this in forms or models. This was the code I wrote in views.py: def createproformastandard(request): now = datetime.datetime.now() year = now.year month = now.month day = now.day if len(str(day)) == 1: day = "0" + str(day) if len(str(month)) == 1: month = "0" + str(month) today = str(year) + "/" + str(month) + "/" + str(day) date = str(year) + str(month) + str(day) randint = str(random.randint(1000, 9999)) rand = str("TSCL") + date + "-" + randint + str("-P") rand = str(rand) while len(ProformaReceipt.objects.filter(rand=rand)) != 0: randint = str(random.randint(1000, 9999)) rand = date + randint rand = int(rand) form = CreateProformaReceipt() if request.method == 'POST': form = CreateProformaReceipt(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request, 'proforma/proforma_form_standard.html', context) -
How to query Django objects based on a field value in the latest ForeignKey?
I have a Django application to store hourly price and volume (OHLCV candle) for several markets. What I'm trying to achieve is to compare the latest volume of all markets and set top10 = True to the 10 markets with the highest volume in the latest candle. What is the most efficient way to do that ? EDIT: The queryset should select all the most recent candle in every markets and sort them by volume. Then return the 10 markets the top 10 candles belong to. models.py class Market(models.Model): top10 = JSONField(null=True) class Candle(models.Model): market = models.ForeignKey(Market, on_delete=models.CASCADE, related_name='candle', null=True) price = models.FloatField(null=True) volume = models.FloatField(null=True) dt = models.DateTimeField() -
Django change model, migrate, and update the existing records
I had a Django model defined as: from users.models import User class Record(models.Model): user = models.ForeignKey( User, on_delete=SET_NULL, null=True) ... I realized that it would be better to rewrite the above model as: from userprofile.models import UserProfile class Record(models.Model): user = models.ForeignKey( UserProfile, on_delete=SET_NULL, null=True) .... How can I migrate (so the new definition of the model Record) is used, without having to lose the old Record instances in the databases? What is the general process of such migrations? Because if I migrate with the new definition of Record, I lose access to the old Record objects so I can't update them. However, if I don't migrate, Django won't let me use UserProfile as the user field. -
Running a Django using gunicorn in docker with reload gives TypeError
Django version: 2.2.23 Everything was working fine. However, when I try to use the --reload flag with gunicorn, it results in the following error: [2021-06-08 09:48:07 +0000] [79] [INFO] Starting gunicorn 19.7.1 [2021-06-08 09:48:07 +0000] [79] [INFO] Listening at: http://0.0.0.0:8000 (79) [2021-06-08 09:48:07 +0000] [79] [INFO] Using worker: sync /usr/lib/python3.8/os.py:1023: RuntimeWarning: line buffering (buffering=1) isn't supported in binary mode, the default buffer size will be used return io.open(fd, *args, **kwargs) [2021-06-08 09:48:07 +0000] [81] [INFO] Booting worker with pid: 81 Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/local/lib/python3.8/dist-packages/gunicorn/reloader.py", line 42, in run for filename in self.get_files(): File "/usr/local/lib/python3.8/dist-packages/gunicorn/reloader.py", line 28, in get_files fnames = [ File "/usr/local/lib/python3.8/dist-packages/gunicorn/reloader.py", line 29, in <listcomp> re.sub('py[co]$', 'py', module.__file__) File "/usr/lib/python3.8/re.py", line 210, in sub return _compile(pattern, flags).sub(repl, string, count) TypeError: expected string or bytes-like object This is my dockerfile: #20.04-LTS FROM ubuntu:focal RUN apt update # install python RUN apt install -y git python python3 python3-dev python3-pip python3-virtualenv && pip3 install --upgrade pip ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 RUN mkdir /web WORKDIR /web ADD requirements.txt /web/ RUN pip3 install -r requirements.txt COPY . /web My docker-compose: version: '2' services: web: build: . depends_on: … -
Django OneToOneField to multiple models and multi OneToOneField
I have the following models: class District(models.Model): pk_district = models.AutoField(primary=True) class Block(models.Model): pk_block = models.AutoField(primary=True) class Community(models.Model): pk_community = models.AutoField(primary=True) class RelateOne(models.Model): pk_object = models.OneToOneField('District or Block or Community') name = models.CharField() class RelateTwo(models.Model): pk_object = models.OneToOneField('District or Block or Community') name = models.CharField() I want the RelateOne or RelateTwo model to associate District or Block or Community, and then I can use it like this: district = District.objects.get(pk=1) district.relate_one.name district.relate_two.name block = Block.objects.get(pk=1) block.relate_one.name block.relate_two.name Block.objects.select_related('relate_one','relate_two') How should I set up the model correctly? -
Stripe API, How can I get"customer_email" when Checkout Session executed
I want Django App to send a confirmation email to a customer when webhook is executed, In order to send an email, I need to get the customer's email address when they make payment. But the JSON posted by stripe Webhook always sends customer_email with null value. Here's the result from the part of Webhook object. { "api_version": "2020-08-27", "created": 1623048315, "data": { "object": { "allow_promotion_codes": null, "amount_subtotal": 1, "amount_total": 1, "billing_address_collection": null, "cancel_url": "http://3.129.28.xxx/subscriptions/cancel/", "client_reference_id": "1", "currency": "jpy", "customer": "cus_Jcrw9AXrxWB91I", "customer_details": { "email": null, "tax_exempt": "none", "tax_ids": [] }, "customer_email": null, "id": "cs_test_a1gup9kG1ArIxORROMUbKqg6eBnIknoYdgQARcr3AS14DGo2gLFfVnxxxx", You can see "customer_email": null, And "customer_details"'s "email" is also null, Therefore I thought I need to get "customer_email" when "create_checkout_session" is executed. So I added "customer_email=userEmail" in create_checkout_session view.py @csrf_exempt def create_checkout_session(request): if request.method == 'GET': # domain_url = 'http://localhost:8000/' domain_url = 'http://3.129.28.206/' stripe.api_key = settings.STRIPE_SECRET_KEY try: checkout_session = stripe.checkout.Session.create( customer_email=userEmail, client_reference_id=request.user.id if request.user.is_authenticated else None, success_url=domain_url + 'subscriptions/success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'subscriptions/cancel/', payment_method_types=['card'], mode='subscription', line_items=[ { 'price': settings.STRIPE_PRICE_ID, 'quantity': 1, } ] ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)}) But it does not work. So I tried a different attempt. customer_email = request.org.billing_email It also does not work. and there is … -
Django Rest Framework PyJWT Token Invalid header padding
I am using Django Rest Frame Work and I'm trying to get authenticated user info, using token in session views.py: # Get Authenticated User Data class UserAPIView(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get(self, request): return Response(UserSerializer(request.user).data) JWTAuthentication class JWTAuthentication(BaseAuthentication): def authenticate(self, request): token = request.COOKIES.get('jwt') print('token = ', token) if not token: return None try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) print('payload = ', payload) except jwt.ExpiredSignatureError: raise exceptions.AuthenticationFailed('unauthenticated') user = User.objects.get(pk=payload['user_id']) if not user: raise exceptions.AuthenticationFailed('User not found!') return (user, None) @staticmethod def generate_jwt(id): payload = { 'user_id': id, 'exp': datetime.datetime.now() + datetime.timedelta(days=1), 'iat': datetime.datetime.utcnow() } return jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256') But I got this error Invalid header padding this is the Traceback [08/Jun/2021 10:44:09] "GET /api/account/user/ HTTP/1.1" 500 134862 token = b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE2MjMyMzU0NDcsImlhdCI6MTYyMzE0MTg0N30.qnNZw3M5YiLMalc78wknjtuTOztHbjyr2swHyK1xuGY' Internal Server Error: /api/account/user/ Traceback (most recent call last): File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\site-packages\jwt\api_jws.py", line 186, in _load header_data = base64url_decode(header_segment) File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\site-packages\jwt\utils.py", line 42, in base64url_decode return base64.urlsafe_b64decode(input) File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\base64.py", line 133, in urlsafe_b64decode return b64decode(s) File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\base64.py", line 87, in b64decode return binascii.a2b_base64(s) binascii.Error: Invalid base64-encoded string: number of data characters (37) cannot be 1 more than a multiple of 4 this is the rest of Traceback During handling of the above exception, another exception occurred: File … -
Django admin - User and group extend
Iam trying to update my user model in Django's admin Panel. I want to add a field/column in Admin panel named "Group" for Users. This field will have the option to select any value from the existing Groups (single option only/Dropdown). I tried to search for the document but I couldnt found out the relevant information to manipulate the User Admin panel. Although I do found a few blogs and video where they have created a new app and extend the User model. Is it possible to update Admin panel for User? Please suggest any document or blog or any approach to achieve the goal.