Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why does my cart page doesnt show its content properly?
{% extends 'app/base.html' %} {% load static %} {% block title %}Cart{% endblock title %} {% block main-content %} <div class="container my-5"> <div class="row"> {% if cart %} <h1 class="text-center mb-5">Shopping Cart</h1> <div class="col-sm-8"> <div class="card"> <div class="card-body"> <h3>Cart</h3> {% for item in cart %} <div class="row"> <div class="col-sm-3 text-center align-self-center"><img src="{{item.product.product_image.url}}" alt="" srcset="" class="img-fluid img-thumbnail shadow-sm" height="150" width="150"></div> <div class="col-sm-9"> <div> <h5>{{item.product.title}}</h5> <p class="mb-2 text-muted small">{{item.product.description}}</p> <div class="my-3"> <label for="quantity">Quantity:</label> <a class="minus-cart btn" pid={{item.product.id}}><i class="fas fa-minus-square fa-lg"></li></a> <span id="quantity">{{item.quantity}}</span> <a class="plus-cart btn" pid={{item.product.id}}><i class="fas fa-plus-square fa-lg"></li></a> </div> <div class="d-flex justify-content-between"> <a href="#" class="remove-cart btn btn-sm btn-secondary mr-3" pid={{item.product.id}}>Remove item </a> <p class="mb-0"><span><strong>₱ {{item.product.discounted_price}}</strong></span></p> </div> </div> </div> </div> <hr class="text-muted"> {% endfor %} </div> </div> </div> <div class="col-sm-4"> <div class="card"> <div class="card-body"> <h3>The Total Amount of</h3> <ul class="list-group"> <li class="list-group-item d-flex justify-content-between align-items-center border-0 px-0 pb-0" >Amount<span id="amount">₱{{amount}}</span></li> <li class="list-group-item d-flex justify-content-between align-items-center px-0">Shipping<span>₱144.00</span></li> <li class="list-group-item d-flex justify-content-between align-items-center border-0 px-0 mb-3"> <div> <strong>Total</strong> <small>(including GST)</small> </div> <span id="totalamount"><strong>₱ {{totalamount}}</strong></span> </li> </ul> <div class="d-grid"><a href="{% url 'checkout' %}" class="btn btn-primary">Place Order</a></div> </div> </div> </div> {% else %} <h1 class="text-center mb-5">Cart is Empty</h1> {% endif %} </div> </div> {% endblock main-content %} The code above is the addtocart html and when … -
How to not save into database if document upload is failed
When a user uploads a document and clicks submit the file is stored in a folder and a database entry is created along with bunch of other details. What I am looking for is to avoid the save if the document doesn't get uploaded into the specific location. serializer.py class DocumentSerializer(serializers.ModelSerializer): class Meta: model = Request fields = ['file', 'doc_type'] def create(self, validated_data): msg = self.__construct_message_body() validated_data['type'] = Request.request_types[-1][0] validated_data['input_message'] = msg instance = ParseRequest.objects.create(**validated_data) msg['request_id'] = instance.id instance.input_message = msg instance.save() return instance views.py class DocumentView(CreateAPIView, ResponseViewMixin): parser_classes = (MultiPartParser, FileUploadParser,) serializer_class = DocumentSerializer def create(self, request, *args, **kwargs): try: data = request.data serializer = self.get_serializer( data=data, context={'request': request}) serializer.is_valid() serializer.save() except Exception as e: logger.error(e) return self.error_response(message=ERROR_RESPONSE['UPLOAD_DOCUMENT']) return self.success_response(message=SUCCESS_RESPONSE['UPLOAD_DOCUMENT']) -
Django generate thumbnail from video, but it encodes it
Im using django-video-encoding this and django-rq to generate a thumbnail but instead it generates another video AND it makes it smaller(in size) here is signals.py: ` from django.db.models.signals import post_save from django.dispatch import receiver from typing import Type from . import tasks , signals from .models import Post from django_rq import enqueue @receiver(post_save, sender=Post) def create_thumbnail(sender, instance, **kwargs): enqueue(tasks.create_thumbnail, instance.pk) here is tasks.py: ` from django.core.files import File from video_encoding.backends import get_backend import os from .models import Post def create_thumbnail(post_pk): video = Post.objects.get(pk=post_pk) if not video.video: print('no video file attached') # no video file attached if video.thumbnail: print('thumbnail has already been generated') # thumbnail has already been generated encoding_backend = get_backend() thumbnail_path = encoding_backend.get_thumbnail(video.video.path) path = video.video.url filename = os.path.basename(path), try: with open(thumbnail_path, 'rb') as file_handler: django_file = File(file_handler) video.thumbnail.save(filename[0], django_file) video.save() finally: os.unlink(thumbnail_path)` and models.py: `from django.db import models from django.contrib.auth.models import User from django.core.validators import FileExtensionValidator from django.contrib.contenttypes.fields import GenericRelation from video_encoding.fields import VideoField, ImageField from video_encoding.models import Format class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=500) description = models.TextField() format_set = GenericRelation(Format) video = VideoField(upload_to='uploads/video_files/%y/%d', validators = [FileExtensionValidator(allowed_extensions=['mp4'])]) thumbnail = ImageField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.title + "\n" … -
ERROR: (gcloud.app.deploy) INVALID_ARGUMENT: Deploying a django app using google app engine
I keep getting error INVALID_ARGUMENT: Filename cannot contain '.', '../', '\r', start with '-', '_ah/', or '\n': --project. Whenever I try to deploy my django Portfolio website using google app deploy. #for my app.yaml file runtime: python37 First I tried using gcloud app deploy and then this below- gcloud app deploy app.yaml --project afroweb -
save() got an unexpected keyword argument 'force_insert' in serializer
My Product model has a many-to-many field warehouse_stocks and to save this I have been using: class ProductSerializer(serializers.ModelSerializer): warehouse_stocks = ProductsInWarehouseSerializer(many=True) class Meta: model = Product fields = "__all__" def create(self, validated_data): print("validated data", validated_data) items_objects = validated_data.pop('warehouse_stocks', []) prdcts = [] for item in items_objects: i = ProductsInWarehouse.objects.create(**item) prdcts.append(i) instance = Product.objects.create(**validated_data) instance.warehouse_stocks.set(prdcts) return instance and this has been working fine in the project but I recently started getting this error: TypeError: save() got an unexpected keyword argument 'force_insert' Full error: Traceback (most recent call last): File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\Rahul Sharma\PycharmProjects\Trakkia-Backend\masters\views.py", line 76, in post serializer.save() File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\rest_framework\serializers.py", line 212, in save self.instance = self.create(validated_data) File "C:\Users\Rahul … -
django: foreign key issues when creating a model object
I am trying to write a row to database, with data gathered in a form. I need to work with two foreign keys and one of them is causing the creating to fail, although I am unable to figure out why: here is my model: def upload_path(instance,file): file_dir = Path(file).stem print('usr',instance.user.id) path = '{}/{}/{}/{}'.format(instance.user.id,"projects",file_dir,file) return path class BuildingFilesVersions(models.Model): version_id = models.AutoField(primary_key=True) building_id = models.ForeignKey(Building, on_delete=models.CASCADE,related_name='building_id_file') user = models.ForeignKey(Building, on_delete=models.CASCADE,related_name="user_file") created_at = models.DateTimeField(auto_now_add=True, blank=True) description = models.TextField(max_length=200, blank=True, null=True) modification_type = models.CharField(choices=WORK_TYPE_CHOICES, max_length=200, blank=True, null=True) filename = models.CharField(max_length=200, blank=True, null=True) file = models.FileField(upload_to=upload_path, null=True, blank=True) and here is my view: @login_required @owner_required def RegisterFileView(request,pk): form = AddBuildingFileForm() if request.method == 'POST': form = AddBuildingFileForm(request.POST,request.FILES) if form.is_valid(): description = form.cleaned_data["description"] modification_type = form.cleaned_data["modification_type"] filename = form.cleaned_data["modification_type"] file = request.FILES['file'].name BuildingFilesVersions.objects.create(building_id_id=pk, user_id=request.user, description=description, modification_type=modification_type, filename=filename, file=file) return redirect('home') else: form = AddBuildingFileForm() context = {'form':form} return render(request, 'building_registration/register_file.html', context) what gets me confused is that the error is Field 'building_id' expected a number but got <SimpleLazyObject: <User: Vladimir>> even though pk return the proper building_id Can anyone see where I messed up? -
Change properties of a foreign key field in default django table
I am trying to use an existing database with django ORM. I have created the models for the tables that I want to use. python manage.py makemigrations ran without any problem. python manage.py migrate returns the error File "/home/s30python-02/anaconda3/envs/test/lib/python3.10/site-packages/pymysql/err.py", line 143, in raise_mysql_exception raise errorclass(errno, errval) django.db.utils.OperationalError: (1005, 'Can't create table site_db.django_admin_log (errno: 150 "Foreign key constraint is incorrectly formed")') I had read that the FOREIGN KEY references in MySQL is that both columns of the constraint must the same column definition. So I checked and the DataType of primary key of user table is int(11) unsigned and the user_id in django_admin_log table is bigint(20). And I think the problem is due to that. Is there a way to override LogEntry which is responsible for the django_admin_log table and change the user_id field properties or is there anything else that can be done. Need your insight on this one. Thanks for your time... -
How to get current page of django rest pagination in List Api View?
How am I, with this code, supposed to get the current page of pagination in Django Rest in a proper way? class LatestEpisodesAPIView(ListAPIView): serializer_class = LatestEpisodeSerializer pagination_class = StandardResultsSetPagination def get(self, request, *args, **kwargs): res = super(LatestEpisodesAPIView, self).get(request, *args, **kwargs) res.render() cache.set("apiepisode_p_" + HOWTOGETCURRENTPAGINATIONPAGE, res, 60*5) return res In this code I wanted to cache the response of the current page for 5 minutes, by which extravagant joining costs could be averted as the cpu operation costs could peak a high of 500ms per request, and this endpoint is frequently used. To that end, the prerequisite is a unique key for each page, which, in common sense, would be the page number. However, inasmuch the impoverished lackluster inherent nature of DRF's official documentation, information about pagination per se is already scarcer than hen's teeth, let alone trying to get the current page. After hours of scouring the length and breadth of DRF docs, and brute-forcing google search, I myself still fail to find any way to accomplish this goal. I believe I could do this by request.query_params.get("page") but this seems really hard-coded and looks more like a hack than a proper way of doing things. Thanks for your help! -
How to associate form with a button outside that form?
Given this field {% bootstrap_field form.photo %} which is a forms.ImageField and the form after, I need to associate the field with the form in a way that when the form is submitted, I get the value in form.photo. <div class="row container h-100"> <div class="col-xl-4"> <div class="card mb-4 mb-xl-0"> <div class="card-body text-center"> <img style="max-width: 50%" alt="Avatar" class="img-account-profile rounded-circle mb-2" src={{ request.user.profile.photo.url }}> {% bootstrap_field form.photo %} </div> </div> </div> <div class="col h-100"> <div class="card shadow-lg"> <div class="card-body p-5"> <form enctype="multipart/form-data" method="post"> {% csrf_token %} <div class="row"> <span class="col"> {% bootstrap_field form.first_name %} </span> <span class="col"> {% bootstrap_field form.last_name %} </span> <button class="btn btn-success col">Update</button> </div> </form> </div> </div> </div> </div> Currently if a photo is uploaded, it won't show up in the form response because it's not included within <form></form>. I need it to be outside the form because the locations of the form fields and the photo are different. -
Order django queryset by rank of related tags
I'm a little stuck on something. I'm trying to create a cheatsheets app where the user can upvote other users posts. I'm using django-taggit to manage tags and django-vote for voting functionality. class Cheatsheet(VoteModel, models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=500, null=True, blank=True, default="") description = models.CharField( max_length=500, null=True, blank=True, default="") tags = TaggableManager(blank=True) def __str__(self): return self.title and this is the view: class CheatsheetViewSet(viewsets.ModelViewSet, VoteMixin): queryset = Cheatsheet.objects.all() serializer_class = CheatsheetSerializer http_method_names = ['get', 'post', 'retrieve', 'put', 'patch', 'delete'] I'm trying to sort cheatsheets based on the tags related to previously upvoted posts. I have managed to obtain a "tag rank" based on the posts that the user has upvoted. For example if the user upvoted a post with the tags "css" and "js" and another post with only the tag "css" user_tag_rank would result in something like this: {"css": 2, "js": 1} I would like to order the posts based on this rank, with tags with the most upvotes first. In this case all posts with the tag "css" would come first, then posts with the tag "js" and then any other posts. The question is how do I go about sorting the posts based on … -
Diango matching a string with a regex field
In django, if we have a regex and look for a rows whose a field is matching with a regex, it will be something like this: MyAudience.objects.filter(email__iregex=f'^({'|'.join(emails)})$') But what if I want to do it the other way? Let's say I have a string: email = 'abc@example.com' and in my model AudienceFilter, I have a field pattern. This column keeps the regex for the model. I want to find with patterns do match my string? How can I do that? AudienceFilter.objects.filter(pattern__?????=email) -
SQLite error when deploying Django Website on AWS
I'm neewbie here and in programming, so please have some mercy :D I'm making my first Django project with Maximilian Course. I have made Django blog. I walked through few errors when deploy, but now i have encountered this one: enter image description here So I found this solution: https://stackoverflow.com/questions/66380006/django-deterministic-true-requires-sqlite-3-8-3-or-higher-upon-running-python So i understand it like this: 1. In ubuntu terminal i type : sudo apt install python3.10-venv to install envirement 2. Then in my Django project in Visual Studio i type python3 -m venv django_my_site to create virtual env 3. Now i click "+" to open this env and type pip3 install pysqlite3 pip3 install pysqlite3-binary 4. After that i type python3 -m pip freeze > requirements.txt and i get requirements.txt file which looks like that: [enter image description here](https://i.stack.imgur.com/ZeS20.png) 5. After that i pack once more all necessary folders and files [enter image description here](https://i.stack.imgur.com/TTZWZ.png) 6. In AWS in application versions I upload zip once more and deploy. 7. Now looks like AWS have problem with installing packages I have an error log like this: https://files.fm/f/562x66duz -
Redirecting old urls to new urls in Django
After publishing site in Django, I changed my slugs and now old pages show as errors in Google search. Is there a way to automatically redirect them without having to write an individual redirect for each page? -
What is the max size of Django cache and is there any chance to extend that?
I'm working on a project where i have to deal with big data (big number of rows) To make the app fast I'm using redis with Django cache , I'm selecting all the data from Table A and saving it to cache as a json array, and later I select, update and delete from cache, I also have other tables B, c, D ... etc Each table could hold more then 3 million rows in the future, probably more and more ... I was wounding if Django cache can handle that? If not what's the maximum size or rows that Django cache can store? Is there a way to extend that, if not what are the order solutions for this problem? I don't want to select data always from database, Because speed does matters here -
I have an error in installing django-socketio in windows virtualenv
I have a problem in installing django socket io, i changed django version to 3.2 and still the error image of the error -
How to change where vitejs puts its HTML files?
I want to change where vite produces its HTML files, but I have not been able to figure it out yet. By default, the files for an html page get compiled into these file locations: /dist/src/pages/index.js /dist/src/pages/index.html The locations above are produced by this vite.config.ts: import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import path, { resolve } from "path"; import manifest from "./src/manifest"; import makeManifest from "./build-utils/rollup-plugins/make-manifest"; const root = resolve(__dirname, "src"); const pagesDir = resolve(root, "pages"); const assetsDir = resolve(root, "assets"); const outDir = resolve(__dirname, "dist"); // const publicDir = resolve(__dirname, "src", "public"); const publicDir = resolve(__dirname, "src", "copied-to-dist-on-compile"); const isDev = process.env.__DEV__ === "true"; const isProduction = !isDev; export default defineConfig({ resolve: { alias: { "@src": root, "@assets": path.resolve(root, "assets"), "@pages": path.resolve(root, "pages"), "@utils": path.resolve(root, "utils") }, }, plugins: [ react(), makeManifest(manifest), ], publicDir, build: { outDir, assetsDir, minify: isProduction, reportCompressedSize: isProduction, rollupOptions: { input: { devtools: resolve(pagesDir, "devtools", "index.html"), panel: resolve(pagesDir, "panel", "index.html"), content: resolve(pagesDir, "content", "index.ts"), background: resolve(pagesDir, "background", "index.ts"), contentStyle: resolve(pagesDir, "content", "style.scss"), popup: resolve(pagesDir, "popup", "index.html"), newtab: resolve(pagesDir, "newtab", "index.html"), options: resolve(pagesDir, "options", "index.html"), }, watch: { include: ["src/**", "vite.config.ts"], exclude: ["node_modules/**", "src/**/*.spec.ts"], }, output: { entryFileNames: "src/pages/[name]/index.js", chunkFileNames: isDev ? … -
Deployment issues with railway
due to the new pricing of heroku I decided to switch from heroku to railway. At first I encountered a cors header error but then I added SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') to my settings.py file. The error stopped occurring but now I'm facing a new error <meta name="viewport" content="width=device-width, initial-scale=1"> <meta charset="utf-8"> <title>Server Error</title> and the title of the error is response status is 503. I've set Debug to False, I've added the url to the list of Allowed hosts and I've also added corsheaders to installed apps and the cors middleware. Any help with go a long way. -
How to keep calling api until task is completed in reactjs?
I am working on reactjs as frontend, and Django in the backend. I have a time taking task written in django, which ideally takes more time to retrieve values than the stipulated API response time. Therefore, I have made it into a celery task, whose task id I return as an API response. The plan was to make the API call on page load which starts the celery task, and returns the task ID. So, with the task ID, I can keep polling another API to get the task's status, until completed. Once the task is completed, I can ping another API to get the response of the celery task. I thought, I can make the API call, and thenafter run a loop with a sleep, but not sure how to achieve this? import { useEffect, useState } from "react" import axios from "axios" function App() { const [taskId, setTaskId] = useState("") const apiToSpawnTask = () => { axios.get("http://localhost:8000/spawn_task") .then(({data}) => setTaskId(data.task_id)) } const checkTaskStatus = () => { axios.get(`http://localhost:8000/task-id/${taskId}`) .then(({data}) => { // data.status contains the status of the task id }) } const getCompletedTaskResult = () => { axios.get(`http://localhost:8000/get-task-result/${taskId}`) .then(({data}) => { // this data is used in … -
Csv to django model with many-to-many relationship
I have to write a script to load data from a csv file and add the entries to a django database. The only problem I have is that I need to group entries from one column and link it to the id-s, like this: So notice that the same protein id-s map to different protein-domains, but protein_domains can also map to more than one protein, thus I need the many-to-many relationship. Of course, protein id I can only have one, so the data should be like: [protein_id, protein_taxonomy,[protein_domain,protein_domain],protein_length] My django models look like this: class Domains(models.Model): pfam = models.ForeignKey(ProteinFamily, on_delete=models.DO_NOTHING) # pfam = models.CharField(max_length=15, null=True, blank=False) description = models.CharField(max_length=100, null=True, blank=False) start = models.IntegerField(null=False, blank=True) stop = models.IntegerField(null=False, blank=True) def __str__(self): return self.pfam.domain class Protein(models.Model): protein = models.ForeignKey(ProteinId, on_delete=models.DO_NOTHING) protein_taxonomy = models.ForeignKey(Taxonomy, on_delete=models.DO_NOTHING) protein_length = models.IntegerField(null=True, blank=True) protein_domains = models.ManyToManyField(Domains, through='ProteinDomainsLink') def __str__(self): return self.protein.protein_id This is my attempt to load the data from csv and add it to the database: with open(assignment_data_set) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: proteins.add((row[0],row[8],row[5],row[1])) protein_rows = {} for entry in proteins: row = Protein.objects.create(protein=proteinIds_rows[entry[0]],protein_length=entry[1],protein_taxonomy=taxonomy_rows[entry[3]]) row.protein_domains.add(domains_rows[entry[2]]) row.save() protein_rows[entry[0]] = row It kind of works, but still 2 Protein objects get created … -
Single Sign-on architecture with Django and Azure
I have 3 applications developed with Django Framework and i need to centralize authentification through Single Sign-On (SSO) with Azure AD. My questions are the following : What is the best architecture to implement the solution? Which libraries should i use ? (i'll be gratefull if usefull tutorials are attached :p) -
how to connect ClearDB -mysql database to my web app django project
i have deployed my first Dejango webapp to Heroku. At the begining it was working but it was not connecting the database and loging and also create super user was not working either. i changed database in heroku from Postgre to ClearDB database because this last one is free in Heroku. the problem is when i try to python manage.py makemigrations or migrate or createsuperuser it does not work and shows this error: **(2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") **``` i changed the Database from settings.py but it was not working either: this is the database file from Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '******', here i have changed from my local database to the new name coming from heroku 'USER': '******', here i have changed the user for the one coming from Heroku 'PASSWORD': '******', here i have changed the passworkd for the one coming from Heroku 'HOST': '****', here i have changed the HOST for the one coming from Heroku 'PORT': 3306 } } this is the top of Settings.py import os import django_heroku import dj_database_url from decouple import config i also changed the allowed hosts ALLOWED_HOSTS = ['.herokuapp.com'] thanks … -
Uncaught SyntaxError: Unexpected token " " is not valid JSON at JSON.parse (<anonymous>) when working with django
I am working on a Django chat application whereby I am using websockets and transferring JSON data. I have however encoutered some errors which are making it difficult for me to proceed. The error states Uncaught SyntaxError: Unexpected token 'T', "Thanks for"... is not valid JSON at JSON.parse (<anonymous>) at ws.onmessage Here is part of my consumers.py which is handling the connection: def websocket_receive(self, event): print(f'[{self.channel_name}] - Recieved message - {event["text"]}') msg = json.dumps({ 'text': event.get('text'), 'username': self.scope['user'].username }) self.store_message(event.get('text')) async_to_sync(self.channel_layer.group_send)( self.room_name, { 'type': 'websocket.message', 'text': msg } ) def websocket_message(self, event): print(f'[{self.channel_name}] - Message sent - {event["text"]}') self.send({ 'type': 'websocket.send', 'text': event.get('text') }) And here is my javascript: ws.onmessage = function(event) { console.log(event); console.log("Message is received"); const ul = document.getElementById('message-list') var li = document.createElement('li') var data = JSON.parse(event.data); // var data = event.data; li.append(document.createTextNode( '[' + data.username + ']:' + data.text )) ul.append(li); } The code above is my original code. After going through similar previous errors, I noticed one comment saying that it is because the data is already in json format. However, when I replace var data = JSON.parse(event.data); with var data = event.data; I do not get the same error above, but instead the returned data … -
Django RequestFactory; TypeError: get() missing 1 required positional argument;
In attempting to test the context of a view PostedQuestionPage with RequestFactory, the following error is being raised when running the test: File "C:\Users\..\django\test\testcases.py", line 1201, in setUpClass cls.setUpTestData() Fi..\posts\test\test_views.py", line 334, in setUpTestData cls.view = PostedQuestionPage.as_view()(request) File "C:\..\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\..\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) TypeError: get() missing 1 required positional argument: 'question_id' It's unclear to me as to why the error is being raised while question_id is being passed into reverse("posts:question", kwargs={'question_id': 1})? test_views.py class TestQuestionIPAddressHit(TestCase): '''Verify that a page hit is recorded from a user of a given IP address on a posted question.''' @classmethod def setUpTestData(cls): user_author = get_user_model().objects.create_user("ItsNotYou") user_me = get_user_model().objects.create_user("ItsMe") author_profile = Profile.objects.create(user=user_author) user_me = Profile.objects.create(user=user_me) question = Question.objects.create( title="Blah blahhhhhhhhh blahhh I'm bord blah blah zzzzzzzzzzzzz", body="This is zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz...zzzzz", profile=author_profile ) authenticated_user = user_me.user request = RequestFactory().get( reverse("posts:question", kwargs={"question_id": 1}), headers={ "REMOTE_ADDR": "IP Address here" } ) request.user = authenticated_user cls.view = PostedQuestionPage.as_view()(request) views.py class PostedQuestionPage(Page): template_name = "posts/question.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['answer_form'] = AnswerForm return context def get(self, request, question_id): context = self.get_context_data() question = get_object_or_404(Question, id=question_id) if question.profile.user != request.user and not question.visible: raise Http404 context |= … -
Getting id for Custom Admin Actions
I want to get the id of a query set that is selected in the admin panel and want this custom action to redirect me to the url having the id in it. However I am not able to do so. admin.py: @admin.register(models.PurchaseItem) class PurchaseItemAdmin(admin.ModelAdmin): list_display = ( 'id', 'product', 'supplier', 'quantity') @admin.action(description='View Invoice') def get_context_data(self, request, query_set): return HttpResponseRedirect('/purchases/10/generatePDF') actions = [get_context_data] I want to be able to have any id instead of hardcoding '10' in the url to that when I select a query, I can use the custom command to redirect to its pdf page. -
Save django summer note as typing
I currently have a working install of django-summernote. What I am wondering, is does django offer the ability to have an event trigger when typing into the editor to save the post?