Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Item in shopping cart dissapears once I navigate to a different page Django
I am creating a e-commerce website with Django and I stumbled onto a problem I cannot solve. If i click on add to cart button, the added product shows up in the shopping cart. However, if i navigate to lets say home page ( or any other page ) the newly added product is not displayed no more in the shopping cart. In JS file I have added some code for debugging. In views I have done the same, although with the current code I have parsed in here, most of the logging is already removed. Any suggestions how I can solve this? I have added logging to server side to debug. I have solved quite a bit there already. On the client side ( atleast, thats what i suspect where the rootcause may lie), the logging is still there. views: def add_to_cart(request): try: cart_product = { "product_name": request.GET["product_name"], "product_price": request.GET["product_price"], "product_quantity": int(request.GET["product_quantity"]), } product_id = str(request.GET["product_id"]) if "cart_data_obj" in request.session: cart_data = request.session["cart_data_obj"] if product_id in cart_data: # Product already exists in the cart, update the quantity cart_data[product_id]['product_quantity'] += int(cart_product['product_quantity']) else: # Product doesn't exist, add it to the cart cart_data[product_id] = cart_product request.session["cart_data_obj"] = cart_data else: # Cart … -
why the password of django admin page and new users that wnats to sign up are should be same?
i want to sign up to my website but it wants admin pages password for a new user which its username and emails are not same what should i do to solve this problem? I just confused plz help to solve this. admin.py from django.contrib import admin from .models import Room, Topic, Message, User admin.site.register(User) admin.site.register(Room) admin.site.register(Topic) admin.site.register(Message) def loginPage(request): page = 'login' if request.user.is_authenticated: return redirect('home') if request.method == 'POST': email = request.POST.get('email').lower() password = request.POST.get('password') try: user = User.objects.get(email=email) except: messages.error(request, 'User does not exist') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Username OR password does not exit') context = {'page': page} return render(request, 'base/login_register.html', context) def registerPage(request): form = MyUserCreationForm() if request.method == 'POST': form = MyUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.username = user.username.lower() user.save() login(request, user) return redirect('home') else: messages.error(request, 'An error occurred during registration') return render(request, 'base/login_register.html', {'form': form}) -
A view in Django is returning a GET response instead POST
In my Django project, I'm trying to implement a logout method but the server throws the following error Method Not Allowed (GET): /logout/ Method Not Allowed: /logout/ [17/Jan/2024 21:01:58] "GET /logout/ HTTP/1.1" 405 0 Any idea why it sends a GET method where it's set to POST in my django form views.py from my main django_project app from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), and logout.html {% extends "blog/base.html" %} {% block content%} <form method="POST" action="{% url 'logout' %}"> {% csrf_token %} <h2>You've been logged out!</h2> <div class="register_signin"> <a href="{% url 'login' %}"><b>Log In Again </b></a> </div> </form> {% endblock content %} I'm using Django 5.0.1 so I know it has to be a POST method I included the CSRF token There is no JS involved -
How to round 3 decimals instead of 2 with django currencies template tags?
{% change_currency video.price CURRENCY.code %} I have this template tag but it rounds the price to 2 decimal points when i change currency. I want to make it to round to 3 decimals points. Its from django-currencies library template tags I tried to add|floatformat:”3” but nothing -
how to upload photo to replicate API using Django?
i need to use i2vgen-xl model in Replicate website using Replicate API in Django and i need to pass an image (not url) but it gives me this error - input: prompt is required - input.image: Does not match format 'uri' view.py def X(request): form = ImageForm() if request.method == 'POST': form = ImageForm(request.POST,request.FILES) if form.is_valid(): form.save() image_name = str(form.cleaned_data['Image']) os.environ["REPLICATE_API_TOKEN"] = "X" image_path = rf"'media\images\\{image_name}" output = replicate.run( "ali-vilab/i2vgen-xl:5821a338d00033abaaba89080a17eb8783d9a17ed710a6b4246a18e0900ccad4", input={ "image": image_path } ) print(output) else: print("image is invalid") return render(request,"img2vid.html",{'form':form}) -
How to properly deploy a Django app while following 12FA?
I am deploying a Django app and I got stuck. I am trying to follow the 12 factor app principles. Specifically, they state that you should have all your configuration in environment variables. Also, I don't want to have multiple settings.py files, because that goes against the 12FA principles. So, I have simply a single settings.py file, which checks environment variables using os.environ['xxx'] for stuff like database login etc. On the local dev machine, these environment variables are pulled from a file called .env. On the server, I am planning to store all the environment variables inside a systemd unit using the Environment= syntax. Now, my problem occurs while deploying. I copy all the source Python files onto the server, and I need to call collectstatic and migrate. However, these actions both require the presence of a settings.py file which needs to have access to the database. However, collectstatic is called from my CI/CD pipeline and doesn't have all those environment variables; the only place where they're stored is the systemd unit file which has very limited permissions (only root can read and write to the file). My question is, what approach could I take in order to follow 12FA … -
Django ORM: how to cast geometry to geography in filter?
In my Django project, I have defined a geometry field on one of my model. Its SRID is 4326 (WGS 84). I would like to write with Django ORM a query that will translate to: select * from building where (ST_DWITHIN(shape::geography, ST_MakePoint(1.9217,47.8814)::geography,20)) In other words, I would like to filter the queryset using the ST_DWITHIN function, applied to a geometry field (shape) casted to a geography. The only way I could find is to use the extra() function, like so: Building.objects.extra( where=[ f"ST_DWITHIN(shape::geography, ST_MakePoint({lng}, {lat})::geography, {radius})" ]) But the extra function is supposed to be deprecated in future version of Django, according to the doc. Can I write this query without escaping from the ORM? Maybe using the Cast function ? -
Django REST framework issue : How to get action attribute in middleware
I want to check my action or some limitation in middleware, but i can't get the action in middleware, I always get None. I tried the following code. My middleware look like the following code. And when i create a new project. I need to get the action name, because i just need to limit the create method. Not the other @action method also POST method. class MyMiddleware: EXEMPT_URLS = ['some url'] # Add the URLs that should be exempted def __init__(self, get_response): self.get_response = get_response def get_record_count(self, viewset_name): # Define a mapping between viewset names and model classes model_mapping = { 'projects': Project, 'datas': Data, 'decisions': Decision } # Get the model class corresponding to the viewset name model_class = model_mapping.get(viewset_name) return model_class.objects.count() if model_class else 0 def __call__(self, request): # Call the next middleware in the stack response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): if request.path_info.lstrip('/') in self.EXEMPT_URLS: return None # Check if the request is a POST method if request.method != 'POST': return None resolver_match = request.resolver_match print(resolver_match) # this is ResolverMatch(func=aiwinops.apps.project.views.ProjectViewSet, args=(), kwargs={}, url_name=project-list, app_names=[], namespaces=[], route=api/v1/projects$) print(view_func.cls) # <class 'myproject.apps.project.views.ProjectViewSet'> if not resolver_match: return JsonResponse({'message': 'URL does not match any view'}, … -
Change generated model name without deleting model django
In django, by default, if you have a structure like this app ├── migrations └── models └ example The generated name of your model will be app_example when executing the command makemigrations. My problem is that I want to move my model from the directory app to the directory other_app which has the same structure. other_app ├── migrations └── models -> example will go here At the same time, I want the generated name of my model to be other_app_example once I migrate without having to delete my table, as to avoid losing the data in it. The thing is, when you create a migration in django after changing a model of place, django delete the model in the migration directory of app and recreate it in another migration in other_app. I know that I have to create a custom migration, but how can I achieve what I want to do ? All I found was RenameModel, but it doesn't change the name generated by django. -
Access the list of items send from view model to serialised
I have a dango app where I try to add all answer alternative to a question (from db) in the serializer. Which seems to work. **My Model** class MyModel(models.Model): Question = models.TextField(null=False, blank= False) Answer=models.CharField(max_length=200,null=False,blank= False) def __str__(self): return Question **My View Model** class get_english_q(APIView): serializer = English_Q_Serializer def get(self,request,**kwargs): language = self.kwargs.get('id') list1 = MyModel.objects.filter(.....) list2 = MyModel.objects.filter(.....) list3 = MyModel.objects.filter(.....) array1 = random.sample([x.id for x in list1], k=5) array2 = random.sample([x.id for x in list2], k=5) array3 = random.sample([x.id for x in list3], k=5) array1.extend(array2) array1.extend(array3) list = MyModel.objects.filter(id__in=array1) serializer = English_Q_Serializer(list, many=True) return Response(serializer.data) **My Serializer Model** class English_Q_Serializer(serializers.ModelSerializer): answers = serializers.SerializerMethodField('get_words') class Meta: model = english_technical fields = ( 'answers', 'id', 'question', ) def get_words(self, instance): list_all=MyModel.objects.all() answers=[instance.answer] array = random.sample([x.answer for x in list if x.answer != instance.answer],k=4) answers.extends(array) return answers Now when I define the list of questions to include I take 5 from one queryset, 5 from another and 5 from another. Now I want to make logic in serializer different depending on if they were in first set of 5, second set of 5 or third set of 5. Is there a way that I in the serializer can get the index … -
How do I render individual dynamic elements from a dictionary in a Django template?
This is my first question (sorry for any english mistakes), and I appreciate your help in advance! I'm working with a Django app (MVT). I have a view that returns a dictionary, and I would like to access individual elements of the dictionary in the template. However, in the template, I can render the complete dictionary without any issues, but I can't render individual elements. I'll show you the view that return the dict registros_por_dia. class GrillaView(View): template_name = 'grilla.html' def get(self, request): return render(request, self.template_name) def contar_registros(self, fecha): ... def post(self, request, fecha=None): if fecha: ... else: # Esta parte se ejecutará cuando se envíe el formulario del mes y año mes = int(request.POST.get('mes')) ano = int(request.POST.get('ano')) dias_en_mes = [dia for dia in range(1, monthrange(ano, mes)[1] + 1)] registros_por_dia = {} for dia in dias_en_mes: fecha = datetime(ano, mes, dia).strftime('%Y-%m-%d') contador = self.contar_registros(fecha) registros_por_dia[dia] = contador return render(request, self.template_name, {'dias_en_mes': dias_en_mes, 'registros_por_dia': registros_por_dia}) And now I'll show you the relevant part of the template. ... {% if dias_en_mes %} {% with fecha_format='%Y-%m-%d' %} <div style="display: flex; flex-wrap: wrap;"> {% for dia in dias_en_mes %} {% with fecha=dia|date:fecha_format %} <div style="width: 50px; height: 50px; border: 1px solid black; margin: 5px;"> … -
Configure PyCharm to run appropriate variant of manage.py that is built within Docker container but doesn't exist in source code?
We have our program all dockerized and I'm now trying to get my pycharm to connect to it to debug something. I've followed these steps but they are incomplete when it comes to how to define the Django application. At this point I'm getting an error saying "python script path must be set" I believe this is because it can't find the manage.py Django script, which it wouldn't find. Instead of having one manage.py script we have a dev, test, and prod script with different names. I should be able to set this in the Django configuration in the 'manage script' field in theory. Except our scripts are actually being built within the Docker environment, I don't have a dev.py script in my source code. I could easily tell it the location of the script on the Docker container, but it won't let me type an arbitrary path, it wants me to select a file within my source code and there is no file in my source code at this point. How can I point Django to a dev.py within my container? -
Let Django form add class to input in case of error
I'm using Django 4.2.9 and need a form add an additional class to an input field, in case the validiation failed. I can already add classes for every case, but I do not know how to do it for the error-case. class ItemForm(forms.models.ModelForm): class Meta: model = Item fields = ("text", ) widgets = { "text": forms.widgets.TextInput( attrs={ "placeholder": "Enter a to-do item", "class": "form-control form-control-lg", } ), } error_messages = {"text": {"required": EMPTY_ITEM_ERROR}} def save(self, for_list): self.instance.list = for_list return super().save() I'd like to have class="form-control form-control-lg is-invalid" for the text-input. <form method="POST" action="/lists/8/"> <input type="text" name="text" value="Buy wellies" placeholder="Enter a to-do item" class="form-control form-control-lg" required id="id_text"> <input type="hidden" name="csrfmiddlewaretoken" value="vcojkMtz3GeonURczjMwIsbsDPQUbeKgrXrPIxZY4jIJSfuUKKGVgaj7wLQBatsd"> <div class="invalid-feedback"><ul class="errorlist"><li>You&#x27;ve already got this in your list</li></ul></div> </form> -
django obtain a value from a determinated queryset with a string?
I want to get or obtain the data from a selected queryset with a string, something like this: queryset= BasicModel.objects.all() x = 10 my_atribute = "name" queryset[x]["my_atribute"] values() don't work, because it's give me, in ForeingKeys model, the key and not the data. -
I can't apply the migrations in Django DB
I am Facing a problem with my project, (cant apply the changes on Django DB) There was an empty field and it didn't set it to Null = TRUE, Blank =True, when I migrated it kept giving me this error message : ''' django.db.utils.IntegrityError: NOT NULL constraint failed: new__orders_order.total ''' I tried to set the values in the cart model to True and then I changed them to False, It didn't solve the problem. I tried importing the Integrity error, still didn't solve the issue : ''' def save(self, *args, **kwargs): try: super.save(*args, **kwargs) except IntegrityError: self.code = generate_code() super.save(*args, **kwargs) ''' Models ''' from django.db import models, IntegrityError from django.contrib.auth.models import User from django.utils import timezone from utils.generate_code import generate_code from products.models import Product from accounts.models import Address import datetime ORDER_STATUS = ( ('Received', 'Received'), ('Processed', 'Processed'), ('Shipped', 'Shipped'), ('Delivered', 'Delivered') ) class Order(models.Model): user = models.ForeignKey(User,related_name='order_owner', on_delete = models.SET_NULL, null = True, blank = True) status = models.CharField(choices=ORDER_STATUS, max_length=12) code = models.CharField(default=generate_code, max_length=20,unique=True) order_time = models.DateTimeField(default=timezone.now) delivery_time = models.DateTimeField(blank=True, null=True) delivery_address = models.ForeignKey(Address, related_name='delivery_address', on_delete=models.SET_NULL, null=True,blank = True) coupon = models.ForeignKey('Coupon', related_name='order_coupon', on_delete=models.SET_NULL, null=True,blank = True) total = models.FloatField(null=True,blank = True) total_with_coupon = models.FloatField(null=True,blank = True) def save(self, … -
Django: Subclassing django.forms.widgets.Media
I want to use a custom javascript widget in my app. The javascript is not static, but dependant on template variables that I have already successfully attached to the widget as attributes (it's a MultiWidget in case that matters). Since the media property can only render static javascript, I was thinking of using the html template renderer in an own subclass MediaDirect(widgets.Media). For that, I have also subclassed Media.render_js and Media.get_absolute_path so that it uses django.template.loader.render_to_string and pastes the content between a <script></script> tag: from django.template.loader import render_to_string from django.utils.html import format_html class MediaDirect(widgets.Media): """Media class that directly renders a template, using the media's parent as context. Important: Javascript or CSS *templates* are accessed per definition of settings.TEMPLATES, not settings.STATIC_URL, since they are not static. """ def __init__(self, context, *args, **kwargs): self.context = context super().__init__(*args, **kwargs) def render_js(self): print("This is never called") result = [] for path in self._js: js = render_to_string(self.absolute_path(path), self.context) ########## <--- result.append(format_html("<script>{}</script>", js)) ########## <--- return result def absolute_path(self, path): if path.startswith(("http://", "https://", "/")): return path return path class NoUISliderMinMaxWidget(widgets.MultiWidget): template_name = "widgets/nouislider_minmax.html" def _get_media(self): """ Media for a multiwidget is the combination of all media of the subwidgets. Override method to use MediaDirect instead of … -
Default pagination with strawberry django
According to the doc and this issue there is no default pagination or maximum limit on returned results. I've managed to have a default pagination by defining field_cls : PAGINATION_MAX_LIMIT = 1000 class DefaultPaginationStrawberryDjangoField(StrawberryDjangoField): def apply_pagination(self, queryset, pagination=None): if pagination is None: pagination = OffsetPaginationInput() if pagination.limit > PAGINATION_MAX_LIMIT or pagination.limit == -1: pagination.limit = PAGINATION_MAX_LIMIT return super().apply_pagination(queryset, pagination) @strawberry.django.type(Project, pagination=True) class ProjectType: ... @strawberry.type class Query: projects: list[ProjectType] = strawberry.django.field(field_cls=DefaultPaginationStrawberryDjangoField) Since I do not want to use Relay, there is a better / cleaner way ? -
Image not changing in Django edit view
def edit_image(request, pk): current_image = get_object_or_404(Images, pk=pk) if request.method == "POST": form = EditImage(request.POST, request.FILES, instance=current_image) print(form) if form.is_valid(): image_path = current_image.image.path print(image_path) print("hello \n\n\n") if os.path.exists(image_path): print("path exists") os.remove(image_path) form.save() messages.success(request, "Image updated successfully") return redirect("index") return render(request, "edit.html", {"image": current_image}) I have this edit_image view which isn't updating the image to a new image. Why is it happening and how do i fix it. I tried the above code and I expected the image to change to a new image after the user chooses an image and submits it. -
HTTP Error 500.0 - Internal Server Error An unknown FastCGI error occurred
HTTP Error 500.0 - Internal Server Error An unknown FastCGI error occurred Most likely causes: IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred. IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly. IIS was not able to process configuration for the Web site or application. The authenticated user does not have permission to use this DLL. The request is mapped to a managed handler but the .NET Extensibility Feature is not installed. Things you can try: Ensure that the NTFS permissions for the web.config file are correct and allow access to the Web server's machine account. Check the event logs to see if any additional information was logged. Verify the permissions for the DLL. Install the .NET Extensibility feature if the request is mapped to a managed handler. Create a tracing rule to track failed requests for this HTTP status code. For more information about creating a tracing rule for failed requests, … -
raise e.__class__( ValueError: Field '_id' expected a number but got 'get_recent_products'. ->?
in windows 10 , i'm using react-router-dom 5.2.0 and react-redux 7.2.5 and react 17.0.2 and axios 0.21.4 and WebStorm 2023.1.3 IDE and PyCharm Community Edition 2023.2 and djangorestframework==3.14.0 and Django==4.2.4 and djangorestframework-simplejwt==5.3.0. Note: Although this question is repeated, I hope that I will not encounter a typo error in this forum, because I really did not find the answer in the set of answers that I searched and observed, and also this error in this program is very stupid and I do not have a specific answer for it, so I have to ask my question. Should I bring it up? information: Actually, in this class based view of Django, I have used pagination for django-rest-api, and my project encountered this error after these changes, and in fact, first in the functional form of this Django view, product_id or ID I had used the product, but I deleted it because I didn't need it, so I applied the necessary changes to the url and django class base view and deleted the product id, but still my project is missing the id due to this error. Despite these modifications it shows in product_urls.py and product_views.py BACKEND: Consider - product_views.py: class GetRecentProducts(GenericAPIView): … -
How to Execute Oracle SQL Query with Multiple Database Links in Django?
I'm working on a Django project where I need to execute a complex Oracle SQL query that involves multiple database links. I have already configured the database credentials for both databases in my Django settings, but I'm struggling with how to correctly execute a query that fetches data from different databases through these links. Here's a sample of the type of query I'm trying to execute: SELECT CASE WHEN ACDMH_LOC_CODE LIKE '02%' THEN 'KHOBAR' WHEN ACDMH_LOC_CODE LIKE '03%' THEN 'RIYADH' ELSE 'JEDDAH' END AS Region, ACDMH_INTF_YN, ACDMH_TRANSACTION_TYPE AS TRANSACTION_TYPE, ACDMH_SOURCE_DOC_NO AS SOURCE_DOC_NO, TO_CHAR(ACDMH_TRANSACTION_DATE, 'dd-MM-yyyy') AS TRANSACTION_DATE, ACDMH_CUSTOMER_ID AS CUSTOMER_No, CUSTOMER_NAME, TO_CHAR(ACDMH_CRE_DATE, 'dd-mm-yyyy') AS Pushed_date_WinIT, TO_CHAR(ACDMH_CRE_DATE, 'hh:mi:ss AM') AS Pushed_time_WinIT, ACDMH_INTF_ORA_REF AS ERP_REF, ACDMH_LOC_CODE AS LOC_CODE, ACDMD_ORIGINAL_INVOICE_NO AS ORIGINAL_INVOICE_NO, ACDMD_OLD_VALUE AS fake_PRICE, ACDMD_NEW_VALUE AS selling_price, ACDMD_TOTAL AS tran_value, ACDMD_TAX_AMOUNT AS TAX_AMOUNT FROM AX_CREDIT_DEBIT_MEMO_HEADERS@erpbridge INNER JOIN AX_CREDIT_DEBIT_MEMO_LINES@erpbridge ON ACDMH_HEADER_ID = ACDMD_HEADER_ID LEFT JOIN AXKSA_ORACLE_CUSTOMER ON CUSTOMER_NUMBER = ACDMH_CUSTOMER_ID WHERE [some conditions]; This query involves database links (@erpbridge) to other sources. I'm unsure how to execute such a query in Django, especially considering the database links. I have the following questions: How can I execute this Oracle SQL query in Django, given the use of multiple database links? Are there any specific configurations … -
Slugify when editing an entry
By adding prepopulated_fields = {'slug': ('title',)} to admin model, Django slugifies the slug field in real-time i.e. as I type in the title field, but only when adding a new entry. After the entry is saved and I come back to edit the title field, the slugification (that's not a word) does not happen and I have to override the save() method to re-slugify, however that doesn't provide the real-time functionality. I have tried to find something related by looking at the source code of the templates, but failed. So is there any way to achieve the real-time slugification of the prepopulated field when editing an entry? -
Use serializer in Django (GeoDjango) to include both model field and some related ForeignKey fields
In my Django project, I have two model Home and Tenant. model Home is based on geodjango model and has a PointField. Model Tenant has the person information, and also has a ForeignKey to a Home. from django.db import models from django.contrib.gis.db import models as geomodels class Home(geomodels.Model): location = models.PointField() code = models.IntegerField() # many other fields class Tenant(models.Model): home = models.ForeignKey(Home, on_delete=models.CASCADE) person_name = models.TextField() # many other fields I use serializer to turn a Queryset of Homes into geojson. The thing is, I want to also include some fields of the last Tenant model object of each well in that geojson, too (As they are home fields, but with a prefix tenant__ to have seperated name from original home fields). I also prefer not to use Django-Rest-Framework. Could you help me? -
Azure SpeechSynthesizer Problem with Safari Browser
We have a ReactJS frontend app, using Django (rest framework) as backend. We are developing an AI-Based Avatar Assistant for businesses which would answer various questions. Here is a demo page: https://sales.airdec.net/ The problem is we have no issue with the process of making the avatar talk in Chrome or Firefox. Although it won't work it Safari Browser. I've been searching for a week now and still have no clue what could be the reason. reproduce problem: Navigate here: https://sales.airdec.net/ Click on the hamburger menu and then Introduction OR Just ask a question At first i was using NodeJS as the backend and was having a request/response error in Safari only (preflight response is not successful 421) So, i decided to transfer the code to Python/Django (the one i have more experience in) and now it still not working despite having no network or console error. -
Django Dynamic Navbar Links
I have a Django website where I have two separate user bases, one is CustomUser the other is Agent. Both models extend AbstractUser model. Now I have separate login urls for both and both logins work fine, like Agents can login through AgentSignIn form only and users can login through UserSignIn form only. But now a problem is that when I login as an Agent through AgentSignIn form, I want to show the links Dashboard(agent dashboard) and Agent Sign Out instead of Sign In and Agent Sign In links. But the problem is I don't know how to let my home view know if an Agent is authenticated or a user. Also how do I write the base.html code? My models.py: class CustomUser(AbstractUser): email = models.EmailField(unique=True) groups = models.ManyToManyField(Group, related_name='CustomUser_set', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.') user_permissions = models.ManyToManyField(Permission, related_name='customuser_set', blank=True, help_text='Specific permissions for this user.') is_user = True class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) phonenumber = models.IntegerField() def __str__(self): return f'{self.user.username} Profile' class Agent(AbstractUser): username = models.CharField(max_length=100, unique=True) name = models.CharField(max_length=100) agent_email = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=200) image = models.ImageField(upload_to = 'Images/') bio = models.TextField() …