Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Use the different field for password in the Custom User Model
When you use the Custom User Model, you can change the "username" field using the USERNAME_FIELD = 'identifier' Is there a way to do similar thing for the "password" field? Something like PASSWORD_FIELD = 'my_password_field' If not, is there any was to store the password not in the default "password" field of the user model? No code tried because I don't know what to write in this case. Django docs contains the instruction about changing the changing the used identifier, but nothing about password. -
Wrong environment in Django
I'm a beginner at Django Web Framework.At the beginning when I start Django project I didnt see venv folder like on the picture on the left.I didnt have bin ,lab , gitignore and pyvenv.cfg files on the right picture.When I made new env I see venv folder but also there are duplicate bin and lib folders.All I want for now is when I start new Django project is to have one VENV folder and that it's gonna be my only enviornment and also bin and lab folders be in venv folder. What I try is this: That was the commands I enter on my MAC. pip install virtualenv virtualenv venv source venv/bin/activate That made a new env and folder venv.But I dont want to have another basic enviornemnt with name of the project like on the picture on the right.I dont want to have in project folder bin and lib folder also. Sorry for my english... -
I need help properly implementing a booking scheduler and availability in Django
This question has been asked many times before on StackOverflow and in the Django forums, but none of the answers I've found are appropriate or complete enough for my situation. First, the brief: I'm creating a web application for a car rental business. In addition to helping them organize and centralize their fleet, it will also help them collect orders directly from customers. As with most rentals, the logistics of it all can be somewhat confusing. Someone may place an order for a car today (December 12th) but actually take the car over the Christmas to New Year's period. A renter may borrow a car for just two days, and then extend the booking at the last minute. When this happens (often very frequently), the business usually has to scramble to find another one for a different customer who was scheduled to get that car the next day. Adding to that, an individual car can only be rented to one client at a time, so it can't have multiple bookings for the same period. Most answers advocate for a simple approach that looks like this: models.py class Booking(models.Model): car = models.ForeignKey(Car, ...) start_date = models.dateField(...) end_date = models.dateField(...) is_available = … -
how to get value from promise and how to get promise resolved
this is my javascript code . I'am trying to get data from backened through axios. how can i get the value in subs variable ? var subs = axios.get("/getdata/", ).then( function(resp){ console.log("respons",resp.data.value); return resp.data.value; }) .catch( function(err){ console.log(err); }) console.log(subs) // console result on browser. How to fulfill this pending promise ? Promise {<pending>} [[Prototype]]: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: "false" views.py file code def data_to_api(request): if request.method == "GET": user_name = request.user.get_username() print(user_name) user_obj = All_users.objects.get(username=user_name) subs= str(user_obj.subs_detail).lower() print(subs) request.data = subs data = { "value":subs, } return JsonResponse(data) -
Error No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
i'm working on a django project to create football trainings. I'm testing the model and its saving. The problem appears when I try to save it, must be something about redirection, because in the database the training does get saved, but it doesn't redirect me anywhere and the error comes out. models.py from django.db import models from django.utils import timezone from users.models import User class Entrenamiento(models.Model): autor = models.ForeignKey(User, on_delete=models.CASCADE) idEntrenamiento = models.AutoField(primary_key=True) idEquipo = models.IntegerField() fecha = models.DateTimeField(default=timezone.now) idDireccionCampo = models.IntegerField() temporadas = [ ('2022/2023','2022/2023'), ('2023/2024','2023/2024'), ('2024/2025','2024/2025'), ('2025/2026','2025/2026') ] temporada = models.CharField(max_length=50, choices=temporadas, default='2022/2023') def __str__(self): return 'Entrenamiento {}'.format(self.idEntrenamiento) @property def entreno(self): return 'Entrenamiento {} de {} para {} con fecha del {}, será en el campo {}'.format(self.idEntrenamiento, self.temporada, self.idEquipo, self.fecha, self.idDireccionCampo) views.py from django.conf import settings from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.messages.views import SuccessMessageMixin from django.contrib.auth.models import User from django.contrib import messages from django.http import HttpRequest, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.views.generic import (CreateView, DeleteView, DetailView, ListView,UpdateView) from django import forms from django.urls import reverse_lazy from .models import Entrenamiento def home(request): context = { 'entrenamientos': Entrenamiento.objects.all() } return render(request, 'entrenamientos/entrenamientos.html', context) class PostListView(ListView): model = Entrenamiento template_name = 'entrenamientos/entrenamientos.html'#<app>/<model>_<viewtype>.html context_object_name = 'entrenamientos' ordering = ['-fecha'] … -
Celery not retrying when an exception is raised when testing in Django
I have a class based celery task, which I would like to test by raising an error and then confirming that retry has been called. During the test, I want to raise a ConnectionError when msg.send() is called and then confirm that it is being 'retried'. The task essentially constructs an email using django.core.mail.EmailMultiAlternatives (which inherits EmailMessage) and then attempts to send that email. The task works well in practice, with a retry being called if a connection does not exist, my only problem is how to test it. So far, I have managed to raise the ConnectionError by patching EmailMultiAlternatives, however, the test does not trigger a retry in the celery terminal. tasks.py (Simplified) class SendMail(Task): max_retries = 4 base = 'BaseTask' def run(self, **kwargs): msg = EmailMultiAlternatives(kwargs.get('some_value'), etc.) msg.attach_alternative(rendered_html) try: msg.send(fail_silently=False) except ConnectionError as exc: self.retry(countdown=backoff(self.request.retries), exc=exc) test_task.py (simplified) class SendMailTest(TestCase): def setUp(self): self.message = {some data} def test_error(self): with patch.object(EmailMultiAlternatives, 'send', return_value=None) as mock_method: mock_method.side_effect = Exception(ConnectionError) SendMail(kwargs=self.message) My question is, why, when the test script is run and an exception is clearly being raise, does Celery not attempt to retry? -
How take path in request.FILE['file'] to put it for download link
I create foo to upload files to Django models, its InMemoryUpload object. and how can I collect the full path to download link? my models.py class Document(models.Model): """Class for uplaoded files. colect file and description working with analog form """ id = models.AutoField(primary_key=True) file_path = models.TextField(max_length=255) hash_size = models.CharField(max_length=255) def __str__(self): return f"{self.id},{self.file_path},{self.hash_size}" def get_hash(file: object) -> str: md = hashlib.md5() # with open(file, "rb") as f: for chunk in iter(lambda: file.read(4096), b""): md.update(chunk) return md.hexdigest() my views.py def model_form_upload_1(request: HttpRequest) -> HttpResponse: ''' view handling this form will receive the file data in :attr:`request.FILES <django.http.HttpRequest.FILES>`''' if request.method == 'POST': upload = request.FILES['file'] path = upload.chunks() print(path) hash_tuple = () form = DocumentForm(request.POST, request.FILES) if form.is_valid(): print(upload.size) if get_file_size(upload): hash = Document.get_hash(upload) hash_list = [x for x in Document.objects.all().values_list('hash_size')] hash_tuple += (hash,) if hash_tuple not in hash_list: Document.objects.create( file_path=request.GET.get(upload), hash_size=hash) else: return HttpResponseBadRequest("file bigger tha 300mb") return redirect("view") else: return HttpResponseBadRequest("Form invalid") else: form = DocumentForm() return render( request=request, template_name='model_form_upload.html', context={'form': form}) return render(request, 'model_form_upload.html') return render(request, 'model_form_upload.html') my template.py <tr> <td>{{document.id}}</td> <td>{{document.file_path}}</td> <td><a href="{{ document.file_path }}">download</a></td> <td>{{document.hash_size}}</td> </tr> before I tried to take request.open(file) but it's actually not what I need. -
How to Install WordPress in Django sub directory
My old site is running on Django. Now I want to run a WordPress site on same domain and server through sub directory. I have a created a sub directory "testsite" in public html folder through c panel, created database and user and then installed WordPress into it. And when I tried accessing my site through www.mysite.com/testsite/wp-admin login page appears for WordPress but when tried to login this error message appears Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ superadmin/ about [name='about'] contact [name='contact'] gallery [name='gallery'] The current path, testsite/wp-admin/, didn’t match any of these. How can I solve this issue.. Please help me in this. thanks in advance I want to access www.mysite.com/testsite/wp-admin and can run my WordPress site smoothly without deleting the Django site. Is it possible anyway? -
Any way we can share a specific item publicly from a private S3 bucket?
The question is pretty vague but here's the entire problem statement. I am using Django REST APIs, and I'm generating invocies for my clients. Using wkhtmltopdf, I'm able to generate a PDF file which gets automatically backed up to S3. Now, we need to retreive the said invoice once our client clicks on a link. We're using pre-signed URLs right now, which last for 12 hours, right? Once that link expires, the entire backend fails. I mean, even if we go for permanent pre-signed links, would there not be a security issue? I could really use some guidance on this. -
Notification template only printing out items after the 3rd position
Notification template only printing out items after the 3rd position. When I inspect element to check if its showing up in the frontend, its there, but its just a blank html <p> tag. Other than this minor bug it works fine. Not sure how to proceed, any help is much appreciated. Here are my models.py class Notification(models.Model): MESSAGE = 'message' APPLICATION = 'application' CHOICES = ( (MESSAGE, 'Message'), (APPLICATION, 'Application') ) to_user = models.ForeignKey(User, related_name='notifications', on_delete=models.CASCADE) notification_type = models.CharField(max_length=20, choices=CHOICES) is_read = models.BooleanField(default=False) extra_id = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='creatednotifications', on_delete=models.CASCADE) class Meta: ordering = ['-created_at'] notification views.py @login_required def notifications(request): goto = request.GET.get('goto', '') notification_id = request.GET.get('notification', 0) extra_id = request.GET.get('extra_id', 0) if goto != '': notification = Notification.objects.get(pk=notification_id) notification.is_read = True notification.save() if notification.notification_type == Notification.MESSAGE: return redirect('room', pk=notification.extra_id) elif notification.notification_type == Notification.APPLICATION: return redirect('room', pk=notification.extra_id) return render(request, 'notification/notifications.html') notifications.html template {% extends 'main.html' %} {% block content %} <div class="container"> <h1 class="title">Notifications</h1> {% if not notifications %} No notifications yet! {% endif %} {% for notification in notifications %} <div class="notification"> <p> {% if notification.notification_type == 'message' %} <a href="{% url 'notifications' %}?goto=room&notification={{ notification.id }}&extra_id={{ notification.extra_id }}"> <strong>{{ notification.created_by.username }}</strong> sent you a … -
Django: Strange error with connection between view, template and url
I have two main usage and main model pages, in which products from a specific usage or model are listed. I have the following views for these pages: def get_common_queryset(): usage_queryset = Usage.objects.all() sub_usage_queryset = SubUsage.objects.all() main_model_queryset = MainModel.objects.all() pump_type_queryset = PumpType.objects.all() queryset_dictionary = { "usage_queryset": usage_queryset, "sub_usage_queryset": sub_usage_queryset, "main_model_queryset": main_model_queryset, "pump_type_queryset": pump_type_queryset, } return queryset_dictionary def products_usage_main(request): queryset_dictionary = get_common_queryset() context = queryset_dictionary return render(request, "products/products_usage_main.html", context) def products_model_main(request): queryset_dictionary = get_common_queryset() context = queryset_dictionary return render(request, "products/products_model_main.html", context) Here we have a get_common_queryset() view, which you can read about the reason of it in this question. Then we have two simillar view functions, products_usage_main and product_model_main but with different templates. In the urls.py I have following paths for these views: urlpatterns = [ path("application/", products_usage_main, name="products_usage_main"), path("model/", products_model_main, name="products_model_main"), ] In which, again, we can see that the two paths are similar with just different views. And finally I have two separate templates for these two views, which their code is not needed or related to the problem I'm facing. THE PROBLEM: In my products page sidebar, I have two main links referencing /products/application/ and /products/model/, and when I click on the /products/application/, everything works just fine; but … -
Django database design
I want to design a data model in Django with the following fields. Student's First name Student Lastname Fee per hour Dates and times of attendance. student photo. Boolean field as to student present or absent. I want to have a monthly summary of each student who attended and the total fee for that Month. Similar to a printout I can send to parents as to how much they have to pay. So my website App has to calculate for the end of each month. How do I design it? Thanks for the help -
DJANGO ORM LEFT JOIN [closed]
SQL: ` select u1.summaryUpdatedOn, u2.summary from sdgdb.user as u1 left join sdgdb.user as u2 on u1.user_id = u2.user_id and (u2.summaryUpdatedOn != '20221207030805'or u2.summaryUpdatedOn is null) where u1.sdgid = 'SDG-s6547df1445-ece35e6e-c1ea-45ae-83e8-9d9c19fab0cd'; ` my Models: ` class User(BaseModel): customer = models.ForeignKey( Customer, null=False, on_delete=models.PROTECT, db_column="customerid" ) group = models.ForeignKey( Group, null=False, on_delete=models.PROTECT, db_column="groupid" ) licensetype = models.ForeignKey( LicenseType, null=False, on_delete=models.PROTECT, db_column="licensetypeid" ) sdgid = models.CharField( max_length=64, null=False, default="temp-" + str(uuid.uuid4()), editable=False, db_column="sdgid", ) name = models.CharField(max_length=100, null=False, default=None, db_column="name") email = models.EmailField( max_length=254, unique=False, blank=True, null=True, db_column="email", ) note = models.CharField( max_length=500, null=True, blank=True, default=None, db_column="note" ) licensekey = models.CharField(max_length=100, null=True, db_column="licensekey") isdisabled = models.BooleanField(null=False, default=False, db_column="isdisabled") summary = models.TextField(null=True, db_column="summary") summaryupdatedon = models.CharField( max_length=14, null=True, db_column="summaryupdatedon" ) ` I didn't switch from SQL to API query. Please help me -
Is there a way to encrypt the password when creating a normal user through django admin?
is there any way to save password in encrypted form while creating a new user through django admin? from django.db import models from django.contrib.auth.models import AbstractUser from src.core.models import TimeStamp class User(AbstractUser, TimeStamp): joined_date = models.DateField('date joined', null=True) leave_date = models.DateField('Leave Date', null=True) role = models.ForeignKey("Role", on_delete=models.SET_NULL, null=True) class Meta: verbose_name = 'user' verbose_name_plural = 'users' def __str__(self): """ username of each user """ return self.username Here is my user model given above -
I want red borders on form submit on invalid fields using django template language
This is my html file I want red borders on form submit on invalid fields using django template language I want red borders on form submit on invalid fields using django template language I want red borders on form submit on invalid fields using django template language {% block body %} {% include 'navbar.html'%} <!DOCTYPE html> <html> <head> <title></title> <body> <form autocomplete="off" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> <label for="Title" class="form-label">Title</label> {{form.title}} <div class="form-text">{{form.title.errors}}</div> </div> <div class="mb-3"> <label for="Written By" class="form-label">Written by</label> {{form.written_by}} <div class="form-text"> {{ form.written_by.errors }} </div> </div> <div class="mb-3"> <label for="Description" class="form-label">Description</label> {{form.description}} <div class="form-text">{{form.description.errors}}</div> </div> <div class="mb-3"> <label for="image" class="form-label">Image</label> {{form.image}} <div class="form-text">{{form.image.errors}}</div> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <style> .form-control { width: 50%; } .errorlist { list-style-type: none; color: red; position: relative; right: 31px; } form { margin-left: 30%; margin-right: 30%; } textarea { height: 4em; width: 50em; } </style> </body> </head> </html> {% endblock %} I want red borders on form submit on invalid fields using django template language I want red borders on form submit on invalid fields using django template language I want red borders on form submit on invalid fields using django template language -
Django an JavaScript: document.getElementById return always Uncaught TypeError: Cannot set properties of null (setting 'innerHtml')
I am writing to you because I am stuck on a basic operation (almost ashamed). I'm working on a Django project and what I'm trying to do is: show inside two 'span' tags the length of a list. It's not the first time I've done this and I've always managed to do it. But now I don't understand why it doesn't work. Here is the code: My index.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Free Attitude</title> <!-- BOOTSTRAP CSS --> <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}"> <!-- CSS --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- JS --> <script type="text/javascript" src="{% static 'js/templatesList.js' %}"></script> </head> <body> {% include '_header.html' %} <main class='home-main'> <div class="container"> <section class="row gy-3"> <!-- FOR LG SCREEN --> <div class="col-md-6 text-container d-md-block d-none"> <h2>Modelli per siti web</h2> <h6>Dai un'occhiata ad alcuni modelli già pronti, protresti trovare qualcosa di tuo interesse.</h6> <a href="{% url 'websiteEcomm:home' %}">Vedi tutti e <span id="total-templates-lg"></span> i modelli disponibili</a> </div> <div class="col-md-6 d-md-block d-none"> <div id="carouselExampleSlidesOnly" class="carousel slide" data-bs-ride="carousel" data-bs-interval="2000"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="{% static 'preview-img/arsha.png' %}" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="{% static 'preview-img/digimedia.png' %}" … -
How to Reset form field after submit in HTMX
I'm tried to reset form field after submit the data in HTMX. Please guide me how to do. -
Access fields dynamically in a django serilaizer
I am trying to acsess fields of a model dynamically(on the basis of call from frontend) in the serializer but unable to do so code: class DynamicFieldsModelSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) print("self", self) fields = self.context['request'].query_params.get('fields') if fields: fields = fields.split(',') # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields.keys()) for field_name in existing - allowed: self.fields.pop(field_name) class ProductTestSerializer(DynamicFieldsModelSerializer, serializers.ModelSerializer): class Meta: model = Product fields = ("id",) class ProductTestAPIView(generics.ListAPIView): def get(self, request): obj = Product.objects.all() data = ProductTestSerializer(obj, many=True) s_data = data.data return Response(s_data) URL: http://127.0.0.1:8000/products-test/?fields=id,short_code It returns the following error: KeyError: 'request' at fields = self.context['request'].query_params.get('fields') -
Regarding python django
error while migrating webapp.Login.user_permissions: (fields.E304) Reverse accessor for 'webapp.Login.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions' models from django.contrib.auth.models import AbstractUser from django.db import models from django.conf import settings # Create your models here. class Login(AbstractUser): is_student=models.BooleanField(default=False) class Student(models.Model): user= models.OneToOneField(Login,on_delete=models.CASCADE,related_name='student') name= models.CharField(max_length=50) def __str__(self): return self.name trying to makemigrations -
Not able to do the migrate in Django, facing Attribute Error: 'str' object has no attribute '_meta'
I made a completely new project using the django-admin startproject and I also made an app using django-admin startapp and I am able to apply the initial migrations but not able to do the migrate. and I didn't add any code into the project. It's completely a new project. python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying auth.0013_user_following...Traceback (most recent call last): File "G:\My Drive\Django 4 by example\myshop\manage.py", line 22, in <module> main() File "G:\My Drive\Django 4 by example\myshop\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 135, in migrate state = self._migrate_all_forwards( File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\migration.py", line 130, in apply operation.database_forwards( File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\operations\fields.py", line 108, in database_forwards schema_editor.add_field( File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\schema.py", line 383, in add_field if field.many_to_many and field.remote_field.through._meta.auto_created: AttributeError: 'str' object has no … -
How does one get a system-wide gunicorn to find django in a virtual environment?
Reading the gunicorn docs, I learn how to run gunicorn as a system-wide app managed via systemd. This is quite convenient, especially for managing multiple django apps via systemd. There is one problem that the documentation omits. It is that the django instances are most likely within virtual python environments. Here is what I get when I implement gunicorn's documentation: gunicorn[14780]: ModuleNotFoundError: No module named 'django' Not cool, not cool at all. I perceive that there is a way to get systemd services to cooperate with virtual environments but I can't seem to locate clear instuctions on that. Most articles out there would have me running gunicorn from the same virt environ with django. Does that mean I have to install a fresh virtual instance of gunicorn for every django project I create? -
Django Form modifies database, could it be an issue if two people submit a form at the same time
I'm very new to Django and I'm writing an app that gives user the best matching product from the database. I have a model with all the products and their specifications, model for user's preferences and Compatibility model where I have all the product ids and when user submits the form, compatibility column updates, then the table is sorted and gives back 5 top choices. My concern is if it could be an issue if two users submit a form at the exact same time? Could that cause User B getting top products for User A form? If yes, what would you recommend me to do or what to section in Django documentation could help me to figure it out? -
Queryset with entries that have related objects
I want to take all entries that have related objects class Author(models.Model): name = models.CharField(...) class Book(models.Model): author = models.ForeignKey(Author) I want to do a queryset that take all the authors that have at least one book. I did the logic in template to show only if _set.all.count != 0 like this views.py Author.objects.all() .html if author.books_set.all.count != 0 But the pagination is showing incorrectly -
How to update a User Profile in Django using Django REST API Framework?
【System Overview】 I have 5 different types of users (Administrators, Staffs, Clients, Students and Teachers) in my system. A client who owns his/her own profile can update his/her own profile information. He/she is not authorized to update other clients' profile information. I am not getting the output as expected as said above. models.py This file includes 2 models (UserAccount and ClientProfile) class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name="Email Address", max_length=255, unique=True) full_name = models.CharField(verbose_name="Full Name", max_length=255) date_joined = models.DateTimeField(verbose_name="Member Since", auto_now_add=True) last_login = models.DateTimeField(verbose_name="Last Logged In", auto_now=True) is_verified = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_client = models.BooleanField(default=False) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_active = models.BooleanField(default=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["full_name", ] objects = UserAccountManager() class Meta: db_table = 'USERS_INFORMATION' verbose_name = "Users Account" verbose_name_plural = "Users Accounts" def __str__(self): return self.full_name def get_name(self): return self.full_name def get_email(self): return self.email class ClientProfile(models.Model): class Meta: db_table = 'CLIENTS_PROFILE_INFORMATION' verbose_name = "Clients Profile Account" verbose_name_plural = "Clients Profile Accounts" client = models.OneToOneField(UserAccount, on_delete=models.CASCADE, related_name="client") country = models.CharField(verbose_name="Country", max_length=100, blank=True, null=True) is_client = models.BooleanField(default=True) def __str__(self): return self.client.full_name def get_email(self): return self.client.email def get_dateJoined(self): return self.client.date_joined def get_lastLoggedIn(self): return self.client.last_login def get_isVerified(self): return bool(self.client.is_verified) get_isVerified.boolean = True def … -
How to limit the number of results in a Django REST serializar?
Hi have this serializer: class ActivitiesSerializer(serializers.ModelSerializer): activity = serializers.CharField(source='task.name') project = serializers.CharField(source='project.name') discipline = serializers.CharField(source='task.discipline.name') class Meta: model = Activities fields = ( 'id', 'activity', 'project', 'discipline', ) How can I limit the number of results to 10? This is my view: class ActivitiesAPIView(generics.ListCreateAPIView): search_fields = ['task__name', 'task__discipline__name', 'project__name'] filter_backends = (filters.SearchFilter,) queryset = Activities.objects.all() serializer_class = ActivitiesSerializer