Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot login to django admin right after implementing DRF token authentication. Setting is_active to True fixed it. Why?
After implementing DRF authtoken app, I deleted my previous superuser (because it did not have an auth token) and created a new one. Looking at the database, I see that the new superuser has an entry in authtoken_token table. It also has is_admin, is_staff, and is_superuser set to True. is_active is set to False but this was also set to False in the previous superuser and loging in to admin was not a problem. When I enter credentials in admin page with is_active=False, it says: "Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive." Before setting is_active=True, some answers from other SO questions I tried: I made sure I'm not setting SESSION_COOKIE_SECURE = True. I'm not using this setting in dev environment anyways. When I check the database, django_session table is there. When I try to authenticate, I do not see a new entry being created. I do create my superuser via python manage.py createsuperuser command, same as I did before. I also tried to change superuser pw via python manage.py changepassword . My db is synced, I checked the tables after deleting and creating a new superuser and they are … -
Django Rest Framework allauth Saving a PrimaryKeyRelatedField to a user during sign up
I have set up a CustomRegisterSerializer using dj-rest-auth and allauth. I can't seem to save the ManytoMany relationships. please can someone advise where I'm going wrong. serializer.py class CustomRegisterSerializer(RegisterSerializer): dbs_number = serializers.CharField(max_length=13, required=True) hospitals = serializers.PrimaryKeyRelatedField(many=True, queryset=HospitalListModel.objects.all()) area_to_work = serializers.PrimaryKeyRelatedField(many=True, queryset=AreaToWorkModel.objects.all()) def get_cleaned_date(self): data_dict = super().get_cleaned_data() data_dict['dbs_number'] = self.validated_data.get('dbs_number', '') data_dict['hospitals'] = self.validated_data.get('hospitals', '') data_dict['area_to_work'] = self.validated_data.get('area_to_work', '') print('serializer :' + str(data_dict)) return data_dict adapter.py class CustomAccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=False): user = super().save_user(request, user, form, commit) data = form.data user.dbs_number = data['dbs_number'] user.save() user.hospitals.add(*data['hospitals']) user.area_to_work.set(*data['area_to_work']) user.save() return user -
django runserver start downlonding file containing this string <function render at 0x0000023B61F4F160>
After running: py manage.py runserver instead of showing me the html views, this string is shown on the page: <function render at 0x0000023B61F4F160> after few minutes this message appears on the terminal: [13/Nov/2020 08:39:05] "GET /socketcluster/ HTTP/1.1" 404 2129 -
Django Form Initial Value not Showing
I want to make a form to edit a model object, with the initial data being the original data (before the change), but it doesn't show, it was just a blank form models.py: class Employee(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) forms.py: class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = ['first_name', 'last_name'] labels = {'first_name' : 'First Name:', 'last_name' : 'Last Name:' } input_attrs = {'class' : 'form-control'} widgets = { 'first_name' : forms.TextInput(attrs=input_attrs), 'last_name' : forms.TextInput(attrs=input_attrs)} views.py: def edit(request, id): employee = Employee.objects.get(id=id) data = { 'first_name' : employee.first_name, 'last_name' : employee.last_name, } form = EmployeeForm(request.POST or None, initial=data, instance=employee) if (form.is_valid and request.method == 'POST'): form.save() return HttpResponseRedirect('/form/') response = {'employee_form' : EmployeeForm, 'employee':employee} return render(request, editemployee.html, response) editemployee.html: <div class="form"> <div class="form-group"> <form action="" method="POST"> {% csrf_token %} {% for form in employee_form %} {{ form.label }} {{ form }} <br> {% endfor %} <input type="submit" value="Submit" class="btn btn-primary"> </form> </div> </div> Can anyone please tell me where I went wrong? I've tried so many things but to no avail. The form works fine, but the initial data doesn't show. -
DFR simple jwt get authToken from a user instance instead of username/password
I have a simple chat app, authentication in it works exaclty as whatsapp Get phone number => if doesn't exist create one else skip => send validation code and set it as "phone_code" field in User model => finally remove the "phone_code" if validated The app is built in React Native with Rest framework as the API, I'm new to this and I'm struggling to get the authentication token without the password. i use djangorestframework-simplejwt my register view: @api_view(('POST',)) def register(request): if request.method == 'POST': serializer = UserSerializer(data=request.data) if not serializer.is_valid(): if 'is not valid' in serializer.errors['phone_number'][0]: return Response(serializer.errors, status.HTTP_400_BAD_REQUEST) phone_number = serializer.initial_data['phone_number'].replace(' ', '') try: user = User.objects.get(phone_number=phone_number) except User.DoesNotExist: user = User.objects.create_user( phone_number=phone_number, username=phone_number) user.phone_code = randint(99999, 999999) user.save() TokenObtainPairView() return Response(serializer.data, status.HTTP_200_OK) # todo send validation code, I will handle later my Login view (Chich validates for the validation code) @api_view(['POST',]) def loginuser(request): if request.method == 'POST': phone_number = request.data.get('phone_number') try: user = User.objects.get(phone_number=phone_number) if int(request.data.get('phone_code')) == user.phone_code and user.phone_code: user.phone_code = None user.save() #!!!!!!!!!!!!!!!!!!!NOW HOW CAN I GET THE JWT AUTHENTICATION TOKEN AND SEND IT TO MY REACT NATIVE APP?! return JsonResponse({'phone_number': phone_number}, status=200) else: return JsonResponse({'error': "Invalid code"}, status=400) except Exception as error: return JsonResponse({'error': … -
how can i change the file in the django database
I have a model like this: class chart(models.Model): name = models.CharField(max_length=10) chart_file = models.FileField(upload_to='charts/1', null=True, blank=True) in chart_file object i have to many excel file. now in views.py i want to get the objects and extract one of the column like this def home(request): charts= chart.chart_file.url read = pd.read_excel(chrts) labels = read['x'].tolist() context = { 's': labels, } return render(request, 'home.html', context) finally for each excel file in my model i want to show the x column like this: {% block content%} {% for i in s %} <p>i</p> {% endfor %} {% endblock %} but it raise this error: 'FileDescriptor' object has no attribute 'url'. how can i render this.please help -
Force client request to include specific data in Django using Gunicorn
Big tech like Google, for instance, can collect the user(client)'s device name when they send a request to any of their services, and that allows them to track all the devices that a user has used to access a particular service, endpoint, application. While building applications with Django; request data or headers can be accessed through the META attribute of the request object. When developing locally, using Django's development server, requests are constructed with a bunch of useful data that could be used to keep track of the device sending requests. Data that interests me here are: request.META.get('LOGONSERVER') request.META.get('USERDOMAIN') Unless I am wrong, these are easily set by the development server and can be collected. In production, these values are nowhere to be found inside request.META. Is there a way to achieve this in production? Is there a condition of trust between server and client supposed to be made before it is possible? -
django-admin startproject command returning bad interpreter: No such file or directory
I can create a project outside of a virtual environment just fine, but when I am using a venv and try to create a django project, I get the following: /Users/justin/Desktop/Programming/Python/Django Projects/env/bin/django-admin: "/Users/justin/ Desktop/Programming/Python/Django: bad interpreter: No such file or directory I created the venv with python3 -m venv env, I then tried to run pip install django where the above error also appeared, I then learned I should be using python3 -m pip install django (pip3: bad interpreter: No such file or directory) and this successfully installed django, but I still cannot start a project. I've ran pip install django and django-admin startproject from a venv many times without an issue so it seems like I broke something recently. Does anyone know how to fix this/where I can begin looking for the issue? Thanks for any help. -
How to add created_by and updated_by fields in any Django model and fill the values automatically using Django middlewares?
This is the Profession model in my Django Project, I have added two fields named created_by and updated_by in this model. Whenever a new object is added to this model or an object is modified of this mode, created_by and updated_by should have relevant 'User' values. class Profession(models.Model): profession_name = models.CharField(max_length=50) is_active = models.BooleanField(default=True) date_added = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name='profession_cb', on_delete=models.PROTECT) updated_by = models.ForeignKey(User, related_name='profession_ub', on_delete=models.PROTECT) def __str__(self): return self.profession_name That's a typical problem and answered by many on Stack Overflow, but I wanted to do it through django middlewares, I found a solution using middlewares but it was for Django older than 2.2. I am using Django 3.1 and 'curry' method is no more on this 3.1 version. I have also tried 'functools.partial' in place of 'curry' but that is also not working. This is my middleware. from django.db.models import signals from functools import partial class WhodidMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. self.process_request(request) response = self.get_response(request) # Code to be executed for each request/response after # the view is … -
Django serializer is not using the model manager
I am trying to work with my own model manager to annotate some properties. This is working fine till the serializers try to use one of this properties. The setup is a little bit complicated but i will try to explain it as best as i can. This is my model (reduced to the important part) class UserManager(DjangoUserManager): def get_queryset(self): return super(DjangoUserManager, self).get_queryset().annotate( is_counselor=Exists(Group.objects.filter(user=OuterRef('pk'), name=User.COUNSELOR_GROUP)) ) class User(AbstractUser): COUNSELOR_GROUP = 'Berater*in' objects = UserManager() Then i have another model which has a foreign key to the user model (simplified): class Message(models.Model): sender = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='sender_message') And in the end i have this serializer: class ConversationMessageSerializer(serializers.ModelSerializer): is_counselor = serializers.BooleanField(source='sender.is_counselor') The error im receiving is this one: AttributeError: Got AttributeError when attempting to get a value for field `is_counselor` on serializer `ConversationMessageSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Message` instance. Original exception text was: 'User' object has no attribute 'is_counselor' I tried to use a methodfieldserializer instead of a boolean serializer but its leading to the same error. I logged the database query from the serializer and the annotations are not in the query. So it seems like the serializer is … -
Fetching From Multiple Formats of the Same URL
Sorry if the title of the question is misleading, I wasn't sure how to ask it. I bought a URL from GoDaddy. Since I did that, I changed the fetch URL in all react components that fetched from my endpoint from local host to www.bluebird-teaching.com. The problem is, if I type exactly that, I get everything I expect. If I type just bluebird-teaching.com or https://www.bluebird-teaching.com, I still load the same website I made, but I don't see any information fetched with the API. Below is an example component where I fetch. Is there a way to fetch from multiple similar URLs depending on what the user types? componentDidMount() { this.setState({isLoading: false}) fetch("http://www.bluebird-teaching.com/focus_log_api/") .then(response => response.json()) .then(data => { this.setState({ focusInfo: data }) }) } I tried a couple of things in playing around with the fetch URL, but nothing seems to work without fixing one URL problem without creating another. Is it possible to fetch from like different http, or www, etc for the same website? -
How to sort a list containing multiple dictionaries based on a specific value which is an alphanumeric value
I have no idea how to proceed with this problem. I have a list containing multiple dictionaries which has some values. I have to sort the based on a value of 'emp_code' in alphanumeric way and emp_code is an alphanumeric value [{'emp_code':'AB100', 'emp_name':'John'}, {'emp_code':'3', 'emp_name':'Prince'}, {'emp_code':'BA250', 'emp_name':'AC500'}] Please help me with this -
Django admin advanced search
I have a model called Document class Document(models.Model): name = models.CharField(max_length=255) description = HTMLField(blank=True, null=True) category = models.ManyToManyField(Category) tags = models.ManyToManyField(Tag) publication_date = models.DateTimeField(blank=True, null=True) What I need is a form on the Document admin page with a text input for name and description, two dropdowns for category and tags and a date from, date to fields for publication date. I tried to overwrite admin/search_form.html and get_query_set() but it did not work. Can anyone guide me how to add a nice form to admin area on top of the change list which replaces the default search box? -
How do I stop my Javascript GET requests from going to the current URL in my Django backend when the cache is on?
I'm building a full-stack website using Django, and I've been making it more app-like by adding AJAX functionality to it in Javascript. This works as expected when the cache is disabled, but when it's enabled my primary onclick GET requests go to the current location, instead of the path stipulated in my code. (There is another GET request triggered on click that checks the task manager, and that works fine whether or not the cache is on.) I've used both XMLHttpRequest and jQuery.GET to make requests, but Django consistently sends them to the wrong location. This is the code. const updateButtons = $('.update-button') updateButtons.on('click', event => { let button = $(event.currentTarget); updatingStatus = true; button.text(toggleUpdateText(button.text())); expandText(button); $.get(button.attr('href'), response => { next = true; updatingCalendar(button); console.log(button.attr('href')); }); }); As you can see, I log the button's HREF attribute (the correct GET path) to the browser's console, and it is exactly the intended URL for the request. When I review the backend console, though, the only GET request is going to the current page (it might go to the right page at most once, but then the cache does something that forces it to go only to the current URL). This is … -
Django: How to sort on manytomany field in Admin Site?
I have below django admin site. The fields Industries and Nationalities are manytomany fields in Person model. Based on Person model below admin page is designed. The name, profession and date of birth fields can be sort by default. However Industries and Nationalities can't be sorted. Is there any way that we can enable sorting on manytomany fields as well? -
Setting up file download form S3 on .ebextensions breaks S3Boto3Storage connection to S3
According to Amazon doc I setup file download from S3 on deployment using elasticbeanstalk on my Django project. Blow is sample code from amazon doc and my code is almost identical to this(only changed buket name, file path and original file path on S3) https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/https-storingprivatekeys.html # Example .ebextensions/privatekey.config Resources: AWSEBAutoScalingGroup: Metadata: AWS::CloudFormation::Authentication: S3Auth: type: "s3" buckets: ["elasticbeanstalk-us-west-2-123456789012"] roleName: "Fn::GetOptionSetting": Namespace: "aws:autoscaling:launchconfiguration" OptionName: "IamInstanceProfile" DefaultValue: "aws-elasticbeanstalk-ec2-role" files: # Private key "/etc/pki/tls/certs/server.key": mode: "000400" owner: root group: root authentication: "S3Auth" source: https://elasticbeanstalk-us-west-2-123456789012.s3.us-west-2.amazonaws.com/server.key I also use S3Boto3Storage(https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html) to manage media files on Django. After I deployed my app using code above to download file from S3 on deployment S3 via S3Boto3Storage broke. How can I setup file download form S3 on deployment and also make S3Boto3Storage work? -
Django not decoding urls properly
The django server is not decoding the get url and sending a 404 error. The django message was as follow: "GET /static/website/css/colors5533.css%3Fcolor%3D0A8F89 HTTP/1.1" 404 1751 The website source code for the url in the browser was shown as follows: href="/static/website/css/colors5533.css%3Fcolor%3D0A8F89" The code in the template of the django project was as follows: <link rel="stylesheet" href={% static 'website/css/colors5533.css?color=0A8F89' %} type="text/css" /> and also coded the link sa follows but that doesn't seem to work <link rel="stylesheet" href="{% static 'website/css/colors5533.css' %}?color=0A8F89" type="text/css" /> Any solutions to the problem? -
How to implement an admin approval system for Registration in pythondjango
I am building a website where user can register and login. But before complete registration, it should be approved by the admin. I do not know how to do it. I made a user authentication system where user can login. But i do not know how is approved with admin approval. -
Django custom model fields with mixin doesn't work as expected
custom_fields.py from django.db import models class NotRequiredMixin: def __init__(self, *args, **kwargs): defaults = {'null': True, 'blank': True} defaults.update(kwargs) super().__init__(*args, **defaults) class CustomDateField(NotRequiredMixin, models.DateField): pass models.py from django.db import models from custom_fields import CustomDateField class FooModel(models.Model): sample_date = CustomDateField('sample date', null=False) in this case, I expected 'sample_date' field is non-nullable, but 'sample_date' field is set to nullable. 'null=False' in models.py>FooModel>sample_date doesn't work. I added test code at custom_fields.py ...python class NotRequiredMixin: def __init__(self, *args, **kwargs): defaults = {'null': True, 'blank': True} defaults.update(kwargs) print(defaults) # test code super().__init__(*args, **defaults) ... > {'null': False, 'blank': True} it prints as expected. it seems kwargs update works fine, but actual field is created as nullable(null=True). what am I missing? -
Reverse for 'django_summernote-upload_attachment' not found
I am having these type of error while clicking "add post" button in django-admin section. here's the error log info : In template C:\Users\niraj\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 19 Reverse for 'django_summernote-upload_attachment' not found. 'django_summernote-upload_attachment' is not a valid view function or pattern name. 9 {% for field in line %} 10 <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 {% if field.is_checkbox %} 13 {{ field.field }}{{ field.label_tag }} 14 {% else %} 15 {{ field.label_tag }} 16 {% if field.is_readonly %} 17 <div class="readonly">{{ field.contents }}</div> 18 {% else %} 19 {{ field.field }} 20 {% endif %} 21 {% endif %} 22 {% if field.field.help_text %} 23 <div class="help">{{ field.field.help_text|safe }}</div> 24 {% endif %} 25 </div> 26 {% endfor %} 27 </div> 28 {% endfor %} 29 </fieldset> here's the admin.py file given below: from .models import Post from django_summernote.admin import SummernoteModelAdmin class PostAdmin(SummernoteModelAdmin): summernote_fields = ('content',) admin.site.register(Post,PostAdmin) here is the urls.py file from django.contrib import … -
Passing an Aggregate Sum to an Html page by Class Based Views on Django
Currently using aggregation for the first time, attempting to get a sum of all 'transactions' and display them on my HTML page. I am using generic class based views, currently in my function it is displaying transactions that are created by the user. I am able to display the cBalance if I return it from a function, although my 'display only the user created transactions' function should take priority. I am trying to get my cBalance to be displayed in HTML Here is my function in views.py class TranListView (ListView): model = transactions def get_queryset(self): #gets only if user matches return self.model.objects.filter(user_id=self.request.user) #def get_context_data(self): # cBalance = transactions.objects.all().aggregate(cBalance=Sum('amount')) # return cBalance List Template: <ul> <a href="{% url 'landing' %}"> Homepage</a><br><br> <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'taction-create' %}">Create New</a> <h5> Transactions: </h5> <li> {{ cBalance }}</li> {% for object in object_list %} <li>{{ object.tname }}</li> <li>{{ object.amount }}</li> <li>{{ object.date }}</li> <li>{{ object.recipient }}</li> <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'taction-update' object.id %}">Update</a> <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'taction-delete' object.id %}">Delete</a> <hr/> {% empty %} <li>No objects yet.</li> {% endfor %} </ul> If anyone can help me out it'd be greatly appreciated -
Flutter Web XMLHttpRequest error. Using django as backend with CORS enabled
Im trying to make HTTP POST request from my flutter web app to Django backend, but im always getting this error: Error: XMLHttpRequest error. C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 894:28 get current packages/http/src/browser_client.dart 84:22 <fn> C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1450:54 runUnary C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 143:18 handleValue C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 696:44 handleValueCallback C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 725:32 _propagateToListeners C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 519:7 [_complete] C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream_pipe.dart 61:11 _cancelAndValue C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream.dart 1302:7 <fn> C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 324:14 _checkAndCall C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 329:39 dcall C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37312:58 <fn> at Object.createErrorWithStack (http://localhost:53905/dart_sdk.js:4353:12) at Object._rethrow (http://localhost:53905/dart_sdk.js:37968:16) at async._AsyncCallbackEntry.new.callback (http://localhost:53905/dart_sdk.js:37962:13) at Object._microtaskLoop (http://localhost:53905/dart_sdk.js:37794:13) at _startMicrotaskLoop (http://localhost:53905/dart_sdk.js:37800:13) at http://localhost:53905/dart_sdk.js:33309:9 I have CORS headers enabled in my settings.py CORS_ORIGIN_ALLOW_ALL = True OR CORS_ORIGIN_WHITELIST = ( "http://192.168.0.106", "http://localhost:51297", ) This is my post request: var data = new Map<String, dynamic>(); data['phone_number'] = phoneNumber; data['signature'] = signature; data['device_token'] = deviceToken; print("device: " + deviceToken); http.Response response = await http.post( 'http://192.168.0.106/checkuser', headers: { "Access-Control-Allow-Origin": "*", // Required for CORS support to work "Access-Control-Allow-Credentials": "true", // Required for cookies, authorization headers with HTTPS "Access-Control-Allow-Headers": "Origin,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token", "Access-Control-Allow-Methods": "POST, OPTIONS, GET, PATCH, PUT" }, body: jsonEncode(data), ); I am still not able to make any POST requests. Flutter posts 'OPTIONS' first, any idea how i can change it? -
Nginx records access log with HTTP/1.1 instead of HTTPS
We have enabled SSL in our django+ Nginx application. All works fine. But when I check the Nginx access log I see all the requests that are accessed with HTTPS are recorded with HTTP/1.1 instead of HTTPS. Any specific reason why it is happening? We have blocked port 80 so requests with HTTP are not allowed We have installed the certificate and configured Nginx with listener port 443 already. enter image description here -
How to Censor words in a Django Blog Comments?
I have applied a comment system to my blogs, and I wanted to apply a simple code to censor the bad words in the content. I have a badwords.txt with all the bad words to be used as a dictionary to Censor the word. My problem is I don’t know where I should apply this code? Here is the bad words code import fileinput filename = input("Enter a file name: ") censor = input("Enter the curse word that you want censored: ") for line in fileinput.input(filename, inplace=True): line = line.replace(censor, 'CENSORED') print(line, end='') Here is the Django project I am working on Here is the models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=300) Here is the views.py class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post).order_by('-id') if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') comment_qs = None comment = Comment.objects.create( post=post, user=self.request.user, content=content) comment.save() return HttpResponseRedirect("blog/post_detail.html") else: comment_form = CommentForm() context["comments"] = comments context["comment_form"] = comment_form return context def get(self, request, *args, **kwargs): res = super().get(request, *args, **kwargs) self.object.incrementViewCount() return res … -
how can I paginate the an array based on the total items for restful?
I want to paginate the total data rows to give me x number of pages with max of 100 elements per page similar to djangopaginator(obj_list, items_per_page, oprehans) however I am using flask for this project where I am not sure how to do it the way I want to . my data output looks like this, but I want to target https://github.com/cve-search/cve-search/blob/19b01af8a4cfbc601db196aee2812ec407b5bc2b/lib/DatabaseLayer.py#L360 in order to paginate over 120k records class API(Resource): def get(self): demo = getCVEs(limit=1) json_1 = {'msg': 'sss'} a = {"cars": 1, "houses": 2} b = convertDatetime(demo) a.update(b) print(len(demo)) return a array json output { "results": [ { "id": "CVE-2020-26219", "Modified": "2020-11-11T22:15:00", "Published": "2020-11-11T22:15:00", "access": {}, "assigner": "cve@mitre.org", "cvss": null, "cwe": "CWE-601", "impact": {}, "last-modified": "2020-11-11T22:15:00", "references": [ "https://github.com/puncsky/touchbase.ai/security/advisories/GHSA-6wcq-7r33-gw8x" ], "summary": "touchbase.ai before version 2.0 is vulnerable to Open Redirect. Impacts can be many, and vary from theft of information and credentials, to the redirection to malicious websites containing attacker-controlled content, which in some cases even cause XSS attacks. So even though an open redirection might sound harmless at first, the impacts of it can be severe should it be exploitable.\nThe issue is fixed in version 2.0.", "vulnerable_configuration": [], "vulnerable_configuration_cpe_2_2": [], "vulnerable_product": [] } ], "total": …