Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to filter the first 4 objects of a model
I wanna get the first 4 Blog objects associated with the Blog Model. I tried this: #views blog_list = blog.objects.all().order_by("id")[:4] This works until I create more than 4 blog objects, and then the result doesn't include the recently created objects rather it gets stuck with the first 4 objects. -
How to create a statistics endpoint?
I'm learning DRF and I've been stuck on this for a few days. I'm trying to create an endpoint that receives a date range .The response should return a report with the monthly sales distribution for the selected period between date_after and date_before. The value field should contain the total sum of all sold products in this month. Input: 127.0.0.1:8000/api/stats/?date_after=2022-08-12&date_before=2022-08-29 Desired response: [ { month: “2022 Jan”, value: 18.00 }, { month: “2022 Feb”, value: 36.00 }, ] My models: class Product(models.Model): title = models.CharField(max_length=200) price = models.DecimalField(max_digits=1_000, decimal_places=2) def __str__(self): return self.title class Order(models.Model): date = models.DateField() # TODO: Add auto_now_add True products = models.ManyToManyField(Product, blank=True, related_name='orders') My viewsets: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer class OrderViewSet(viewsets.ModelViewSet): queryset = Order.objects.all().order_by('-date') serializer_class = OrderSerializer My serializers: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id', 'title', 'price'] class OrderSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): products = ProductSerializer(many=True, required=False, read_only=False) class Meta: model = Order fields = ['id', 'date', 'products'] I have no idea how to go about this so I've just been blindly scouring the docs. Any help is greatly appreciated. -
How to implement the penalty in loan
In Django Rest Framework, I'm creating a loan API. Can someone suggest how I implement the penalty function? This is how the penalty works. If the loan is not fully paid by 3 months, the remaining balance will be penalised by 1%, and then by another 1 month, if not fully paid, the remaining balance will be penalised by 1% again. For example, if I loan 50,000 on 8-23-2022, I will be penalised 1% of the remaining balance on 11-23-2022 and then by next month, 12-23-2022, if not fully paid, penalised again of 1%. this is my model for loan: class Loan(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) loan_amount = models.IntegerField() date = models.DateField(auto_now_add=True) and this is model for payments class LoanPayment(models.Model): loan = models.ForeignKey(Loan, on_delete=models.CASCADE) payment_amount = models.IntegerField() date = models.DateField(auto_now_add=True) -
Django QuerySet filter by Range with DateTimeField
I tried to fix my queryset method, checked some answers on Stackoverflow, but still couldn't do it. Basically i want to validate my form, so when there is an lesson within ceratin range, a Student cannot propose this specific timerange to it's lesson. The problem is that when i try to find a queryset withing DateTimeField that exists, i still got an empty queryset: My model: class Lesson(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.ForeignKey(Classroom, on_delete=models.CASCADE) description = models.CharField(max_length = 200) start_time = models.DateTimeField() end_time = models.DateTimeField() accepted = models.BooleanField(default=False) Method in form: def clean(self): cleaned_data = super().clean() lesson_start_time = cleaned_data.get('start_time') lesson_end_time = cleaned_data.get('end_time') queryset = Lesson.objects.filter(start_time__range=(lesson_start_time,lesson_end_time)) print(lesson_start_time) #2022-08-23 15:44:00+00:00 print(lesson_end_time) #2022-08-23 15:36:00+00:00 print(queryset) # <QuerySet []> if lesson_end_time < lesson_start_time: raise ValidationError("End time cannot be lower than start time!") And there is for sure a Lesson Object within this range. What i know for now is that it requeries something else to filter DateTimeField by range, but everything that i tried didn't work (for example: Django - Filter objects by DateTimeField with a date range). Could you please help me? -
Linking to different models problem Django
I have to models models.py class Member(models.Model): full_name = models.CharField(max_length=125, unique=True) email = models.EmailField(max_length=125, blank=True, null=True) phone = models.CharField(max_length=20) detail = models.CharField(max_length=256, blank=True, null=True) image = models.ImageField(max_length= 256, upload_to='media', null=True, blank=True) date_created = models.DateTimeField(default=django.utils.timezone.now) class Meta: verbose_name_plural = "All Members" def __str__(self): return str(f"{self.full_name}") def save(self, *args, **kwargs): # delete old file when replacing by updating the file try: this = Member.objects.get(id=self.id) if this.image != self.image: this.image.delete(save=False) except: pass # when new photo then we do nothing, normal case super(Member, self).save(*args, **kwargs) class ActiveMember(models.Model): member = models.OneToOneField(Member, on_delete=models.CASCADE, related_name='is_member') start_date = models.DateField(default=django.utils.timezone.now) end_date = models.DateField(default=django.utils.timezone.now) status = models.CharField(max_length=2, choices=(('1','Active'), ('2','Inactive')), default = '1', blank=True, null=True) def __str__(self): return str(f"{self.member}") Just to get an idea of the site see picture. When I click on active (on Navbar) then under Actions edit. I am redirected to second image. This works fine for a while then after sometimes if I click on Harry it will take me to Ron or someone else. There's a problem with the Id that is being passed when a member is edited updated or deleted maybe everything gets screwed and stops working properly. I have to delete the database and starts again and it works again for awhile. … -
How to join values of two tables. python django
I am trying to use two tables inside one django query. But my query is resulting as "invalid JSON" format. I want to filter data in Request table by (status="Aprv"). The Request table contains attributes 'from_id' and 'to_id'. The uid is the id of the user who is currently logged in. If the current user(uid) is having the 'from_id' of Requests table, the query should return data of 'to_id' from the 'RegUsers' table. If the current user(uid) is having the 'to_id' of Requests table, the query should return data of 'from_id' from the 'RegUsers' table. class frnds(APIView): def post(self, request): uid = request.data['uid'] ob = Requests.objects.filter(status="Aprv") fid = ob.value('from_id') tid = ob.value('to_id') if fid == uid: obj = RegUsers.objects.filter(u_id=tid) else: obj = RegUsers.objects.filter(u_id=fid) ser = android_serialiser(obj, many=True) return Response(ser.data) Please Do Help me Currect the syntax. -
Django: How to navigate multi-level reverse relationships?
I have several models that are related hierarchically: Projects have one or more Experiments Experiments have one or more Scans Scans have one or more Scan Decisions Simplified Models: class Project(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) class Experiment(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255, blank=False) project = models.ForeignKey('Project', related_name='experiments', on_delete=models.CASCADE) class Scan(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=127, blank=False) experiment = models.ForeignKey('Experiment', related_name='scans', on_delete=models.CASCADE) class ScanDecision(models.Model): id = models.UUIDField(primary_key=true, default=uuid4, editable=False) scan = models.ForeignKey('Scan', related_name='decisions', on_delete=models.CASCADE) If I have a specific Scan Decision and I want to get the Project associated with that decision, how can I do so? The Django documentation speaks of backward relationships but the examples seem limited to a single level of relationship. For example, to get the ScanDecision associated with a Scan I could do something like: sd = ScanDecision.objects.get(id=1) sd.scan_set.all() # Returns all scan objects related to the specific ScanDecision But what if I want to get the Project that is associated with the ScanDecision indirectly through Scan and Experiment? e.g., something like this but without all the steps? sd = ScanDecision.objects.get(id=1) # The desired ScanDecision object s = sd.scan_set.all() # Gets the related Scan object e … -
whoosh schema in haystack and django
I am trying to integrate a whoosh searcher into a django project. I saw that you can do that using haystack but I am realizing I can't (dont know yet) how to add my custom whoosh index into the searcher. My schema has ID, KEYWORD and TEXT but they are all text in reality. I used these schemes because it suits my search needs for each of the documents. How do I use this schema in Haystack. PS: A solution without Haystack is ok too. Here is my whoosh schema/writer/searcher import pandas as pd from whoosh.index import create_in from whoosh.fields import * from whoosh.qparser import QueryParser from whoosh.query import * def nan2none(x): y = None if pd.isna(x) else x return(y) df = pd.read_csv("df.csv", index_col=[0]) schema = Schema(a = ID(stored=True), b = KEYWORD(lowercase=True), c = TEXT, d = KEYWORD(lowercase=True)) ix = create_in("indexdir", schema) writer = ix.writer() for index, row in df.iterrows(): writer.add_document(a = index, b = nan2none(row['b']), c = nan2none(row['c']), d = nan2none(row['d'])) writer.commit() search_term = "hobbit" with ix.searcher() as searcher: a_query = QueryParser("a", ix.schema).parse(search_term) b_query = QueryParser("b", ix.schema).parse(search_term) c_query = QueryParser("b", ix.schema).parse(search_term) d_var_query = QueryParser("d", ix.schema, termclass=Variations).parse(search_term) d_fuzz_query = QueryParser("d", ix.schema, termclass=FuzzyTerm).parse(search_term) query = Or([a_query, b_query, c_query, d_var_query, d_fuzz_query]) results … -
Field 'mobile' expected a number but got ['2222222', '2222222']
This is Error showing TypeError at /page Field 'mobile' expected a number but got ['22222', '3333']. Request Method: POST Request URL: http://127.0.0.1:8000/page Django Version: 4.1 Exception Type: TypeError Exception Value: Field 'mobile' expected a number but got ['22222', '3333']. While Submitting Form This error occurs. I am trying to submit form of same name twice simultaneously to same model Views.py def page(request): if request.method == 'POST': description = request.POST['description'] price = request.POST['price'] name = request.POST.getlist('name') mobile = request.POST.getlist('mobile') pay = bill(description=description,price=price) pay.save() mypayee = payee(billId=pay,name=name,mobile=mobile) mypayee.save() return render(request, 'split_app/page.html') this model from django.db import models # Create your models here. class bill(models.Model): price = models.IntegerField() description = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.description class payee(models.Model): billId = models.ForeignKey(bill,on_delete=models.CASCADE,related_name='persons') name = models.CharField(max_length=50) mobile = models.IntegerField() this is image of HTML FORM generated using javascript enter image description here ** This is how I am submitting data with form having same form twice of same name(name & mobile) ** HTML generate <div class="container my-3"> <button type="button" class="btn btn-secondary">ADD NEW BILL</button> <form action="/page" method="POST"> {% csrf_token %} <div class="input-group mb-3"> <label for="discription" class="col-sm-2 col-form-label">DESCRIPTION:</label> <div class="col-sm-2"> <input type="text" name="description" id="discription" placeholder="Bill For.." /> </div> </div> <div class="input-group mb-3"> <label for="price" class="col-sm-2 … -
In Django define a validation function to avoid number overlaps
In django apps i have a model for the range number In my model.py def valide_range(value): all_ranges = RangeNumber.objects.all() for a_range in all_ranges: if a_range.start_num_int <= value <= a_range.end_num_int: raise ValidationError('The number is in an exiting number range') class RangeNumber(models.Model): start_num = models.IntegerField(validators=[valide_range]) end_num = models.IntegerField(validators=[valide_range]) This validation is ok for the create range but not for the udapte range, because is check all range(the edited range and the other), for the update I want just check the other. Thanks -
Django - NOT NULL constraint failed with modelchoicefield
I am making an auction site for an assignment, but I cannot manage to make the category non-obligatory when creating a new listing. I get a NOT NULL constraint failed error after pressing "Create listing", while I have null=True and blank=True in my model. What am I doing wrong? my category model looks like this: class Category(models.Model): name = models.CharField(max_length=64, blank=True, null=True) def __str__(self): return self.name forms.py looks like this: class CreateListing(forms.ModelForm): category = forms.ModelChoiceField(queryset=Category.objects.all(), empty_label="No category", required=False) class Meta: model = AuctionListing fields = ('title', 'description', 'starting_bid', 'url', 'category', 'user') widgets = { 'title': forms.TextInput(attrs={'placeholder':'Write your listing title here...'}), 'description': forms.Textarea(attrs={'placeholder':'Write your comment here...', 'rows':3}), 'user': forms.HiddenInput(), } def __init__(self, *args, **kwargs): user = kwargs.pop('user') super().__init__(*args, **kwargs) self.fields['user'].initial = user.id And this is the view for creating a listing: def create_listing(request): form = CreateListing(request.POST, user=request.user) if request.method == "POST": if form.is_valid(): form.save() return HttpResponseRedirect(reverse("index")) else: print("RIP") return render(request, "auctions/create_listing.html", {"form": form}) return render(request, "auctions/create_listing.html", { "form" : CreateListing(user=request.user) }) -
RemovedInDjango20Warning: Error handlers should accept an exception parameter. Update your code as this parameter will be required in Django 2.0
Hi Stackoverflow community, does anybody knows how to cope with the Django warning? RemovedInDjango20Warning: Error handlers should accept an exception parameter. Update your code as this parameter will be required in Django 2.0 -
Jquery code in my django app is not working
Well i have an issue with my Jquery code.I'm including my script file - which depends on jQuery - after jQuery. So i dont know what is the issue. The HTML page i extended jquery from : <!-- Core JS --> <!-- build:js assets/vendor/js/core.js --> <script src="{% static 'main/vendor/libs/jquery/jquery.js' %}"></script> <script src="{% static 'main/vendor/libs/popper/popper.js' %}"></script> <script src="{% static 'main/vendor/js/bootstrap.js' %}"></script> <script src="{% static 'main/vendor/libs/perfect-scrollbar/perfect-scrollbar.js' %}"></script> <script src="{% static 'main/vendor/js/menu.js' %}"></script> <!-- endbuild --> <!-- Vendors JS --> <!-- Main JS --> <script src="{% static 'main/js/main.js' %}"></script> <!-- Page JS --> {% block js %} {% endblock %} HTML with ajax code <script> paypal .Buttons({ createSubscription: function (data, actions) { return actions.subscription.create({ plan_id: "my plan", // Creates the starter plan }); }, onApprove: function (data, actions) { $.ajax({ type: "POST", url: "{% url 'payment-success' %}", data: { subscriptionID: data.subscriptionID, userId: "{{user.profile.uniqueId|safe}}", csrfmiddlewaretoken: "{{csrf_token}}", }, sucess: function (data) {}, }); }, onCancel: function (data) { $.ajax({ type: "POST", url: "{% url 'payment-success' %}", data: { 'userId': "{{user.profile.uniqueId|safe}}", 'csrfmiddlewaretoken': "{{csrf_token}}" }, sucess: function (data) { alert(data.result); } }); alert("You have canceled your subscription"); } }) .render("#paypal-button-container-1"); // Renders the PayPal button </script> My views.py from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth.models import … -
Django template looping for each character
I have a text file like generated from 100 Cisco switches like this: ['device1', 'device2', 'device3', 'device4', ....., deviec100] and I want to show this information using loop in template. So I have something like this in my HTML file to loop through each device: {% for x in devie_list %} {{ x }} {% endfor %} But it is just adding a space between each character, so the result is like this: [ ' d e v i c e 1 ' , ' d e v i c e 2 , .... ] How can I tell Django, to loop through each item within the commas? or better say each list item. -
django.utils.datastructures.MultiValueDictKeyError: 'file'
Hey i got this function to save file into folder. @csrf_exempt def SaveFile(request): file=request.FILES['file'] file_name=default_storage.save(file.name,file) return JsonResponse(file_name,safe=False) Firstly it worked fine, i managed to upload image. But after few tries it stopped working showing the error like this: django.utils.datastructures.MultiValueDictKeyError: 'file' [22/Aug/2022 15:58:34] "POST /events/savefile HTTP/1.1" 500 72933 I upload it with postman, post method-body-form-data, no idea where is the problem. I read some posts about that, tried to add get after file=request.FILES['file'], but didnt worked. Any advice where could be the problem? -
Assign RBAC role to ManagedIdentity from python function
I have an azure python function which creates bunch of resources and after they are created, I need to assign some roles to Web App hosted on Azure so it can access those newly created resources and that web app use System Assigned Managed Identity. That Azure python function also use system assigned Managed Identity. If I will use code credential = ManagedIdentityCredential() this will return credentials for my azure python function. How can I get to Managed Identity of the Web App in my azure function so I can start assigning some roles? I know I should use AuthorizationManagementClient but it need credential token and in case of system assigned managed identity, there are no parameters for ManagedIdentityCredential() so I can't point to that Web App. -
Getting an error App 'org' doesn't have a 'Topic' model when running tests in django app
I have the below function in the migrations file to add initial data to db: def add_topics(apps, schema_editor): topic_model = apps.get_model('org', 'Topic') for topic in TOPICS: topic_model.objects.get_or_create(name=topic['name'], display_name=topic['display_name']) However running tests is giving an error, in get_model LookupError: App 'org' doesn't have a 'ContextualSubTopic' model. App 'org' doesn't have a 'Topic' model. -
Best way to get the model object that has a DateTime field closest in DateTime to current DateTime
I want to make an efficient ORM query that returns the model object in which the objects datetime is the closest to the current datetime. So if the current datetime is 22/08/2022 15:00 and I have objects with datetimes of object1.datetime == 22/08/2022 15:30 and object2.datetime == 22/08/2022 15:45 I want to be able to query the DB for the object with the closest datetime which would be the object1 object. So basically I want to find the object that is closest, in the future, to the current datetime. The only solutions I've been able to think of are inefficient and involve looping and comparing multiple objects by adding them to lists etc. dt = datetime.datetime.now() objs = Model.objects.all() for obj in objs: if obj.dateTime //etc... Obviously this isn't a good solution because it's going to loop through my whole model database. How can I make this query in the most efficient way? -
What is the use of token return after login or registration from django-rest-knox?
Hy there, I work on project where I used django-rest-knox for token authentication. I have doubt that 1.How token be used that has return while registering and login. ( when i pass token in postman as like, in header section Authentication Token abcjdkkfjjrhehrjlajn@kfjdk ) this doesnot work 2.when i call logout and logoutall endpoint it say, { "detail": "Authentication credentials were not provided." } even though i pass all correct credentials. Here is the code that i follow, in setting.py REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( 'knox.auth.TokenAuthentication', "rest_framework.authentication.BasicAuthentication", "rest_framework.authentication.SessionAuthentication",)} REST_AUTH_TOKEN_MODEL = 'knox.models.AuthToken' REST_AUTH_TOKEN_CREATOR = 'users.authentication.create_knox_token' REST_AUTH_SERIALIZERS = { 'USER_DETAILS_SERIALIZER': 'users.serializers.CustomUserSerializer', 'TOKEN_SERIALIZER': 'users.serializers.KnoxSerializer' } in urls.py path('auth/register/',KnoxRegisterView.as_view(),name='register'), path('auth/login/',KnoxLoginView.as_view(),name='login'), path('api/auth/logout/',knox_view.LogoutView.as_view(),name='knox_login'), path('api/auth/logoutall/',knox_view.LogoutAllView.as_view(),name='knox_alllogin'), in authentication.py from knox.models import AuthToken def create_knox_token(token_model, user, serializer): token = AuthToken.objects.create(user=user) return token in serializers.py class KnoxSerializer(serializers.Serializer): """ Serializer for Knox authentication. """ token=serializers.CharField() user = CustomUserDetailsSettingsSerializer() in views.py class KnoxRegisterView(RegisterView): def get_response_data(self, user): return KnoxSerializer({'user': user, 'token': self.token}).data def perform_create(self, serializer): user = serializer.save(self.request) self.token = create_knox_token(None, user, None) complete_signup(self.request._request, user, allauth_settings.EMAIL_VERIFICATION, None) return user class KnoxLoginView(LoginView): def get_response(self): serializer_class = self.get_response_serializer() data = { 'user': self.user, 'token': self.token } serializer = serializer_class(instance=data, context={'request': self.request}) return Response(serializer.data, status=200) -
How to automatically replace a word with another?
I am currently using Django 4.0 and trying to find a way to transform the following: [year] to the current year. It needs to be automatically replaced every time [year] is found. Be it from the admin panel, from CKEDITOR, or comments, etc. I can find ways to do this when [year] is hardcoded, but I don't know how to make it work when I am posting a blog post from Django Admin, for example. To also add, I have tried using JS to transform the [year] tag to the current year. The problem with this is that it doesn't work on the page title or for search engines. They will still index the page with [year] instead of 2022, for example. Using JS works well for people, but not from a SEO perspective. Your help would be appreciated! Thanks. -
Django query if / else?
I'm building a website that displays photo albums. For that I have the following Models. class Medium(models.Model): pass class MediaSet(models.Model): media = models.ManyToManyField("Medium", related_name="sets", through="SetContent", through_fields=('set', 'medium'),) class SetContent(models.Model): is_cover = models.BooleanField(default=None, null=True) set = models.ForeignKey("MediaSet", on_delete=models.CASCADE, related_name="set_content") medium = models.ForeignKey("Medium", on_delete=models.CASCADE, related_name="set_contents") Every MediaSet(=Album) might have a cover. If it doesn't I will just use the first image in there. Now I'm trying to optimize the DB by reducing queries. I'm working on the MediaSetListView which lists MediaSets. Is it possible at the Query level to annotate or Prefetch() a cover (one Medium) depending on whether is_cover exists or not? In other words: Get a list of all mediasets and have every mediaset have a cover that is either the Medium marked as "is_cover" in SetContent or else the first Medium in SetContent. Currently I have this logic in the model, but that leads to tons of queries which I don't want. Thanks for your help. -
Python, Django: Test Custom Command with Mock
I have a very basic custom management command inside my django-application: management-command: from django.core.management import BaseComman class Command(BaseCommand): help = 'Just do some stuff here...' def handle(self, *args, **kwargs): # Let's pretend I'm doing something really important here!? pass test_managements.py: import django.core.management from django.core.management import call_command from django.test import TestCase from unittest import mock class TestCommands(TestCase): def test_do_something(self): with mock.patch.object(django.core.management, 'module') as mock_management: call_command('do_something', [], {}) mock_management.assert_called_once() I'm starting new with mocking inside my django-application and found some piece of code in another post here. I've tried to modify it to my use, but whenever I'm trying to run a test, it's saying that django.core.management doesn't have a module. Unfortunately there is no explanation what module stands for. The idea is to check, if the management-command gets called one single time. Does anyone has an idea or maybe did it for himself and can help me out. Unfortunately there are only a few code examples out there for mocking inside django. Thanks and have a great day! -
Django inject data after base.html
I have a base.html file which is a side bar menu. like this: <body> <div class="wrapper"> <nav id="sidebar"> <div class="sidebar-header"> <h3>Welcome!</h3> </div> <ul class="list-unstyled components"> <li class="active"> <a href="#list">List</a> </li> <li> <a href="#">Item 1</a> </li> <li> <a href="#">Item 2</a> </li> </ul> </nav> </div> </body> I also have a text file that I want to show the content. So I configured my view like this: def list(request): f = open('textFile.txt', 'r') file_content = f.read() f.close() context = {'file_content': file_content} print(file_content) return render(request, "list.html", context) The destination HTML file which is going to show the data is like this: {% extends 'base.html' %} {{ file_content }} The problem is, the text file data is now showing up. and if I remove {% extends 'base.html' %} them the text file data shows up, but I lose the side bar. How can I resolve this issue? -
What could cause django's FilteredSelectMultiple right half not to display 'initial' values after page reload (Ctrl R)?
I was under the impression that if I do something like this: self.fields["xxx"].initial = termin.getXxx.all() then the widget's right half will display the value of termin.getXxx.all() And it is true, almost always. Except if I reload the page using 'Ctrl R' because then I get the right half completely empty, even though self.fields["xxx"].initial does contain the required value. What is so special about 'Ctrl R' that breaks the widget? Below the widget's code: xxx = forms.ModelMultipleChoiceField( queryset=Person.objects.none(), widget=OurFilteredSelectMultiple("XXX", is_stacked=False), required=False, ) class OurFilteredSelectMultiple(FilteredSelectMultiple): class Media: js = ( "/jsi18n/", "/static/core/admin/js/our_filtered_multi_select_widget.js", ) css = {"all": ("/static/core/admin/css/our_filtered_multi_select_widget.css",)} def render(self, name, value, attrs, renderer): """! Adding the id of the field to an hidden input. @detail These widgets HTML-elements get their id based on the id of the field. In order to use it in JS we set up this hidden parameter and get the value inside js. """ identifier = "multiple_select_id" ret = super().render(name, value, attrs, renderer) ret += f'<input type="hidden" id="{identifier}" value="{attrs.get("id")}">' return mark_safe(ret) -
Admin site for custom user model and extended user model
My Django app needs custom user model and some additional fields so I have defined them as below: Custom User Model and Manager (defined in an app called users): class CustomUserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self._create_user(email, password, **extra_fields) class CustomUser(AbstractUser): username = None email = models.EmailField(unique=True) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email Extra model field (defined in an app called api): class Customer(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created = models.DateField(auto_now_add=True) The Admin Site (defined in users app): class CustomerInline(admin.StackedInline): model = Customer readonly_fields = ('created',) @admin.register(CustomUser) class CustomUserAdmin(UserAdmin): inlines = (CustomerInline,) list_display = ('email', 'is_active', 'is_staff', 'is_superuser') list_filter = ('email', 'is_active', 'is_staff', 'is_superuser') fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name')}), ( ('Permissions'), { 'fields': ( 'is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions', ) }, ), ) add_fieldsets = ( ( None, { 'classes': ('wide',), 'fields': ( 'email', 'password1', 'password2', 'is_active', 'is_staff', 'is_superuser', ), }, ), ) search_fields = ('email',) ordering = ('email',) …