Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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": … -
How to display one question per page in Django
Suppose I have 10 rows in the table Question and I can call questions= Question.objects.all() It displays all the questions on the page like this but I am trying to display one after one on the page. how can I display it? Any help is appreciated -
Django form - How to save data or get data without having to save it to database?
I've created a form with some fields for users to enter data, and a button to submit them and run some functions, then display the results on the same page (without having to store it to the database). Now I would like to add a button (view/download as PDF) to have the page generated as a PDF file, so that the user can save the results. But I'm having trouble retrieving the entered data, even they are still displaying on the page. They don't seem to be stored in the variables (or I don't know where to look). I've read that if using modelForm I can call the .save function and save data to the database. But for this app I don't really need a database (it's more like an one-off calculations). So I would like to know if there's any way to: Get the entered data directly while they are still on display (after submitting the form). Generate a PDF directly from what's on the page (like the print to PDF file function that most browsers have, but with some customization such as without the headings and navigation bars). Is there a way to do this? I've been searching … -
ImportError: cannot import name 'ConfigSerializer' from partially initialized module 'api.serializers'
I have been trying to understand which part of the app has a circular import but I just can't get the logical flow in this. If I may show you the directory tree of this app called, "api": When I run a unit test, I get this error: E ====================================================================== ERROR: api.serializers (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: api.serializers Traceback (most recent call last): File "/usr/local/Cellar/python@3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "/usr/local/Cellar/python@3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name __import__(name) File "/Users/nick/work/shiftwork_backend/api/serializers/__init__.py", line 1, in <module> from .default import * File "/Users/nick/work/shiftwork_backend/api/serializers/default.py", line 10, in <module> from api import views File "/Users/nick/work/shiftwork_backend/api/views/__init__.py", line 1, in <module> from .base import * File "/Users/nick/work/shiftwork_backend/api/views/base.py", line 10, in <module> from api.serializers import ConfigSerializer ImportError: cannot import name 'ConfigSerializer' from partially initialized module 'api.serializers' (most likely due to a circular import) (/Users/nick/work/shiftwork_backend/api/serializers/__init__.py) So I looked at the views/base.py and saw this: import requests from django.http import JsonResponse from django.shortcuts import get_object_or_404 from rest_framework.permissions import AllowAny from api.constants import Constants from api.models import Config, UserCompany, UserPattern from api.serializers import ConfigSerializer and views/init.py looks like below: from .base import * from .alarm import * from .company import * from .config import * from .holiday … -
Model hierarchy in Django
Sorry for the long text Models are given: User Hierarchy There are users, they can invite each other. The invitees, in turn, can accept the invite or reject it. Suppose that Mark invited Masha, Katya and Dima. Masha accepted Mark's invitation, and even invited Kolya herself. On one tab, you need to display the hierarchy. Continuing the example, Mark should have: 1st level: Masha, Katya, Dima 2nd level: Kolya and other guys 1st level for Mark - those whom he invited. 2nd level - those who were invited by people invited by Mark. And so on. Tell me how to implement it | what to familiarize yourself with to get closer to the result -
Django: saving models using parallel processing
I have a 35000 list of items which i have to update. I am planning to use bulk update. In bulk update we have the batch_size=option. I am planning to use a batch size of 20. Now what i found is that this runs the 20 sets of update in sequence. one after another Is it good idea to parallelize the update sets. If yes, how can i do it using multiprocess I came to know about multiporcessing a bit: import multiprocessing import django django.setup() # Must call setup def db_worker(item): from app.models import Model1 Model1.bulk_update(item).save() if __name__ == '__main__': list_update_values = 3500 items list_chunks = [] chunk_size = 20 for i in range(0,35000,chunk_size) list_chunks.append(list_update_values[i:i+chunk_size]) p = [multiprocessing.Process(target=db_worker,args=(item)) for item in list_chunks] p.start() p.wait() Will this going to help much -
How to solove, django.db.utils.IntegrityError: NOT NULL constraint failed: new__todolist_postcomment.comment_user_id
(projectenv) E:\demo practice\django-todolist_new\projectenv\src>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, todolist, userprofile Running migrations: Applying todolist.0012_auto_20201112_2021...Traceback (most recent call last): File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: new__todolist_postcomment.comment_user_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "E:\demo practice\django-todolist_new\projectenv\src\manage.py", line 22, in main() File "E:\demo practice\django-todolist_new\projectenv\src\manage.py", line 18, in main execute_from_command_line(sys.argv) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\core\management_init_.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "E:\demo practice\django-todolist_new\projectenv\lib\site-packages\django\db\backends\sqlite3\schema.py", … -
directive is not allowed here in /etc/nginx/default.d/app.conf:1 NGINX Config EC2
I'm trying to configure my app to run on ec2 with some difficulty. It's a multi container app built with docker-compose consisting of django, drf, channels, redis gunicorn, celery and nuxt for frontend. I've an instance running and can SSH to the instance and install the relevant packages, docker nginx docker-compose etc. What I can't do is edit my app.conf nginx file to use the public ip 33.455.234.23 (example ip) To route the backend, rest and frontend. I've created and app.conf nginx file which works fine local but when I try edit the nginx files after install to configure my app to the public ip's I run into errors. The error I have when writing my config is 2020/11/13 01:59:17 [emerg] 13935#0: "http" directive is not allowed here in /etc/nginx/default.d/app.conf:3 nginx: configuration file /etc/nginx/nginx.conf test failed This is my nginx config worker_processes 1; events { worker_connections 1024; } http { include /etc/nginx/mime.types; client_max_body_size 100m; upstream asgiserver { server asgiserver:8000; } upstream nuxt { ip_hash; server nuxt:3000; } server { listen 80 default_server; server_name localhost; location ~ /(api|admin|static)/ { proxy_pass http://asgiserver; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Host $host; } location /ws/ { proxy_pass http://asgiserver; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; … -
How to store video transcripts in a database
I have some video transcripts that I would like to be able to search and filter on. They are stored in SRT files currently. I have around 200 files/videos and they are for videos that are 4 hours long and each file is around 200-400KB depending on the length. I'm using Django for my backend and a Postgres database. Here's a snippet of an example: 1 00:00:00.503 --> 00:00:02.782 SPEAKER 1: text text text 2 00:00:02.782 --> 00:00:04.090 SPEAKER 2: more text So I was thinking I might store it so each of the pre-made blocks as a single entry in my db. So I would have a table like: speaker | text | start | end I'd say per file there is 6k entries so that's around 1.2 million records and it will keep growing. I'm not sure if that's going to be fast for a text search. How should I store my transcripts so I can search by text and filter on speaker quickly? -
Passing List of Dictionaries to Django View Using Ajax
I am new to Ajax and Django, so I might be missing something basic here. I am trying to pass a list of dictionaries to a Django view. Example: data = [ {'item':'itemname','qty':'qty','price','price'},{'item':'itemname','qty':'qty','price','price}, etc. ] I have set up my Ajax call to fire when a button is pressed. My cart.js $(document).ready(function(){ var userCart = grabCart(); userCart = JSON.stringify(userCart); $("#Checkout").click(function(){ $.ajax({ URL: some URL headers: csrf_token, //Im passing the token using Django type: 'POST', data: {'userCart':userCart}), success:function(){//stuff} complete:function(){//stuff, but its routing to confirmation.html} error:function(){//stuff} }); }); My Django view def confirmation(request): data = json.loads(request.POST.get('userCart')) # <-- this line is throwing the error print(type((data)) # this prints out list print(data) #this prints out the list of the dictionaries return render(request,'confirmation.html') I keep getting an Error 500, Type Error. The JSON object must be str, bytes, or byte array, not NoneType This is confusing. The results are there but Django is throwing an error and won't render the confirmation page. -
Loading Comments to page without Refreshing
I am new to JS and I am trying to learn steps to add comments to posts without refreshing the page. So, far I was successful in using JS in loading Like button without refreshing by following tutorials but I need some help with the comments. Here is the comments view.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 class PostCommentCreateView(LoginRequiredMixin, CreateView): model = Comment form_class = CommentForm def form_valid(self, form): post = get_object_or_404(Post, slug=self.kwargs['slug']) form.instance.user = self.request.user form.instance.post = post return super().form_valid(form) def form_invalid(self, form): return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('blog:post-detail', kwargs=dict(slug=self.kwargs['slug'])) Here is the template: <legend class="border-bottom mb-0"></legend> {{comments.count}} Comment{{comments|pluralize}} <div class="container-fluid mt-2"> <div class="form-group row"> <form action="{% url 'blog:post-comment' post.slug %}" method="post" class="comment-form" action="."> {% csrf_token %} {{ comment_form.as_p }} <input type="hidden" name="post_id" value='{{post.id}}' class="btn btn-outline-success"> <button type="submit" … -
Django ModuleNotFoundError: No module named 'Web_App.index'
I'm trying to use a function inside index.py which is in the same directory as views.py in Django but it won't work. These are my files.1 Dir -
How can I do to do some specific filter using Django?
I am using Django and I woud like to do some specific filter. Let's take this example : MyTable.objects.filter(number=3) This query will return me all the entries which has the following criteria number=3 but in what I would want is something like this : MyTable.objects.filter(number='all') And in this case I will get all the entries. I know I can do something like that : MyTable.objects.all() But I would like to use only filter to do that. Could you help me please ? Thank you a lot !