Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rendering ForeignKey objects in template with Django
I'm having trouble rendering related objects in a template. I have a Page model, that has a ForeignKey relationship to itself to define parent-child relationships. class Page(BaseModel): title = models.CharField( max_length=280, blank=False, null=False, ) description = models.CharField( max_length=280, blank=False, null=False, ) slug = models.SlugField( blank=False, null=False, ) is_home = models.BooleanField( default=False, ) is_parent = models.BooleanField( default=False, ) parent = models.ForeignKey( 'self', on_delete=models.PROTECT, default='Home', blank=True, null=True, related_name='children', ) content = RichTextField( blank=False, null=False, ) def __str__(self): return self.title def get_absolute_url(self): return reverse('page_detail', args=[str(self.slug)]) My views.py filters out non-parent pages: class PageListView(ListView): queryset = Page.objects.filter(is_parent=True, is_home=False) template_name = 'pages/page_list.html' context_object_name = 'page' But when it comes to rendering 'child' objects in my template, I'm stuck. I've figured that I need a loop within a loop (first for parent pages, second for child pages per parent page), but can't get the second loop to work. Here was my latest attempt, which got me a "'Page' object is not iterable" error. {% extends '_base.html' %} {% block content %} <div class="container"> {% for page in page %} <p>{{ page.title }}</p> {% for children in page %} <p>{{ page.title }}</p> {% endfor %} {% endfor %} </div> {% endblock content %} -
Passing html code from django and also from Javascript. How can I improve this?
I am making a twitter like social web page por homework. In one single page I have a form to write a tweet and enough space down there to show the tweets. To dynamicaly show them I`m using javascript fetch api to intercept the form and show them asynchronously: document.querySelector('form').onsubmit = (event) => { event.preventDefault(); fetch("", { method: 'POST', body: JSON.stringify({ body: document.querySelector('#new_message').value }), headers: { "Content-type": "application/json; charset=UTF-8", "X-CSRFToken": getCookie('csrftoken') } }) .then(response => response.json()) .then(result => { document.querySelector('#new_message').value = "" let div = document.createElement('div') div.innerHTML = ("<p>" + result.creation_date + "</p>" + "<a href='#'>" + result.username + "</a>" + ' said:' + '<br><br>' +"<div class='container'>" + "<p>" + result.body + "</p>" + "</div>"); div.style.cssText = "box-shadow: 0px 0px 2px; ; background-color:#F5F5F5; border-radius:10px; padding: 10px; margin: 5px;"; document.querySelector('#posts').append(div); }); } This dinamically shows the tweet when it`s written withouth reloading the page. But the problem comes when I want to display them when a user actually reloads the page, i mean, via a get method: if request.method == "GET": if request.user.is_authenticated: posts = Posts.objects.all().order_by('-creation_date') return render(request, "network/index.html", { "posts":posts }) else: return render(request, "network/login.html") This makes me handle the tweet html from the javascript code and also with django … -
Django site cycling between two views using schedule function
I created a site in Django that's supposed to cycle display a different song and album each day from Rolling Stone's top 500. However, if you refresh the site a few times, it eventually displays a different song and album than it originally did. What's more, it eventually goes back to the original song and album choices after a few more refreshes. Even stranger, it only switches between the same two song and album combinations, it never spontaneously picks a new song/album or adds a new set of songs and albums to the rotation. I've attached my views.py code responsible for displaying my home screen and loading a new song/album, let me know if you see the issue. entry = {"status": None} # Define song and Album of the day def reload(): # Change status of old song/album to used, and save the date that it was used if entry["status"] == "filled": currentSong = Songs.objects.get(entry["songEnt"].name) currentAlbum = Albums.objects.get(entry["albumEnt"].name) currentSong.dateUsed = datetime.now().date() - timedelta(days=1) currentAlbum.dateUsed = datetime.now().date() - timedelta(days=1) currentSong.used = True currentAlbum.used = True currentSong.save() currentAlbum.save() # If there is no old song, skip above step and begin adding new songs else: entry["status"] = "filled" song = Song.objects.filter(used = False).order_by("?").first() … -
Heroku Internal Server Error when Debug is False and collectstatic dosen't work - Django
I deployed an app to Heroku, which uses Postgres. Anytime I set Debug to True, it works fine. When I set it back to False, it gives an Error 500, Internal Server Error. I don't know why it does that. Does it have to do with staticfiles? I am using whitenoise for serving static files. Anytime I run heroku run python manage.py collectstatic, it gives me Running python manage.py collectstatic on djangotestapp... up, run.9614 (Free) 300 static files copied to '/app/staticfiles', 758 post-processed. When I then run heroku run bash, I find out that there is no staticfiles folder. Where exactly does it copy the static files to? Is this what is causing the Error 500? How can I solve it? settings.py import os import dj_database_url from decouple import config, Csv # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', cast=bool) SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_SECONDS = 200 SECURE_HSTS_PRELOAD = True ALLOWED_HOSTS … -
How to stop Django from removing stop words in auto-generated slugs from prepopulated_fields?
I am developing a dictionary application using Django. I would like the URL to contain the dictionary headword currently being examined, and I would like this to happen automatically. Using Django prepopulated_fields, however, when I insert headword "this is my headword", I get the slug "my-headword". How can I tell Django to generate the slug "this-is-my-headword" instead? In other words, how do I stop it from removing stop words from auto-generated slugs? Here is my Headword class in models.py: class Headword(models.Model): headword = models.CharField(max_length=64, unique=True) slug = models.SlugField(max_length=32, unique=True) def __str__(self): return f"{self.headword}" And here is my HeadwordAdmin class in admin.py: class HeadwordAdmin(admin.ModelAdmin): fieldsets = [ (None, {"fields": ["headword"]}), ("URL", {"fields": ["slug"]}), ] inlines = [DefinitionInline] list_display = ("headword",) search_fields = ["headword"] prepopulated_fields = {"slug": ("headword",)} -
'RedisChannelLayer' object is not callable
I have a Django app I'm using Django channels when deploying this app to Heroku I get this error 'RedisChannelLayer' object is not callable This is the trackback for this error 2020-08-29T19:33:37.543129+00:00 app[web.1]: 2020-08-29 19:33:37,542 DEBUG HTTP b'GET' request for ['10.9.251.250', 35308] 2020-08-29T19:33:37.543586+00:00 app[web.1]: 2020-08-29 19:33:37,543 ERROR Traceback (most recent call last): 2020-08-29T19:33:37.543592+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/daphne/http_protocol.py", line 180, in process 2020-08-29T19:33:37.543593+00:00 app[web.1]: "server": self.server_addr, 2020-08-29T19:33:37.543594+00:00 app[web.1]: TypeError: 'RedisChannelLayer' object is not callable 2020-08-29T19:33:37.543599+00:00 app[web.1]: 2020-08-29T19:33:37.543727+00:00 app[web.1]: 2020-08-29 19:33:37,543 DEBUG HTTP 500 response started for ['10.9.251.250', 35308] 2020-08-29T19:33:37.544107+00:00 app[web.1]: 2020-08-29 19:33:37,543 DEBUG HTTP close for ['10.9.251.250', 35308] 2020-08-29T19:33:37.544398+00:00 app[web.1]: 2020-08-29 19:33:37,544 INFO "10.9.251.250" - - [03/Jan/1970:21:31:20 +0000] "GET /favicon.ico HTTP/1.1" 500 452 "https://belkahla-mohamed-chatapp.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.9 Safari/537.36" 2020-08-29T19:33:37.544593+00:00 app[web.1]: 2020-08-29 19:33:37,544 DEBUG HTTP response complete for ['10.9.251.250', 35308] 2020-08-29T19:33:37.544687+00:00 app[web.1]: 10.9.251.250:35308 - - [29/Aug/2020:19:33:37] "GET /favicon.ico" 500 452 this is my asgi.py file: import os import django from channels.routing import get_default_application from channels.layers import get_channel_layer os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ProfilesApp.settings.development') django.setup() application = get_default_application() channel_layer = get_channel_layer() settings.py ASGI_APPLICATION = "ProfilesApp.routing.application" WSGI_APPLICATION = 'ProfilesApp.wsgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, }, } Please let me know how to fix … -
Django on Google Cloud App Engine: No Module Named 'django'
I am trying to deploy a Django website to GAE, but I keep getting a 502 error. When I look at the log files, I see this: "Traceback (most recent call last): File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/env/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 92, in init_process super().init_process() File "/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/env/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/env/lib/python3.7/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/opt/python3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/srv/main.py", line 1, in <module> from tanuki.wsgi import application File "/srv/tanuki/wsgi.py", line 11, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django'" I have Django installed on my virtual environment and my sys.path includes the path to the site-packages. Is there something else I am missing? -
How to change this code to make sure the User can only send a follow request once and not multiple times?
Hey guys I have a model and a function to send follow request to other users and they will be accepting the request if the sender has to follow them. problem is I need to make sure that when the sender first sends a request, the button shouldn't show follow again, instead should show cancel option to delete that request. As of now the user can send requests again and again. These are the codes. def send_follow_request(request, username): user_from = request.user user_to = Account.objects.get(username=username) # is_requested = False send_request = notify.send(user_from, recipient=user_to, verb='has sent you a follow request', target=user_to) # is_requested = True return redirect('posts:userprofile', user_to.username) models.py class Contact(models.Model): user_from = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='rel_from_set', on_delete=models.CASCADE) user_to = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='rel_to_set', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) follow_status = models.CharField(choices=FOLLOW_STATUS, max_length=10) #USER_FROM IS THE ONE WHO IS FOLLOWING AND USER_TO IS ONE BEING FOLLOWED class Meta: ordering = ('-created',) def __str__(self): return f'{self.user_from} follows {self.user_to}' following = models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False) #adding the above field to User Model class user_model = get_user_model() user_model.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) Thank you -
Django - 'QuerySet' object has no attribute 'künstler_set'
I have a relation between an artist and images. I want to show a single artist and his related images. I created two models for artist and image. Inside the image class I made a ForeignKey to artist: class Artist(models.Model): profilepic = models.ImageField( blank=True) surname = models.CharField(max_length=120) class Image(models.Model): image = models.ImageField() relArtist = models.ForeignKey(Artist, null=True, on_delete=models.SET_NULL) inside my views.py I tried to get the artist by ID (primaryKey) which is working perfectly but it didn't work with the images. def artistSingle(request, pk): artist = Artist.objects.filter(id=pk) images = artist.relArtist_set.all() return render(request, 'artists/artistSingle.html', { 'artist': artist, 'images': images, }) If I run the code it throws an error: 'QuerySet' object has no attribute 'relArtist_set' I dont know how to get the images which rely to the artist. Does someone have a solution? -
How to be sent to another html page using django ID
I am creating a website where i am using django database.The database will have one def called categories and one called gifi.So a gif will belong to a category and when one category will be clicked it will send the user to a page where all gifs that belong to that category will show up,and when i click to one of the gifs i will be sent to another html page that will contain information about the clicked gif.I know that i should do something like requesting ID but i dont know the code. This is the models: from django.db import models class categorite(models.Model): name = models.CharField(max_length=100) id = models.AutoField(primary_key=True) class Gifi(models.Model): foto = models.ImageField(upload_to='website/static/') emri = models.CharField(max_length=100) Source = models.CharField(max_length=100) Kodet = models.CharField(max_length=12) categoryId = models.ForeignKey(categorite, on_delete=models.CASCADE) id = models.AutoField(primary_key=True) This is views: from django.shortcuts import render,get_object_or_404 from .models import Gifi,categorite # Create your views here. def home(request): return render(request, 'website/home.html') def categories(request): content = { 'view': categorite.objects.all() } return render(request, 'website/categories.html',content) def PostaCode(request): return render(request, 'website/PostaCode.html') def Contact(request): return render(request, 'website/Contact.html') def category(request,id): content = { 'view': Gifi.objects.filter(categoryId_id=id), } return render(request, 'website/category.html',content) def code(request,id): content = { 'view': Gifi.objects.filter(id_id=id) } return render(request, 'website/code.html',content) The def code is the … -
django form doesn't upload images but admin panel does how can I solve this problem,
This is all files in my GitHub enter link description here -
Access to XMLHttpRequest at 'http://localhost:8000/api/posts/' from origin 'http://localhost:3000' has been blocked by CORS policy. Django and React
I am creating a full-stack app with Django and React. I created a component lookup in which I use cookies. This is my code: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function lookup(method, endpoint, callback, data) { let jsonData; if (data){ jsonData = JSON.stringify(data) } const xhr = new XMLHttpRequest() const url = `http://localhost:8000/api${endpoint}` xhr.responseType = "json" const csrftoken = getCookie('csrftoken'); xhr.open(method, url) xhr.setRequestHeader("Content-Type", "application/json") if (csrftoken){ xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest") xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest") xhr.setRequestHeader("X-CSRFToken", csrftoken) } xhr.onload = function() { callback(xhr.response, xhr.status) } xhr.onerror = function (e) { console.log(e) callback({"message": "The request was an error"}, 400) } xhr.send(jsonData) } export function createPost(newPost, callback){ lookup("POST", "/posts/create/", callback, {content: newPost}) } export function loadPosts(callback) { lookup("GET", "/posts/", callback) } This code results in this error in my frontend: (the backend works fine) Access to XMLHttpRequest at 'http://localhost:8000/api/posts/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field http_x_requested_with is not allowed by Access-Control-Allow-Headers in preflight … -
Invalid base64-encoded string: number of data characters (217) cannot be 1 more than a multiple of 4
I am learning django and creating a todo app using it. while setting up the django rest framework api. I am getting an unusual error. I am using django for some time, but never got the same error before. I don't know why is this error coming. The error occurred the very first time when I executed the command manage.py runserver and navigated to users The error is as below Invalid base64-encoded string: number of data characters (217) cannot be 1 more than a multiple of 4 Request Method: GET Request URL: http://127.0.0.1:8001/users/ Django Version: 3.1 Exception Type: Error Exception Value: Invalid base64-encoded string: number of data characters (217) cannot be 1 more than a multiple of 4 Exception Location: /usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/base64.py, line 87, in b64decode Python Executable: /Users/yogendrakumar/PycharmProjects/todo_app/bin/python Python Version: 3.8.5 Python Path: ['/Users/yogendrakumar/PycharmProjects/todo_app', '/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python38.zip', '/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8', '/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload', '/Users/yogendrakumar/PycharmProjects/todo_app/lib/python3.8/site-packages'] Server time: Sat, 29 Aug 2020 12:25:01 +0530 views.py from django.contrib.auth.models import User, Group from rest_framework import viewsets from rest_framework import permissions from todo.serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or … -
What is the preffered way to access Django Database ? Raw SQL or Django queries?
Django documentation suggests to use Django ORM queries to access database to avoid certain issues with Raw SQL. Later I found that almost any queries can be done with Django ORM queries. I have not studied SQL queries much and relied heavily on ORM. does Raw SQL queries have any advantages ? -
how can i solve this error ( Field 'total_price' expected a number but got {'price__sum': 222} ) django?
how can i get the total_price of books which the added by user in store. i also add a @property to calculate and save the total price. when i try to save the form i getting typeError Exception Value: Field 'total_price' expected a number but got {'price__sum': 222}. how can i solve this issue? Store class Book(models.Model): name = models.CharField(max_length=100) price = models.IntegerField(default=0) def __str__(self): return self.name class Store(models.Model): keeper = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) books = models.ManyToManyField(Book) total_price = models.IntegerField(default=0) @property def save(self): self.total_price = self.books.all().aggregate(Sum('price')) super(Store, self).save() -
How to compare dictionary key and queryset value in Django Template
I'm trying to compare a dictionary key with query set variable in a Django Template. Both output correctly on their own, however, together I cannot compare the values. Django template {% for object in query_set %} {% for key, value in dictionary.items %} var key = {{ key }}; {% if key == query_set.name %} <h5> You get this value: {{ value }}</h5> {% endif %} {% endfor %} {% endfor %} What ends up happening is that key gets all the variable values instead of a singular value and it cannot properly compare. Output of key key var = output 1; key var = output 2; key var = output 3; I think I'm just missing a syntax error or maybe I need to write a custom html tag to do this? -
Return key/attribute JSON object instead of array of JSONs for model Django Rest Framework
Like mentioned in the title.I have such JSON array being returned from backend: [ {id:1, name:'name1'}, {id:2, name:'name2'}, {id:3, name:'name3'}, {id:4, name:'name4'} ] and I would like to return something like this instead: { "1": {id:1, name:'name1'}, "2": {id:2, name:'name2'}, "3": {id:3, name:'name3'}, "4": {id:4, name:'name4') } Is it possible in Django Rest framework to send such object as Response ? Obviously there will not be too many keys so size should not be an issue. -
How to translate field name in Django?
I am writing a web app backend that need to reuse an existing REST API. The API has a list of configuration field in JSON looks like this: feature1.export.car.functionA feature1.export.car.functionB feature2.a.b.c Whereas it is a dot notation string and the value can be anything. I was planning to have several Django models that represent those fields base on the feature and each configuration field will be represented by each model field. I am planning to use verbose_name in the Field object to represent the actual Django model field so that I can do the mapping between the input field from the API and the Django model field: class Feature1(models.Model): export_car = models.CharField(verbose_name="feature1.export.car.functionA") class Feature2(models.Model): a_field = models.CharField(verbose_name="feature2.a.b.c") But I am not sure how to do the 1 to 1 mapping when I receive the request from the View class. Is there an easy way to do that in Django? -
cURL - file upload with file path location not working with windows command prompt
I am trying to send a file to server using cURL command from windows command prompt. But getting error message. But using postman I am able to send a file to server. Below given details. These are the two cURL commands I tried to send/upload file by just sending file location: curl --insecure -F user_file=@"C:/Users/402096/Desktop/dau_settings-123.conf" -H "Content-Type: application/json" -H "Authorization: Token 3f98d0a178ddd176faea94e6d629621920d203b2624550e68a" -X POST https://10.107.12.123/import_config curl --insecure -F "user_file=@C:/Users/402096/Desktop/dau_settings-123.conf" -H "Content-Type: application/json" -H "Authorization: Token 3f98d0a178ddd176faea94e6d629621920d203b2624550e68a" -X POST https://10.107.12.123/import_config Here is the my code which will be called to upload a file in django @api_view(["POST", "GET"]) @permission_classes((IsAuthenticated,)) @permission_required('dau_gui_app.execute_import_config') def import_config_view(request): if request.method == 'POST' and request.FILES['user_file']: user_file = request.FILES['user_file'] fs = FileSystemStorage() filename = fs.save( user_file.name, user_file) filePath = fs.location + "/" + filename print filePath message ="{\ \"command\":\"execute\",\ \"subcommand\":\"import_config\",\ \"args\": [{\"file_path\":\"" + filePath + "\"}]}" message.replace(" ", "") try: response = send_cmd(message) except: print("An exception occurred sending the message:") print(message) #end try fs.delete(filename) return HttpResponse(response, content_type='application/json') return render(request, 'dau_gui_app/import_config.html' ,{'title':"Import Configuration" }) NOTE: I am able to successfully upload a file using postman. When I looked at the cURL code that postman has used to upload/send a file, I see below cURL in postman. But when I typed same … -
When an object is created with an admin form, how can to create related objects?
When I create a PotatoBatch item via my admin form, I want many Potato objects to be created. Potato has a ForeignKey to PotatoBatch. I made a PotatoBatchCreateForm that has an extra field, "number_of_potatoes". When I save this form, I want it to generate the correct number of potatoes for this batch. I wanted to override my PotatoBatchCreateForm's save method like this : def save(self, commit=True): potato_batch = super().save() # save the potato_batch object in order to have an object id number_of_potatoes = self.cleaned_data['number_of_potatoes'] for i in range(number_of_potatoes): Potato.objects.create(potato_batch=potato_batch) return potato_batch But this fails with a 'PotatoBatchCreateForm' object has no attribute 'save_m2m' error. How can I resolve this ? -
Django Error: "You're using the staticfiles app without having set the required STATIC_URL setting"
django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the required STATIC_URL setting. This is appearing in the command prompt. I'm not sure I understand -
Javascript formdata object doesn't send any key, pair value over to the django frame
Django framework isn't able to print the post data from the XMLHttpRequest I'm writing vanilla javascript by the way and not jquery, Please don't write a jquery answer . Thanks In Advance. BELOW IS MY HTML CODE <form action="{% url 'feed:update_comment' comment.id %}" method="POST" onsubmit="UpdateComment(event)" class="comment-update-form">{% csrf_token %} <div class="close-comment-box"onclick="this.parentElement.parentElement.classList.add('hide')"> <span>&times;</span> </div> <textarea name="body" id="post_body">{{comment.text}}</textarea> <div class="btn-div"> <button type="submit" class="button">Update</button> </div> </form> BELOW IS MY VANILLA JAVASCRIPT function UpdateComment(event){ event.preventDefault() let comment_field_to_update = event.target.parentElement.parentElement.parentElement.querySelector('.comment-text-div').querySelector('.feed_text_element') const data = new FormData(event.target); const xhttp = new XMLHttpRequest(); xhttp.onload = (response)=>{ console.log(response) } xhttp.open("POST",event.target.getAttribute("action","action"),true) xhttp.setRequestHeader("Content-Type",'application/x-www-formurlencoded') xhttp.setRequestHeader('X-CSRFToken',csrftoken) xhttp.send(data) } BELOW IS MY PYTHON DJANGO CODE from django.http import JsonResponse @login_required def updateComment(request,id): if request.method == "POST": response = {} try: comment = Comment.objects.get(id=id) if comment.author == request.user: comment.text = request.POST['body'] comment.save response['200'] = comment.text return JsonResponse(response) else: response['400'] = 'You Can"t Edit This Comment' return JsonResponse(response) except Comment.DoesNotExist: response['404'] = 'Comment Not Found' return JsonResponse(response) BELOW IS THE ERROR I'M GETTING FROM DJANGO System check identified no issues (0 silenced). August 29, 2020 - 17:23:54 Django version 2.2.14, using settings 'jumbo.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /update_comment&comment_identifier=/9/ Traceback (most recent call last): File "/usr/lib/python3/dist-packages/django/utils/datastructures.py", line 78, in … -
How to create a system tray popup message with Django? (Windows)
I have a web app, in Django, Azure. I want to click a button and send a notification to another users (user info stored in db). This has to appear on their notification bar when they are logged in. How can I initiate it? I know there are several ways to do it, please suggest the best option. -
JavaScript translates my "a" string to 'a'
I'm sending: short_names = ["a", "b"] as context through function view to JS. Then I'm using it in JS: let names = {{ short_names }}; But what i really got is: labels: [&#x27;a&#x27;, &#x27;b&#x27;] What's going on with this behaviour? How may omit it? -
Django : how to divide result from search
Assume I've created a search views with chain (multiple search from different app). I want to display my result at the same place: {% for object in object_list %} {% with object|class_name as klass %} {% if klass == 'Post' %} {{ object.title }} {% elif klass == 'Catego' %} {{ object.name }} {% elif klass == 'UserProfile' %} {{ object.user.username }} {% else %} {% endif %} {% endwith %} {% empty %} {% endfor %} Everything is ok. I got all of my result. Now, if I want to separate this result in different div (row and collapse class). If I try this: <div class="row collapse" id="collapseNutri"> {% for object in object_list %} {% with object|class_name as klass %} {% if klass == 'Post' %} {{ object.title }} {% endif %} {% endwith %} {% endfor %} </div> <div class="row collapse" id="collapseCatego"> {% for object in object_list %} {% with object|class_name as klass %} {% if klass == 'Catego' %} {{ object.name }} {% endif %} {% endwith %} {% endfor %} </div> <div class="row collapse" id="collapseUserProfile"> {% for object in object_list %} {% with object|class_name as klass %} {% if klass == 'UserProfile' %} {{ object.user.username }} …