Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How could I submit multiple forms?
How could I submit multiple forms (with the same names) created with for loop? Currently my submit button does nothing at all. Here's my code. {% for key, value in questions.items %} <form action="." method="post"> <div class="question"> {{value.0.question}} {% csrf_token %} {% for answer in value %} <div class="answer"> <input type="radio" name="answer-checkbox" value="{{ answer.id }}"> {{ answer }} </div> {% endfor %} </div> </form> {% endfor %} <input type="submit" value="Save"> -
Blocking unwanted users from access another users profile data with function based view in Django
I am working with some function-based views in Django. I have a custom build decorator named industry_required which allows passing by verifying a user is authenticated from an Industrial account or not. I have some functions in views.py and their particular URL in urls.py. like: in urls.py: path('industryDetails/', views.industryDetails.as_view(), name='industryDetails'), path('industry_create_report/<int:pk>/', views.industry_create_report, name='industry_create_report'), in views.py: @method_decorator(industry_required, name='dispatch') class industryDetails(DetailView): model = Industry template_name = 'app/industryDetails.html' def get_queryset(self): return Industry.objects.filter(user=self.request.user) def get_object(self): return get_object_or_404(Industry, user=self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['inserted_text'] = "inserted text from EmployeeDetails of views.py" context['employee_table'] = self.object.employee_set.all() return context def industry_create_report(request): industry_create_report_dict = { } #bla bla.... return render(request, 'app/industry_create_report.html', industry_create_report_dict) Now my problem is when I use the DetailView, I can easily ensure that which user logged in that user can see only his DetailView profile by using the method_decorator named industry_required and get_queryset and get_object method. But when I use the function-based view, suppose an Industrial account user with pk=1 can also see the data of pk=2 with using URL pattern (industry_create_report/2/), which is not desireable. How can I fix it? -
Bootstrap - how can I push the below element down once the above has grown?
I'm struggling with one thing. I'm iterating objects which create some sort of row table (the new one is always below the previous one). I tried to add footer but the issue arises when I'm displaying more than 18 elements per page, it overlaps it: Example: My html: <body> <div id="main" class="d-flex flex-column h-100"> <div class="container h-100"> {% include 'navbar.html' %} {% block content %}{%endblock%} </div> {% include 'footer.html' %} </div> <script src="{% static 'js/vue2.js' %}" type="text/javascript"></script> </body> How can I make this table to push the footer all the way down depends on its size ? -
Could not parse the remainder: ' _json' from 'room_name _json'
I am trying to learn Django Channels. BUT i am stucked on a problem. Problem is given Below :- room.html <script src="{% static 'main.js' %}"></script> <script src="{% static 'reconnecting-websocket.js' %}"></script> <script> var roomName = {{ room_name _json }}; var username = {{ username }}; var chatSocket = new ReconnectingWebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/'); consumers.py @login_required def room(request, room_name): return render(request, 'chat/room.html', { 'room_name_json': mark_safe(json.dumps(room_name)), 'username': mark_safe(json.dumps(request.user.username)), }) The Problem 1). When i am trying to open the page in browser, It is showing me Could not parse the remainder: ' _json' from 'room_name _json' error. Some extra information When i notice in IDE , i noticed that , when an error occur in line, then text editor show it like This. It is showing me the red underlines below words. I will really appreciate your Help. tHANK yOU iN aDVANCE -
How to use Django like a PHP
I need some information about Django. Basically i'm PHP developer. nowadays moving to python with micro services. But i need to know how to handle user authorization in Django. For example, The site have two different users logins. One is front users and another one is site administrators users. The front users have multiple users level and also administrator panel also different levels is there. The front user means like one client, the client have multiple users like employees based on the level the page will available. Coming to admin panel also the site owner also have multiple employees, and the employees also have different roles. Coming to me what was we used in earlier for database table structures is, like Front Users Table: users roles Site Admin Panel Table: admin_users admin_roles In Django have inbuilt administrator panel and also have different level authorization. I'm confused how to handle this. I want to create a users and roles table and want handle sessions in differently or i want use existing Django inbuilt admin users tables??? Please clarify this, it will help me lot and moving further things. Kindle share the links or tutorials related to this. -
Django different filters based on category
I couldn't find a question like mine. Basically, I want to create a complex filtering system. The user goes into different categories, and he will see different filters for the model based on the category he is at. It all needs to be on one HTML page. Any ideas? (Sorry if it's a bit hard to understand I just don't really know how to.) -
python crash course making django posts accessible to unregistered users
Im currently trying to do this exercise of python crash course and am unsure with how to proceed with it. Here is the exercise in question. Then try adding a more advanced feature, such as giving users the option of making a topic public. This would require an attribute called public as part of the Topic model (this should be set to False by default) and a form element on the new_topic page that allows the user to change a topic from private to public. Here are the changes that I have already made so far in forms.py, My understanding is that when the user types in the 'public' text bos either 'True' or 'False', the public attribute of the Topic model will be updated accordingly? from django import forms from .models import Topic, Entry class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['text', 'public'] labels = {'text': '', 'public' : "True/False"} class EntryForm(forms.ModelForm): class Meta: model = Entry fields = ['text'] labels = {'text': 'Entry:'} widgets = {'text': forms.Textarea(attrs={'cols': 80})} the Topic model in models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Topic(models.Model): """A topic the user is learning about.""" text … -
Django: Raw SQL Query with parameterized parameters
I'm trying to test the vulnerabilities of SQL injection using the Manager's raw() function in Django. I'm using SQLite as the backend database. I have tried the following two functions for showing the values of the Person Model that I have created. urls.py urlpatterns = [ path('unsafe/<str:user_name>', views.unsafe_get_users, name='unsafe_get_users'), path('safe/<str:user_name>', views.safe_get_users, name='safe_get_users'), ] models.py class Person(models.Model): name = models.CharField(max_length=30) age = models.IntegerField() def __str__(self): return self.name + " " + str(self.age) views.py from django.shortcuts import render from django.http import HttpResponse from .models import Person def unsafe_get_users(request, *args, **kwargs): # sqli using raw user_name = kwargs['user_name'] users = Person.objects.raw('SELECT * FROM member_list_person WHERE name = %s' % user_name) return HttpResponse(users) def safe_get_users(request, *args, **kwargs): # uses parameterized query user_name = kwargs['user_name'] users = Person.objects.raw('SELECT * FROM member_list_person WHERE name = %s', [user_name]) return HttpResponse(users) The Person Model has two fields, namely name and age. As for the unsafe_get_users function, the column data are displayed successfully but for the safe_get_users function, nothing shows up on the server page. I have tried printing len(users), which shows the number of data in the returned RawQuerySet, but for the second one it returns 0 (empty query). Why does unsafe_get_users function return the data as expected … -
django-rest-framework access field inside serializer
So I have a model like this class DataSheet(BaseModel): """ Represents a single dataSheet. dataSheets have their own model at the core. Model data is added to the dataSheets in the form of separate records. """ class Meta: verbose_name = 'datasheet' verbose_name_plural = 'datasheets' ordering = ['position', 'cluster'] required_db_features = { 'supports_deferrable_unique_constraints', } constraints = [ models.UniqueConstraint( fields=['position', 'cluster'], name='deferrable_unique_datasheet_position', deferrable=models.Deferrable.DEFERRED ) ] def __str__(self): return self.name objects = managers.DataSheetsManager() positions = managers.PositionalManager() position = models.PositiveSmallIntegerField(db_index=True, editable=True) name = models.CharField(max_length=100, validators=[MinLengthValidator(2)], db_index=True) description = models.CharField(max_length=1024, null=True, blank=True, db_index=True) owner = models.ForeignKey('api_backend.Member', on_delete=models.CASCADE, db_index=True, editable=False) fields = models.ManyToManyField('api_backend.Field') overwrites = models.ManyToManyField('api_backend.RoleOverwrite') parent = models.ForeignKey('api_backend.Category', on_delete=models.CASCADE, null=True, blank=True) cluster = models.ForeignKey('api_backend.Cluster', on_delete=models.CASCADE, editable=False) REQUIRED_FIELDS = [name, owner, cluster] and a serializer like this class DataSheetSerializer(serializers.ModelSerializer): """ A serialized DataSheet Object. Datasheets have their own: - array of fields - array of role-overwrites """ def get_fields(self): fields = super(DataSheetSerializer, self).get_fields() fields['parent'].queryset = self.cluster.categories.all() return fields class Meta: model = DataSheet read_only_fields = ['position'] fields = '__all__' # need to make sure that the parent category of the datasheet # belongs to the datasheet's cluster only. fields = partial.PartialFieldSerializer(many=True, read_only=True) overwrites = partial.PartialOverWriteSerializer(many=True, read_only=True) the thing is, I want to access the serializer model's … -
Send a websocket message when exceptions is raised in django channels
I'm using django-channels. When an exception is raised within a consumer it will log the error, the websocket connection will be disconnected and then it will re-connect again. I would like to send a websocket message before it disconnects. I've tried to catch the error, send the message and then re-raise the exception. But the message still isn't sent. What's the best way of achieving this? -
Import current module from an imported module in python Django (importing loops)
Take the following pseudo-code for example models.py from django.db import models from django.core.exceptions import ValidationError from .methods import list_eligible_badges class User(models.Model): handle = models.SlugField(max_length=200) class Permission(models.Model): user = models.ForeignKey(User) badge = models.SlugField(max_length=200) def clean(self): super(Permission, self).clean() allowed_badges = list_eligible_badges() try: allowed_badges.index(self.badge) except: raise ValidationError('This user is not eligible for this privilege') methods.py from .models import User def list_eligible_badges(user_handle): user_in_context = User.objects.get(handle=user_handle) # do some validation on the user_in_context to figure out what # badge is this user eligible for then return a list of badges # allowed for this user The above code defines two related data models, User and Permission where each permission is associated with a user. and in the file methods.py we have a method, list_eligible_badges where this method takes the user_handle (unique slug identifier of a user) and returns a list of slugs for the permissions that this particular user is eligible for. And then the list_eligible_badges method is being used in the clean function of the Permission model to validate each permission before it's added to the database. Everything seems fine, except that when running the code, it shows the error: File "methods.py", line 1, in from .models import User ImportError: cannot import name 'User' … -
signup with OTP in django
i want to create a signup system for my users with django like below, 1- user enter phone_number 2- server store phone_number as a new user 3- server store a key-value pair in redis like this: phone_number : generated_token with five minute life time 4- server send a sms to user containing generated_token i have two question here: 1 - how should i create a new token? hotp or totp or urandom ? 2 - in case of a secure and safe generated_token, is this approach good ? i have little information about those 3 algorithm, but i need more thank you -
Django Form save successfully through url into database but not through bootstrap Modal Form
I'm trying to post data through bootstrap modal form. From all checks the data is post successfully but it doesn't save in database. Meanwhile data is save into database if form is accessed directly through add URL. Form save into database if accessed directly Form doesn't save into database when accessed through Modal form.html {% load widget_tweaks %} <form method="post" action="."> {% csrf_token %} <div class="modal-header"> <h4 class="modal-title">Add Bank</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <input type="hidden" name="action" value="{{ action }}"> {% if form.errors %} <div class="alert alert-danger alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> <h5><i class="icon fas fa-ban"></i> An error occurred while trying to save the record!</h5> <ul> {% for field in form %} {% for error in field.errors %} <li>{{ error }}</li> {% endfor %} {% endfor %} </ul> </div> {% endif %} <div class="form-row"> {% for field in form %} <div class="form-group col-md-6"> <label for="{{ field.id_for_label }}">{{ field.label }}:</label> {% render_field field class="form-control" placeholder=field.label %} <div class="{% if field.errors %} invalid{% endif %}"> {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> </div> {% endfor %} </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success">Save <i class="fas fa-save"></i></button> <button … -
How can we create a page that allows user to create virtual machine in django
Basically I have a project with following milestones: Take user apis from user interface and save in db. Allow user to update api keys or add more keys. Then create page where user can create vm. ( basically you dont have to create vm, just call rest api to create one). List and manage those vms (you can either locally create table to store vm details or fetch from apis) in django.Please help! -
Unable to Save to Django Model
I am saving a Django model and everything works except for one column in the model and I can't seem to figure out what the issue is. I imagine just a fresh pair of eyes will see the likely basic error I am making. Here is an abbreviated snippet of my code: My model: class Commission(models.Model): checkout_id = models.CharField(max_length=20,null=True, blank=True) My function: def custom_order(custom_order_manager_data): from apps.commission.models.commission import Commission custom_order_id = custom_order_manager_data['customOrderId'] custom_order_data = Commission.objects.get(id=custom_order_id) custom_order_data.checkout_id = checkout.id #checkout works ignore this print("CHECKOUT ID: ",checkout.id) print("CUSTOM ORDER CHECKOUT Public ID: ",custom_order_data.checkout_id) custom_order_data.save() print("Post Save ",custom_order_data.checkout_id) When I check my logs, everything works and is printing the correct data, but it still isn't saving. Here are the logs: CHECKOUT ID: 3380 CUSTOM ORDER CHECKOUT Public ID: 3380 Post Save 3380 For me this shows that the instance is gathering the correct data and it is saved correct to that instance, but it won't save in the db (all other data does though, it's just specifically when I'm trying to save to checkout_id that isn't working. I am getting no errors. Here is what I've tried: I've changed the model name. I've changed the column name to something more unique. I've increased the … -
Django Pagination in nested field with Generics
i have following class class PersonSerializer(serializers.ModelSerializer): comments = CommentSerializer(source='comment_set', many=True) images = ImageSerializer(source='image_set', many=True) class Meta: model = Person exclude = ('paid', 'status', 'register_date', 'paid_date') which returns me info about user with nested comment field { "id": "718b309c-864d-4c26-a80e-2e744ac3102a", "comments": [ { "id": "6fc515bb-295a-4191-8255-da7f8fe7976e", "comment": "Test comment", "name": "Test", "age": 25, "comment_date": "2021-01-10T10:07:45.549207Z", "person": "718b309c-864d-4c26-a80e-2e744ac3102a" } ], "images": [], "name": "Test"} Class that handles query looks like class PersonListView(generics.ListAPIView): serializer_class = PersonSerializer permission_class = permissions.IsAuthenticatedOrReadOnly pagination_class = PageNumberPagination filter_backends = (DjangoFilterBackend,) filterset_fields = { 'city': ['exact'], 'age': ['gte', 'lte', 'exact', 'gt', 'lt'], } def get_queryset(self): queryset = Person.objects.filter(status=2, paid=False) return queryset I use PageNumberPagination as i default paginator. But nested field is not paginated. Is there any general way to do it with Generics ? -
Password is not being hashed when using Django Abstract User
I'm building a web application am using AbstractUser to create custom users. here are my models. from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): login_count = models.PositiveIntegerField(default=0) class Supplier(User): company_name= models.CharField(max_length=30) company_domain=models.CharField(max_length=30) class Meta: verbose_name = 'supplier' verbose_name_plural = 'suppliers' class Worker(User): ACCOUNT_TYPE = ( ('1', 'Admin'), ('2', 'Regular'), ) account_type = models.CharField(max_length=1, choices=ACCOUNT_TYPE) class Meta: verbose_name = 'worker' verbose_name_plural = 'workers' admin.py from django.contrib.auth.admin import admin from .models import Worker , Supplier , User admin.site.register(Supplier) admin.site.register(Worker) Everything works fine until ti comes to saving users and there passwords. The passwords are not encryted both in the admin and my django rest urls . Is there a gerenal way to fix it in the User model directly without overiding the Serialisers create method so it works corectly for everything? If no how can I fixed the admin side too. -
how to view specific fields from db of two tables into html table in django?
how to combine specific fields in two tables in dbsqlite into html table in python django.how to call values into table <tbody id="tableSearch"> {% for instance in experiment_detail %} {% for instance in project_detail %} <tr> <!-- <td>{{ instance.id }}</td> --> <td>{{ instance.Experiments_name }}</td> <td>{{ instance.Experiments_remarks }}</td> <td>{{ instance.ProjectName }}</td> <td> class Experiments(models.Model): Experiments_name = models.CharField(max_length=100) Experiments_status = models.CharField(max_length=100) Experiments_project_id = models.ForeignKey('Project', on_delete=models.CASCADE) Experiments_testRatio = models.FloatField(default=0.0) Experiments_remarks = models.CharField(max_length=100,default='') class Project(models.Model): ProjectName = models.CharField(max_length=100) -
Django channels update playerlist on disconnect
I'm making a chat room with django-channels(websocket functionality). I have Room and Artist models and, I have two forms HostRoom and JoinRoom. I have a player list on the left of the screen. I'm able to update the player list in a room when a new user enters by broadcasting new playerlist to room. (running broadcast_msg_to_chat by catching m2m changed) However, I couldn't find a way to update the room player list when one of the artist leaves the room, I also need to delete disconnected artist instance from the room instance. I tried to update in onDisconnect using self.nickname inside consumer, but it deleted the the nickname of the last person who entered the room. How can I handle that? #forms.py class HostRoomForm(forms.ModelForm): class Meta: model = Artist fields = ['nickname', ] labels = { 'nickname': _('nickname'), } class JoinRoomForm(forms.ModelForm): temp_room_code = forms.CharField(max_length=6, min_length=6) class Meta: model = Artist fields = ['nickname', 'temp_room_code', ] labels = { 'nickname': _('nickname'), } #models.py class Room(models.Model): name = models.CharField(max_length=6) # make unique artists = models.ManyToManyField('Artist') active = models.BooleanField(default=False) class Artist(models.Model): nickname = models.CharField(max_length=30, default='') def __str__(self): return f'{self.nickname}' def artists_changed(instance, *args, **kwargs): artists_count = instance.artists.count() # broadcast playerlist to room if artists_count … -
Mac OS Big Sur update causing pip install requirements for django 1.11 with cffi error
Mac OS Big Sur update causing pip install requirements for django 1.11 with cffi error. How can I resolve this ? Running setup.py install for cffi ... error ERROR: Command errored out with exit status 1: command: /Users/axil/Documents/project/projectdotcom/projectdotcomenv_v2/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/gp/2f22kt6s75d8tf653xq_5rfh0000gn/T/pip-install-nsm19ufc/cffi_73cb07cbfd52456caf370009aa7e0938/setup.py'"'"'; __file__='"'"'/private/var/folders/gp/2f22kt6s75d8tf653xq_5rfh0000gn/T/pip-install-nsm19ufc/cffi_73cb07cbfd52456caf370009aa7e0938/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/gp/2f22kt6s75d8tf653xq_5rfh0000gn/T/pip-record-y3_9oop2/install-record.txt --single-version-externally-managed --compile --install-headers /Users/axil/Documents/project/projectdotcom/projectdotcomenv_v2/include/site/python3.8/cffi cwd: /private/var/folders/gp/2f22kt6s75d8tf653xq_5rfh0000gn/T/pip-install-nsm19ufc/cffi_73cb07cbfd52456caf370009aa7e0938/ Complete output (65 lines): running install running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.8 creating build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/backend_ctypes.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/error.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/setuptools_ext.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/__init__.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/cffi_opcode.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/vengine_gen.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/model.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/ffiplatform.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/api.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/vengine_cpy.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/commontypes.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/lock.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/recompiler.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/cparser.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/verifier.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/_cffi_include.h -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/parse_c_type.h -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/_embedding.h -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/_cffi_errors.h -> build/lib.macosx-10.9-x86_64-3.8/cffi running build_ext building '_cffi_backend' extension creating build/temp.macosx-10.9-x86_64-3.8 creating build/temp.macosx-10.9-x86_64-3.8/c gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DUSE__THREAD -DHAVE_SYNC_SYNCHRONIZE -I/usr/local/Cellar/libffi/3.3/include -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/ffi -I/Users/axil/Documents/project/projectdotcom/projectdotcomenv_v2/include -I/Library/Frameworks/Python.framework/Versions/3.8/include/python3.8 -c c/_cffi_backend.c -o build/temp.macosx-10.9-x86_64-3.8/c/_cffi_backend.o c/_cffi_backend.c:4197:31: warning: assigning to 'char *' from 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers] … -
no such column: ecomapp_firstsliderdata.category_id why the category data is not deleting and showing this error in django
when i try to open column in no such column category_id why this is showing and also i'm not able to delete category list from DB my models.py class FirstSliderData(models.Model): image = models.ImageField() title = models.TextField(max_length=500) desc = models.TextField(max_length = 5000 ,null=True,blank=True) category = models.ForeignKey(Category , on_delete=models.CASCADE , default=1) brandName = models.TextField(max_length = 100,default='',null=True,blank=True) class TopList(models.Model): image = models.ImageField(upload_to='ProductImg') title = models.TextField(max_length=500) discountpercentage = models.IntegerField(blank=True,null=True) discountPrice = models.IntegerField(blank=True,null=True) brandName = models.TextField(max_length = 100 , default='',null=True,blank=True) desc = models.TextField(max_length=5000 ,null=True,blank=True) finalprice = models.IntegerField(blank=True,null=True) category = models.ForeignKey(Category , on_delete=models.CASCADE , default=1) @staticmethod def get_products_by_id(ids): return Product.objects.filter(id__in =ids) @staticmethod def get_all_products(): return Product.objects.all() @staticmethod def get_all_products_by_categoryid(category_id): if category_id: return Product.objects.filter(category = category_id) else: return Product.get_all_products() class Category(models.Model): name = models.CharField(max_length=20) @staticmethod def get_all_categories(): return Category.objects.all() def __str__(self): return self.name my admin.py file also the category list is not deleting from db it shows same error again when i try to delete like listed product i'm getting same errors from .models import FirstSliderData , TopList ,Category @admin.register(FirstSliderData) class FirstsliderModelAdmin(admin.ModelAdmin): list_display=['id','image','title' ,'category'] @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ['name'] -
Django RetrieveAPIView class with pagination
I have following class class CommentRetrieveView(generics.RetrieveAPIView): queryset = Comment.objects.all() serializer_class = CommentSerializer pagination_class = PageNumberPagination permission_classes = (permissions.IsAuthenticatedOrReadOnly,) As a pagination class i set PageNumberPagination, but when i try to http://127.0.0.1:8000/api/comments/6fc515bb-295a-4191-8255-da7f8fe7976e my result is without pagination { "id": "6fc515bb-295a-4191-8255-da7f8fe7976e", "comment": "test comment", "name": "Test", "age": 25, "comment_date": "2021-01-10T10:07:45.549207Z", "person": "718b309c-864d-4c26-a80e-2e744ac3102a"} The default pagination class in settings is 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination' How to correctly use pagination in RetrieveAPIView? -
How could I create many radio inputs with for loop?
Here's my code: {% for answer in value %} <div class="answer"> <input type="radio" name="answer-checkbox" value="{{ answer.id }}"> {{ answer }} </div> {% endfor %} I want to create multiple sets of questions and answers, within each set only one answer could be selected at a time, how could I do this? -
How to not submit a form unless search is one of the options (django + HTML) [duplicate]
So I have the following code: <input autocomplete="off" type="search" list="liss" name="q" id="id_q" placeholder="Search"> <datalist id="liss"> <option value="one">Value 1</option> <option value="two">Value 2</option> <option value="three">Value 3</option> <option value="four">Value 4</option> <option value="five">Value 5</option> <option value="six">Value 6</option> </datalist> And it all works fine. The only thing I want it to do is to not let the user submit the form unless the input value is one of the options. How can I do that? -
A way to filter models for ModelChoiceField in Wagtail
Let's say I have a ForeignKey field in my model. class MyModel(StatusModel): site = models.ForeignKey('wagtailcore.Site', related_name='test_field', on_delete=models.CASCADE) panels = [ FieldPanel('site') ] Looks like Wagtail creates ModelForms by itself, but I need to filter models that make it to the dropdown list on my editing page. How can I do it?