Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework Return List of all parents and their children
I have been going crazy searching for an answer. I have two tables (models) as follows: class DisplayPosts(models.Model): post_id = models.CharField(unique=True, max_length=300, blank=True, null=True) post_url = models.CharField(max_length=300, blank=True, null=True) class Observations(models.Model): post = models.ForeignKey(DisplayPosts, to_field="post_id", on_delete=models.DO_NOTHING, related_name='observations') created = models.DateTimeField(blank=True, null=True) I have created the following seriailzers: class ObservationsSerializer(serializers.ModelSerializer): class Meta: model = Observations fields = '__all__' class DisplayPlostsSerializer(serializers.ModelSerializer): observation = ObservationsSerializer(many=True, source='observations') class Meta: model = DisplayPosts fields = '__all__' I am trying to create a search API to retrieve a list of posts urls and their respective created dates (the relationship between DisplayPosts to Observations is one-to-many). When I retrieve a single post I get all the child observations, but when I try to pull a list based on search terms, the child list is empty. These are my views for single post v.s. list posts: @api_view(['GET', ]) @permission_classes((IsAuthenticated,)) def api_detail_posts(request, post_id): try: display_post = DisplayPosts.objects.get(post_id=post_id) except DisplayPosts.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == "GET": serializer = DisplayPlostsSerializer(display_post) return Response(serializer.data) class ApiPostListView(ListAPIView): queryset = DisplayPosts.objects.all() serializer_class = DisplayPlostsSerializer observaation_serializer_class = ObservationsSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) filter_backends = (SearchFilter, OrderingFilter) pagination_class = PageNumberPagination search_fields = ('post_id', 'post_url') I would appreciate any hints on how I can go about … -
How can I use Med7 and Negspacy simultaneously?
I'm trying to use med7 and negspacy from Spacy but they both need separate version of spacy. How can i use both in the same script? I'm using en_core_med7_lg from spacy to get disease, drug and other entities out of text import spacy import scispacy from spacy import displacy from spacy.matcher import PhraseMatcher from spacy.tokens import Span from negspacy.negation import Negex med7 = spacy.load("en_core_med7_lg") # create distinct colours for labels col_dict = {} seven_colours = ['#e6194B', '#3cb44b', '#ffe119', '#ffd8b1', '#f58231', '#f032e6', '#42d4f4'] for label, colour in zip(med7.pipe_labels['ner'], seven_colours): col_dict[label] = colour options = {'ents': med7.pipe_labels['ner'], 'colors':col_dict} negex = Negex(med7, ent_types=["DISEASE", "NEG_ENTITY"], name="negex", neg_termset={'pseudo_negations': ['no further', 'not able to be', 'not certain if', 'not certain whether', 'not necessarily', 'without any further', 'without difficulty', 'without further', 'might not', 'not only', 'no increase', 'no significant change', 'no change', 'no definite change', 'not extend', 'not cause', 'neither', 'nor'], 'preceding_negations': ['absence of', 'declined', 'denied', 'denies', 'denying', 'no sign of', 'no signs of', 'not', 'not demonstrate', 'symptoms atypical', 'doubt', 'negative for', 'no', 'versus', 'without', "doesn't", 'doesnt', "don't", 'dont', "didn't", 'didnt', "wasn't", 'wasnt', "weren't", 'werent', "isn't", 'isnt', "aren't", 'arent', 'cannot', "can't", 'cant', "couldn't", 'couldnt', 'never', 'neither', 'nor'], 'following_negations': ['declined', 'unlikely', 'was not', 'were not', "wasn't", 'wasnt', "weren't", … -
How do I get user input from search bar to display in a page? Django
Django is very challenging and I still need to get used to the code and currently, I just want the search bar to display every time a user input a text and it will display like a title I really don't how to interpret the code to tell that every time the user inputs in the search bar, It is supposed to display the user input on a page like a title. Example: user input in the search bar: cat and it displays cat title Display on the current page: Result search: "Cat" HTML Code <!-- Search Bar --> <form action="{% url 'enc:search' %}" method="GET"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search"> </form> In my views.py I only write this code and I don't know what to write it. views.py def search (request): title = request.GET.get("q", "") urls.py urlpatterns = [ path("", views.index, name="index"), path("search/", views.search, name="search"), Right now just a simple display from the search bar input later I will code it in a data search where there is some file to integrate the search but right now I really need some help my brain is cracking. It's kinda sad I mean I know it be a simple … -
Google Autocomplete with Modal Dialog HTML5
Been working with google's autocomplete for a project to use it to find establishments. However whenever I call for it, the pac container div is appended to the body of the html rather than the dialog tag of modal dialog. I have tried a lot of stuff, using promises, messing with focusing. However whenever the page is loaded or whenever you focus into the input box, the first iteration of loading the autocomplete sets the container to the body rather than the input box itself. I've tried also taking it out of the ready and placing it else where, doing a callback into the google url itself. However a simple timeout function does get rid of the pac container, but I would rather like to solve this issue without the use of one. Image of pac container when the dialog screen is loaded up Here is a sample of what my code looks like for the dialog. <dialog id="myDialog> <div class="modal-body"> <input id="searchbox" name="searchbox"/> </div> </dialog> <script> $(document).ready(function () { initAutocomplete(); }); </script> autocomplete.js function initAutocomplete() { const input = document.getElementById("searchbox"); const autocomplete = new google.maps.places.Autocomplete(input); autocomplete.addListener("place_changed", () => { var place = autocopmlete.getPlace(); /* Rest of the code*/ } … -
How to maintain authentication data
I am doing a Vue 3 practice together with Django Rest Framework, what I am trying to do is a token authentication validation, a user logs in, a token is going to be generated, but I run into a problem and it is that when at moment of logging in is done correctly and I am able to obtain the generated token, the problem is that when reloading the page the token is no longer in the vue application, a possible solution that I decided is to make the token save in local storage, but i think it is not the correct solution. This is my Login.vue: <template> <h2>login</h2> <form method="POST" @submit.prevent="sendData" autocomplete="off"> <input type="text" placeholder="Nombre de Usuario" v-model.trim="username" /> <input type="password" placeholder="Contraseña de Usuario" v-model.trim="password" /> <button type="submit">enviar</button> </form> </template> <script> import { ref } from '@vue/reactivity'; import { watchEffect } from '@vue/runtime-core'; export default { setup() { const username = ref(''); const password = ref(''); const token = ref(''); const sendData = () => { fetch(`http://localhost:8000/auth-token/`, { method: 'POST', body: JSON.stringify({ username: username.value, password: password.value, }), headers: { 'Content-Type': 'application/json', }, }) .then((res) => res.json()) .catch((error) => console.error('Error:', error)) .then((response) => { token.value = response.token; }); }; watchEffect(() … -
How to prevent Django caching querysets in memory in a ./manage.py command
I have a ./manage.py command that is made to run as a service in the background. However the memory usage goes up steadily and the script gets killed eventually. By using memory_profiler I found that the memory usage goes up after each query, especially after bulk_create(). I tried putting the results in a variable and setting it to None, also tried django.db.connection.close() after each iteration of the endless loop. Is there a way to tell Django not to cache those queries? -
Make Django Admin Commands run automatically in deployment (apache2)
I am creating an eCommerce site and want to delete rows of the order table after 20 days has passed. And I was successfully able to do that! My code... delete_old_orders.py from django.core.management.base import BaseCommand, CommandError from store.models import Order from datetime import datetime, timedelta class Command(BaseCommand): help = 'Delete objects older than 20 days' def handle(self, *args, **options): Order.objects.filter(order_date__lte=datetime.now()-timedelta(days=20)).delete() self.stdout.write('Deleted objects older than 10 days') In which, just for your information my file location goes as... store/ models.py management/ __init__.py commands/ __init__.py delete_old_orders.py tests.py views.py Every time in order to run it, I need to run the code python manage.py delete_old_orders in the terminal. However, this is in my local machine, when I want this to run every day at 2am in my server, which runs apache2 in Ubuntu. How should I deal with this? Should I alter my config file in the server? Any help would be much appreciated! Thanks! -
Translation from data in database
I implemented a logs system in my Django app, this system, for every action of any user will save informations in the database. Here is the model: class Log(models.Model): user = models.ForeignKey(to=User, on_delete=models.PROTECT) log = models.CharField(max_length=255) type = models.CharField(max_length=50) date = models.DateTimeField(auto_now_add=True) company = models.ForeignKey(to=Company, on_delete=models.PROTECT) My point is on the translation of the log field. For exemple my language is english, it will save in the database "did create a new customer", But if I change the language in french I will obviously get this in english again. Same if a french create a log I will have some logs in french others in english. My problem is there is hundreds of different possibilities for this log field. Is it a way with Django to translate data coming from the database in the templates like with a {% translate %} tag? I was thinking something like having these hundreds possibilities in the translation files and Django translate it directly in the templates? I do have the same problem with the permissions name. Users can give permissions to other users but these permission names are in english. Thanks for your help -
Django served on specific URL - relative urls corrupted
I've deployed my Django (DRF API) project on DigitalOcean apps. The path "/" is used by my static site that uses this API so I set route for this component to "/api" which works correctly. The problem: I go to /api/admin/ and it redirects me to /admin/login but the django is served on /api url so this URL is invalid. Do you know how to make this work? Is there a way to tell django to use absolute URL everywhere? -
Is possible to make unique a field in the database for a foreign key?
Lets suppose that I have two models named Company and Airplane: class Company(models.Model): name= models.CharField(max_length=250) location=models.Charfield(max_length=250) class Airplane(models.Model): company = models.ForeignKey(Company, on_delete=models.RESTRICT) number = models.IntegerField(unique=True) I want the number in Airplane model to be unique but just in the same company, an airplane from another company can have the same number. Is it that possible? -
Error 500 in djangoAPP deployed on microsoft AZUR
so i've tested my djangoApp locally and everything went fine, then i used microsoft Azur to deploy my App, many users were able to register but most of them got the error 500,i want to know what's could be the problem and how can i fix it? -
Stop python function call on page reload
I have a python function which is called by an onclick HTML event - <button name="get_key_btn" class="waves-effect waves-light btn" onclick="location.href='{% url 'getkey' %}'" method="GET">My Keys</button> Python function below - @login_required def get_key(request): """A view to return landing page keygen""" args = {} customer_name = request.user.username return render(request, 'landing.html', {'customer_name': customer_name}) The above get_key function is called each time the browser is refreshed, which is causing some difficulty. -
I want to turn a template on Django But Not Succeed
I want to create this [theme] with Django https://themeforest.net/item/skrollex-creative-one-page-parallax/11211962 Not showing any error here. But I think the Java script not working. -
access the values of this result, obtained from an api
GOOD, I have a problem, I am developing an application that consumes an api and returns the token, but obviously that token expires, I wanted to know some way to get the value of the access-toke, the truth is I don't know if this result is a json or simply a dictionary, disuclpar I am something newbie is this of programming, the thing is that I cannot access that value to store it in a variable because when the token expires, I have to raise everything again and paste the new generated token, all this is being developed with the request library and for the django backend class Token(object): def init(self, url, payload): self.url = url self.payload = payload headers = { 'Content-Type': 'application/x-www-form-urlencoded' } self.response = requests.request("POST", self.url, headers=headers, data=self.payload) if self.response.status_code == 200: print('Success!') elif self.response.status_code == 404: print('Not Found.') a = self.response.text print (a) def consulter_padron(self): url = "I delete this, they kick me out of work hahaha" payload={} headers = { 'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjVMcDByZ0xrNmJYS3RHZURzSmhMeS1xakFobyIsImtpZCI6IjVMcDByZ0xrNmJYS3RHZURzSmhMeS1xakFobyJ9.eyJjbGllbnRfaWQiOiJJbnRlcnB1YmxpY2EiLCJzY29wZSI6IkludGVycHVibGljYSIsInN1YiI6IjkzNDkyZmU2LWU1NTEtNDMwNy04ODdkLTQwODIxYmZhZmE2ZSIsImFtciI6WyJwYXNzd29yZCJdLCJhdXRoX3RpbWUiOjE2MTcyNzQyNTcsImlkcCI6Imlkc3J2IiwicHJlZmVycmVkX3VzZXJuYW1lIjoiQ29ycmFsZXMiLCJlbWFpbCI6Im5vbWFpbEBub21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOiJ0cnVlIiwicGhvbmVfbnVtYmVyIjoiNDQ0NDQ0NDQ0IiwicGhvbmVfbnVtYmVyX3ZlcmlmaWVkIjoidHJ1ZSIsIlVzdWFyaW8iOiI1MyIsIlNlcnZpZG9yIjoiMyIsIkRvbWluaW8iOiIyNyIsIkVudGlkYWQiOiI1MyIsInJvbGUiOlsiRG9tYWluIiwiSW50ZXJwdWJsaWNhIiwiUGFkcm9uIl0sImp0aSI6IjE5YTFlM2UzMWI3NDg5ZGM1ZjA2NTJhNjJlYTAzMGMyIiwiaXNzIjoiaHR0cHM6Ly9wcmUtaW50ZXJwdWJsaWNhYXV0aG9yaXphdGlvbi5pbnRlcnB1YmxpY2EuZXMvaWRlbnRpdHkiLCJhdWQiOiJodHRwczovL3ByZS1pbnRlcnB1YmxpY2FhdXRob3JpemF0aW9uLmludGVycHVibGljYS5lcy9pZGVudGl0eS9yZXNvdXJjZXMiLCJleHAiOjE2MTcyNzc4NTgsIm5iZiI6MTYxNzI3NDI1OH0.CbYFfMNHfaqjmtdDx6Bb3sfrzMBbWmi9p1-4xsYLQxOmigupwZqnHHopy5Ltu3mwWftNwvPj0Lx1bH5m1kI0wG0Y_zWqQ3N7UacZDtApfaoNpwOjygPWcZsHj83V2xdYKSPGBFjaDng_9TECBz4ANOlmbh7c0pklLu-nA_Od9E_wa2znq8CGv4sxIC4ViTeoEclMAq--sP2j1FNxZiFinq7dG32QV7zzR_1JJjVjtzK4eAT4CViZFhedsswn9OEn6wctJtmnDkRBnQioHSvz2wM5J-tngVS6tn_o1PUwVtykBc_0_TTfowiJkAkEmSQJKobAQPIgVvPrH4JsNeahGw' } self.response = requests.request("GET", url, headers=headers, data=payload) print (self.response.text) prueba01 = Token('I delete this, they kick me out of work hahaha') prueba01.consulter_padron() -
Run Dash inside Flask on a template
I started a prototype of a web app on Django using Dash for data visualization, but for comparison purpose I started doing it on Flask too. The main thing is, in Django we have django-plotly-dash that does the interface to connect Django and Dash. With that module, you can embed your Dash app on a single div on your page, which is exactly what I need since im using the website template for the design. I can't seem to find a way to do it in Flask, the only thing I was able to do so far was route it so i cant include it on the app, but on a different page, only with the Dash components. Can anyone help me on how to get the only the div from the Dash app and how to embed it on my base template? Thanks in advance! -
Python Django UNIQUE constraint failed problem
So I am using the Django REST Framework. I want to register a new user but I always get this "error": django.db.utils.IntegrityError: UNIQUE constraint failed: user_account.username Even if I haven't the user created yet I get this error. This is my model: class Account(AbstractBaseUser): ... username = models.CharField(max_length=50, unique=True) firstname = models.CharField(max_length=200) ... If I remove unique=True I won't get this error, but a username can exists like 5 times. That isn't what I want -
How I can delete a comment of post in django-rest?
I'm a newbie to Django and Django-rest. I've written a blog app using django. I want to delete a comment by comment owner and post owner.thanks in advance this is my comment and post model: class Post(models.Model): name = models.CharField(blank=True, max_length=60) caption = models.CharField(blank=True, max_length=280) status = models.CharField(blank=True, max_length=20) owner = models.ForeignKey(User, related_name='Post_owner', null=True, on_delete=models.CASCADE) created_at = models.TimeField(auto_now_add=True) multimedia = models.ManyToManyField(Media, related_name='Post', blank=True) class Comment(models.Model): context = models.CharField(blank=True, max_length=280) author = models.ForeignKey(User, related_name='comment_author', null=True, on_delete=models.CASCADE) created_at = models.TimeField(auto_now_add=True) post = models.ForeignKey(Post, related_name='comments', null=True, on_delete=models.CASCADE) this is my serilaizers class CommentSerializer(serializers.ModelSerializer): class Meta: model = models.Comment fields = ('id','context', 'author','created_at', 'post') class PostSerializer(serializers.ModelSerializer): multimedia = PostMediaSerializer(many=True, read_only=True, required=False) comments = CommentSerializer(many=True, read_only=True) class Meta: model = models.Post fields = ('name', 'caption', 'status', 'owner', 'created_at', 'multimedia','comments') and this is my view class to insert a comment: class CreateCommentView(generics.RetrieveUpdateDestroyAPIView): queryset = Comment.objects.all() permission_classes = (IsAuthenticated,) serializer_class = post_serializer.CommentSerializer def put(self, request, pk=None): user = request.user data = request.data data['author'] = user.email data['post'] = pk serializer = self.get_serializer(data=data) if not serializer.is_valid(True): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response("comment created!", status=status.HTTP_202_ACCEPTED) -
how can I display the content of the page I am viewing on users' screens
i'm working on personnal project that have as optionthat allow the administrator to display the content of his curent page to the other user's in order to pilote a vote process.Thanks -
Django: user login system is not working in the same page with user registration
I'm new to Django and trying to make a user registration and login system in same HTML page. My user registration part is working but login part is not. So, my views.py is in the below, def index(request): if request.method == "POST": if request.POST.get('submit') == 'Kayıt Ol': username= request.POST['username'] email= request.POST['email'] password= request.POST['password'] if User.objects.filter(username=username).exists(): messages.info(request,'Bu kullanıcı adı kullanılıyor') return redirect('/') elif User.objects.filter(email=email).exists(): messages.info(request,'Bu email kullanılıyor.') return redirect('/') else: user = User.objects.create_user(username=username, email=email, password=password) user.save() return redirect('/') else: return render(request, 'blog/SignPage.html') elif request.POST.get('submit') == 'Oturum Aç': username= request.POST.get('username') password= request.POST.get('password') user= auth.authenticate(username=username,password=password) if user is not None: auth.signin(request,user) redirect('/anasayfa') else : messages.info(request,'Yanlış kullanıcı adı veya şifre') return redirect('/') else: return render(request, 'blog/SignPage.html') Also my urls.py is, urlpatterns = [ path('', views.index, name='kaydol'), ] -
Why getting a 403 error on plesk trying to run Django
Been following a tutorial on udemy for python, and atm im suppose to get a django app deployed. Since I already had a vps, I didnt go with the solution on the tutorial using google cloud, so tried to configure the app on my vps, which is also running plesk. Followed the tutorial at https://www.plesk.com/blog/tag/django-plesk/ to the letter the best I could, but keep getting the 403 error. httpdocs -djangoProject ---djangoProject ------asgi.py ------__init__.py ------settings.py ------urls.py ------wsgi.py ---manage.py -passenger_wsgi.py -python-app-venv -tmp passenger_wsgi.py: import sys, os ApplicationDirectory = 'djangoProject' ApplicationName = 'djangoProject' VirtualEnvDirectory = 'python-app-venv' VirtualEnv = os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin', 'python') if sys.executable != VirtualEnv: os.execl(VirtualEnv, VirtualEnv, *sys.argv) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory)) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory, ApplicationName)) sys.path.insert(0, os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin')) os.chdir(os.path.join(os.getcwd(), ApplicationDirectory)) os.environ.setdefault('DJANGO_SETTINGS_MODULE', ApplicationName + '.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() passenger is enabled in "Tools & Settngs > Apache Web Server" in "Websites & Domains > Domain > Hosting & DNS > Apache & nginx settings" I've got: "Additional directives for HTTP" and "Additional directives for HTTPS" both with: PassengerEnabled On PassengerAppType wsgi PassengerStartupFile passenger_wsgi.py and nginx proxy mode marked "Reverse Proxy Server (nginx)" is also running No idea what else I can give to aid in getting a solution, … -
how to make a django bootstrap breadcrumbs
how do I create dynamically a django bootstrap breadcrumb like that : home > category > product > product_detail ? I've tried using documentation but can't implement it . this is my_project urls : from django.contrib import admin from django.urls import path , include urlpatterns = [ path('accounts/' , include('accounts.urls') ), path('' , include('products.urls' ) ), this is my_app urls : from django.urls import path from . import views urlpatterns = [ path('' , views.index , name='index' ), ] urlpatterns += [ path('category_1' , views.category_1, name='category_1' ), path('category_2' , views.category_2, name='category_2' ), path('category_3' , views.category_3, name='category_3' ), path('product_detail /<str:product_title>/' , views.product_detail , name='product_detail '), ] this my views : from django.shortcuts import render , get_object_or_404 from .models import category , product def index(requset): category = category .objects.all() category_1= product.objects.filter(category=category[0]) category_2= product.objects.filter(category=category[1]) category_3= product.objects.filter(category=category[2]) context = { 'category_1':category_1, 'category_2':category_2, 'category_3':category_3, } return render(requset, "products/index.html", context) def product_detail (requset ,product_title): all_products = product.objects.filter(product_title = product_title) context ={ 'all_products':all_products , } return render( requset,'products/product_detail .html',context) -
How can I hide fields in auto-generated schemas, or define schemas explicitly?
I am using drf-yasg (Django REST Framework - Yet Another Swagger Generator) to generate docs for my RESTful API, but it's not doing exactly what I want. I thought that setting read_only and write_only attributes to True would hide fields from the documentation as they are omitted from request and response bodies, but this is not the case. I don't see any examples of defining schemas within a decorator, or even just hiding a field, but if I can learn how to do one of those things, I'll be in good shape. Let's go with a basic example: user login. # serializers.py class TokensSerializer(serializers.Serializer): """ Serializes access and refresh tokens for responses to a logged-in user. """ username = serializers.CharField(max_length=64, write_only=True) access = serializers.CharField(max_length=4096, read_only=True) refresh = serializers.CharField(max_length=4096, read_only=True) # ... class LoginSerializer(serializers.ModelSerializer): """ Serializes username, email, password, and tokens to allow for logging in. """ class Meta(): model = User fields = ['username', 'email', 'password', 'tokens'] username = serializers.CharField(max_length=64) email = serializers.CharField(max_length=254, read_only=True) password = serializers.CharField( min_length=8, max_length=64, write_only=True) tokens = TokensSerializer(read_only=True) # ... These serializers generate Tokens and Login models respectively, which are defined in the following .json and .yaml formats: { "definitions": { "Tokens": { "required": ["username"], … -
Expecting value: line 1 column 1 (char 0) (django)
hello I am getting this error and I don't know how to solve it please help this is my traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/cart/update/ Django Version: 3.1.6 Python Version: 3.6.8 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'billing', 'accounts', 'products', 'orders', 'search', 'tags', 'carts', 'addresses'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "c:\python36\lib\json\decoder.py", line 355, in raw_decode obj, end = self.scan_once(s, idx) During handling of the above exception (0), another exception occurred: File "C:\Users\daghe\Dev\ecommerce - Backup\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\daghe\Dev\ecommerce - Backup\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\daghe\Dev\ecommerce - Backup\src\carts\views.py", line 28, in updateItem data = json.loads(request.body) File "c:\python36\lib\json\__init__.py", line 354, in loads return _default_decoder.decode(s) File "c:\python36\lib\json\decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "c:\python36\lib\json\decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None Exception Type: JSONDecodeError at /cart/update/ Exception Value: Expecting value: line 1 column 1 (char 0) and this is my view def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items':items, 'order':order, 'cartItems':cartItems} return render(request, 'carts/home.html', context) def updateItem(request): data = json.loads(request.body) … -
WebRTC Peer to Server instead of Peer To Peer
WebRTC Peer to Server instead of Peer To Peer I want to build a WebRTC Video and Voice Calling App. However, I do not want a user to be able to connect directly to another user, as this brings unwanted security risks. So I think it makes more sense to implement the whole thing in such a way that all users (2 in this case) connect to a server, which then distributes the data and the users do not distribute it among themselves, so that, for example, the IP is publicly visible. I don't want that: So even I think this is the normal way you could do it I don't want to, because, how I said there are a lot of security risks that this kind of connection brings with it. I want that: I've heard that Discord, for example, does exactly what I show in the graphic (at least similarly). Can this be implemented? And if so, how? By the way, I used Python Django in the backend. I was wondering whether this could also be done with Python Django Channels. So is there an implementation in Django Channels that I can set up a WebRTC server? Many … -
Django filefield.open() accesses local storage instead of remote storage during data migration. Why?
Using Django 2.2 and python 3.7, deployed on Heroku I have a model with a filefield with a flexible storage location, depending on app environment (local filesystem in dev, S3 in production). We need the file upload model to do more stuff, and we're approaching it by create the new model use a data migration to copy data from the old model to the new one delete the old model The data migration works great in local (with local filesystem storage), but fails on a Heroku test server (where the files are stored in an S3 bucket). I get an error message like so: FileNotFoundError: [Errno 2] No such file or directory: '/app/private/recalls/user_74/PDIR_BBUY__9e8c995f-512f-446a-9e99-e95f0de1a4ff.pdf' Relevant code is below Existing "old" model: from django.db import models from myapp.storage_backends import storages_location, upload_file_rename class OldUpload(models.Model): recall_file = models.FileField( validators=[FileExtensionValidator(allowed_extensions=['pdf'], message=RECALL_FILE_EXTENSION_MESSAGE)], storage=storages_location(), upload_to=recall_file_rename ) myapp.storage_backends (based on Local filesystem as a remote storage in Django): import os import uuid from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings from django.core.files.storage import FileSystemStorage, get_storage_class class PrivateS3MediaStorage(S3Boto3Storage): location = settings.PRIVATE_MEDIA_LOCATION default_acl = 'private' file_overwrite = True custom_domain = False bucket_name = settings.AWS_MEDIA_BUCKET_NAME class PrivateFileSystemStorage(FileSystemStorage): location = os.path.join(settings.MEDIA_ROOT, settings.PRIVATE_MEDIA_LOCATION) def storages_location(): media_storage = None if settings.SITE_NAME == 'LOCAL': base_url …