Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is this if statement not working in Django?
I'm just trying to run an if statement in html using django in the {% %} things. The statemnet is {% if listing in watchlist %}. Even though the listing is in watchlists, it doesn't make the if statement true. I used {{ }} to see what watchlist and listing are. for {{ watchlist }} I got: <QuerySet [<Watchlists: 15: Dan1308 has added 3: The Bus (yes the cool airplane), starting at 3000 to watchlist>]> for {{ listing }} I got: 3: The Bus (yes the cool airplane), starting at 3000 here's my views.py: def listing(request, NewListings_id): user = request.user listing = NewListings.objects.get(pk=NewListings_id) comments = Comments.objects.filter(listing=listing) watchlist = Watchlists.objects.filter(user=user) return render(request, "auctions/listing.html", { "listing": listing, "comments": comments, "user": user, "watchlist": watchlist }) and here's my models.py: class Watchlists(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) listing = models.ForeignKey(NewListings, on_delete=models.CASCADE) def __str__(self): return f"{self.id}: {self.user} has added {self.listing} to watchlist" So, why is it not working? -
Unable to display JsonResponse in Django web project
I am working on a django project. I want to display the result of a query with JsonResponse, but I can only get the raw data, rather than the colourful Json response. Here is my code views.py from django.shortcuts import render from django.db import connection from django.http import JsonResponse import json # Create your views here. def index(request): return render(request, 'AppTPCC/index.html') def result(request): search_string = request.GET.get('name', '') query = 'SELECT * FROM item WHERE i_name ~ \'%s\'' % (search_string) c = connection.cursor() c.execute(query) results = c.fetchall() result_dict = {'records': results} return render(request, 'AppTPCC/result.html', result_dict) def query(request): query = """ SELECT w.w_country, SUM(s.s_qty) FROM warehouse w, stock s, item i WHERE i.i_name = 'Aspirin' AND i.i_id = s.i_id AND w.w_id = s.w_id GROUP BY w.w_country; """ c = connection.cursor() c.execute(query) results = c.fetchall() return JsonResponse(results, safe=False) urls.py from django.urls import path, re_path, include from . import views urlpatterns = [ re_path(r'^$', views.index), re_path(r'result', views.result), re_path(r'query', views.query, name='query'), ] Then when I type http://127.0.0.1:8000/AppTPCC/query in my browser, I can only get the raw data type. I am wondering how to solve this. Thanks in advance. -
Django how to get a user and send him through a form
I need to grab a logged in user and send it to the database. model user is ForeignKey and I need to join the logged sessions. this doesn't work don't overwrite it: if request.method == 'POST': form = Inzeratform(request.POST, instance=request.user) if form.is_valid(): post = form.save(commit=False) post.user = request.user.get_username() -
object not being saved on database while using Ajax on django
I have this form that uses ajax on post method when saving new todo object on database and it works fine. When I add new entry on the form, it is being saved on the database and displays the new entry on the end user. However, I made a code that whenever I clicked those tasks below(the whole div), (Grocery, eat snack, etc see the picture for reference), the object's completed attribute should be True(it means the end user is done doing the task) and the texts should have a line-through on it. But, the completed attribute of each tasks listed below is not being saved as True on the database after every time I add a new entry and click the tasks, it only adds a line-through style on text, It will only be saved when I refresh the page and then click on those tasks again. in short: working: adding new entry, it displays new entry on end user without refreshing the page not working: clicking the task to make the completed attribute True after adding new entry. it only adds line-through style on each texts. (This will work ONLY if I refresh the page and then click … -
Nested writable serializer to process flattened normalized request data
I have a nested writable serializer. class GamerSerializer(serializers.ModelSerializer): account= AccountSerializer() document = DocumentSerializer() class Meta: model = Gamer fields = [ 'chosen_game', 'gamer_experience' ] This serializers is supposed to create Account object, a Gamer object related to Account as well as Document object related to Gamer. By default the nested serializer always accepts nested objects as data like this: serializer = self.get_serializer(data= { account: {...acount}, document: {...document}, chosen_game: "Minecraft", "gamer_experience": "1 year" } ) but I want the serializer to accept normalized flattened data( we assume that names of the model attributes do not overlap). Like this : serializer = self.get_serializer(data= { account_name: '', account_type:'', document_name: '', document_file: '', chosen_game: "Minecraft", "gamer_experience": "1 year" }) How can I achieve this result ? -
Post method Forbidden (CSRF cookie not set.)
I am trying to create new post from react frontend and I am getting this error. Forbidden (CSRF cookie not set.): /blog/create/ # views.py class CreatePost(CreateAPIView): permission_classes = (permissions.AllowAny, ) queryset = BlogPost.objects.all() serializer_class = BlogCreateSerializer # urls.py path('create/', CreatePost.as_view()), But when I tested my api with Postman, it created the new post without any problem. I already tried other provided answers from stackoverflow but no luck. -
ebay python SDK with django - config file not found when addietm function is called through views.py, works otherwise
I'm building a django project where, in my views.py, I'm trying to call a function from another .py file in the same directory, which makes an api call to ebay. When I run the function inside the .py file, it works fine, but when I call it from my views.py, I get this error: 'config file ebay.yaml not found. Set config_file=None for use without YAML config.' I don't understand why this only happens when I call it from views.py? The ebay.yaml file is in the same directory as both these files. views.py from django.http import HttpResponse from django.shortcuts import render import sys from djangonautic.forms import HomeForm import _sqlite3 import os.path from djangonautic import additem #this is the file that has the function def homepage(request): if request.method == "POST": form = HomeForm(request.POST) if form.is_valid(): print("Form was valid") text = form.cleaned_data['post'] config_for_ebay = 'ebay.yaml' #config file to make api call resp_object = additem.make_api_call(text, config_file=config_for_ebay) args = {'form': form, 'text': text} context = {'title': resp_object} return render(request, "script_run.html", context=context) else: print("ewe") form = HomeForm() return render(request, "homepage.html", {'form': form, 'text': 'bla'}) additem.py from ebaysdk.trading import Connection from djangonautic import api_formatting_for_raw_html from djangonautic import get_categories #var_pics = {'Color': [x[1] for x in variations]} def … -
How to join Objects in Django with Foreign Keys 2 tables deep
I have 2 models each with foreign keys to 2 tables. I'm trying to join the 1st table to the 3rd. Here are my models: Model 1: class AppBillingBil(models.Model): id_bil = models.AutoField(primary_key=True) idtrp_bil = models.ForeignKey(AppTradingPartnerTrp, models.DO_NOTHING, db_column='idtrp_bil', blank=True, null=True) idcst_bil = models.ForeignKey(AppCustomerCst, models.DO_NOTHING, db_column='idcst_bil') idbtp_bil = models.ForeignKey(AppBillingTypeBtp, models.DO_NOTHING, db_column='idbtp_bil') class Meta: db_table = 'app_billing_bil' ordering = ['id_bil'] Model 2: class AppCustomerCst(models.Model): id_cst = models.AutoField(primary_key=True) is_active_cst = models.BooleanField() name_cst = models.CharField(max_length=50, blank=True, null=True) Model 2: class AppTradingPartnerTrp(models.Model): id_trp = models.AutoField(primary_key=True) tpid_trp = models.CharField('TPID', max_length=50, blank=True, null=True) name_trp = models.CharField('Name', max_length=50) Final Model Needed: class AppCustomerTpRel(models.Model): id_rel = models.AutoField(primary_key=True) idcst_rel = models.ForeignKey(AppCustomerCst, models.DO_NOTHING, db_column='idcst_rel') idtrp_rel = models.ForeignKey(AppTradingPartnerTrp, models.DO_NOTHING, db_column='idtrp_rel') cust_vendor_rel = models.CharField(max_length=50, blank=True, null=True) I need to join on the following criteria: idtrp_bil__id_trp = idtrp_rel idcst_bil__id_cst = idcst_rel And I need to be able to use the cust_vendor_rel field from AppCustomerTpRel in a filter query on AppBillingBil -
django-cors-header problem with authorization cookies
I am using Django base authorization to protect specific routes of my API (using @login_required decorator), and Insomnia to test them out. Using Insomnia I can login using my ```api/auth`` route and then access to every protected route of my APIs. The problem comes with React: I have my React app running on localhost:3000 and my Django APIs on localhost:8000. When I log in though the login page (made with react and react-router-dom) it just works. But after that, if I open the HomePage (which fetches data from a login_required route) I get a 404 response ( which is caused by @login_required ). I tought that the problem was because of fetch and cookies, But I can't figure out a way to solve it. It seems like Insomnia automatcally stores the cookie returned by api/login but the same doesn't happen with react. I've also already tried to set credentials to include and same-origin in my login fetch. Did someone already experienced this problem? MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] ... MIDDLEWARE_CLASSES = ( 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware' ) CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', ] CORS_ORIGIN_REGEX_WHITELIST = [ 'http://localhost:3000', ] -
How to Dynamically adding a form to a Django formset with jQuery
I want to automatically add new forms to a Django formset using jQuery, so that when the user clicks an "add" button it runs jQuery that adds a new form to the page. Django Template: {% extends 'base/base.html' %} {% load static %} {% block content %} <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script> $('#add_more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> <div class="card"> <form class="form-horizontal" action="" method="post"> {% csrf_token %} <div class="card-header"> <strong class="icon-book"> User Academic Information</strong> <hr class="divider" /> </div> <div class="card-body"> <div class="card-body"> <div class="form-horizontal"> {{ employAcademicFormSet.management_form }} <div id="form_set"> {% for form in employAcademicFormSet %} {% for field in form.visible_fields %} <div class="form-group row"> <label class="col-md-3 col-form-label" for="text-input"><h6>{{ field.label_tag }}</h6></label> <div class="col-md-9">{{ field }}</div> </div> {% endfor %} {% endfor %} <div class="form-group row"> <label class="col-md-3 col-form-label" for="text-input"> </label> <input class="ml-2" type="button" value="Add More" id="add_more"> </div> </div> </div> </div> </div> <div class="card-footer"> <button class="btn btn-lg btn-primary" type="submit">Submit</button> </div> </form> </div> {% endblock %} Please help me for solve the problem... -
ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 6379) WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:56602]
Here, I need to connect another channel using web sockets in django channels. I can't connect to the another channel, it showing error like this. Can anybody please help me, I just attched my code below, kindly go through it consumers.py import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) routing.py*(In django project)* from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) routing.py*(In chat app)* from django.urls import re_path from .consumers import ChatConsumer websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$',ChatConsumer), ] views.py from django.shortcuts import render def index(request): return render(request, 'chat/index.html') def room(request, room_name): return render(request, 'chat/room.html', { 'room_name': room_name }) urls.py*(In chat App)* from django.contrib import admin … -
Enter a valid date/time in django
Everytime I select date and time, django form throws "Enter a valid date/time" error. models.py class Quiz(models.Model): .... Ending_Time = models.DateTimeField(null=True) .... forms.py class QuizForm(forms.Form): .... closing_time = forms.DateTimeField(widget=forms.DateTimeInput(attrs={'class':'form-control form-control-lg','type':'datetime-local'})) .... views.py def createquiz(request): if request.method == "POST": form = QuizForm(request.POST) if form.is_valid(): quiz_text = form.cleaned_data['desc'] closingtime = form.cleaned_data['closing_time'] newquiz = Quiz(Description=quiz_text, Ending_Time=closingtime) newquiz.save() return HttpResponseRedirect(reverse('createques')) else: form = QuizForm() return render(request, "quiz/createquiz.html", {'form': form}) -
Creating a single API with models which dont have direct relationship with each other
I have these 3 models. Among these 3 models, Flightdetails and Passenger are in relationship with the third model Booking. But the 1st and the 2nd model doesnt have any relationship. And in the frontend I have a form like that for the booking. What I want to do is create an POST API from passenger model where user can submit the passenger's info and it is booked. BUt what my senior is demanding is that in the same post api, I should also have the flight id( primary key) request, so that when I submit the form or book, it (the object) should also have its own flight id. I hope I explained well. class FlightDetails(models.Model): Flight_Name = models.CharField(max_length=200) Aircraft_name = models.CharField(max_length=200) Destination = models.CharField(max_length=200, verbose_name = "To") def __str__(self): # return self.Flight_Number return 'Flight({})'.format(self.id) class Passenger(models.Model): First_name = models.CharField(max_length=200, unique=True) Last_name = models.CharField(max_length=200, unique=True) Gender = models.CharField(max_length=50) Nationality = models.CharField(max_length=200, unique=True) Passport_No = models.CharField(max_length=200, unique=True) Passport_Exp_Date = models.DateField(blank=False) Contact_Number = PhoneField(help_text='Contact phone number') Email = models.EmailField(max_length=200, unique=True) # Customer_id = models.CharField(max_length=50) def __str__(self): return (self.First_name, self.Contact_Number) class Booking(models.Model): # Book_Id = models.CharField(max_length=50) flight_number = models.OneToOneField(FlightDetails, on_delete = models.CASCADE) Booking_Date = models.DateField(default= True, verbose_name = "Booking Date(dd/mm/yy)") customer_name_and_phone = … -
Deploy Django 1.7 application to Apache2 with WSGI
I am trying to deploy an old Django application (1.7) to the Apache2 server on Debian. I am finally able to run the app with ./manage.py runserver but I had no success in getting the mod-wsgi working. I've never wrote a server side application in Python so please forgive me if I am missing something obvious. These are the steps I followed Everything I tried is with /usr/bin/python which is 2.7 - I know, I should be using virtuelenv but I didn't want to add even more complexity to the while thing (since I am not familiar with it) installed mod-wsgi with apt-get install libapache2-mod-wsgi Add following config to the /etc/apache2/mods-enabled/wsgi.conf Apache2 restart <IfModule mod_wsgi.c> WSGIScriptAlias / /home/rosasystem.pl/public_html/rosasystem/rosasystem/wsgi.py WSGIPythonHome /usr/bin/python WSGIPythonPath /home/rosasystem.pl/public_html/rosasystem LogLevel warn <Directory /home/rosasystem.pl/public_html/rosasystem/rosasystem> <Files wsgi.py> Order deny,allow Require all granted </Files> </Directory> </IfModule> Since then, I keep getting this error message in the error.log - most of the stuff I've googled suggest that there is a Python version discrepancy between mod-wsgi and system/virtualenv Python version which in this doesn't make sense because everything is Python 2.7. [Tue Oct 06 15:13:42.946626 2020] [mpm_event:notice] [pid 17059:tid 139874785088640] AH00489: Apache/2.4.38 (Debian) mod_fcgid/2.3.9 OpenSSL/1.1.1g mod_wsgi/4.6.5 Python/2.7 configured -- resuming normal operations … -
Django Project error repormissingimports , could not be resolved
Now I'm working on main project's root urls.py file in the configuration directory my_blog, and want to import views.py file from user app, but when i can't user app in main urls file and when trying to import like;from users importenter image description here views as user_views, its showing an error -
Django and windows Server 2012
I have developed a Django project and I want to host my website on a server which has Operating System: Microsoft Server 2012 R2 . I am new to Django and kind of lost where is to start.Can anyone provide me step by step direction? -
django.core.exceptions.ImproperlyConfigured:while generating fake data
##its Models.py## from django.db import models from random import * from django_faker import Faker # Create your models here. class Blore_jobs(models.Model): date=models.DateField() company=models.CharField(max_length=100) title=models.CharField(max_length=30) eligibility=models.CharField(max_length=30) email=models.CharField(max_length=50) phone=models.IntegerField() # @classmethod # def get_or_create(cls, date, company, title, eligibility, email, phone): # pass class populator(): # from portal.models import * # import os # os.environ.setdefault('DJANGO_SETTINGS_MODULE','Jobs.settings') # import django # django.setup() def generate(self,n): fek = Faker.getPopulator() for i in range(50): fdate = fek.date() fcompany = fek.company() ftitle = fek.random.choice(('TeamLead', 'Developer', 'Tester', 'Manager')) feligibility = fek.random.choice(('Btech', 'Mtech', 'Math')) faddress = fek.address() fmail = fek.email() def indian_phone(self): fek = Faker.getPopulator() first = fek.random.randint(7, 9) last = '' for i in range(9): last = last + str(fek.random.randint(0, 9)) return int(str(first) + last) fphone = indian_phone(self) # to add fake data to db Blore = Blore_jobs.get_or_create(date=fdate, company=fcompany, title=ftitle, eligibility=feligibility,email=fmail, phone=fphone) generate(50) I cant able to add fake data to Blore_jobs Db i am getting error like: Traceback (most recent call last): File "models.py", line 7, in <module> class Blore_jobs(models.Model): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/apps/registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/conf/__init__.py", line 64, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: … -
Comments not visible in template even though they are saved in the database
I currently have 2 models in my App, one for uploaded files and another one for comments. I've figured out how to implement the forms on the same page and it seems to be working but for some reason, the submitted comments aren't being shown and I have no idea on how to accomplish that. Should I provide the comments in a return or seeing as that there is a ForeignKey in the Comment model this is not neccesary and the comments can be accessed through each file? # Model for all uploaded files class Uploaded(models.Model): objects: models.Manager() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="users") time_uploaded = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=100) file = models.FileField(upload_to=MEDIA_ROOT) admintags = TaggableManager(blank=True, through=AdminTagsAll, verbose_name="Admin Tags") usertags = TaggableManager(through=UserTagsAll, verbose_name="User Tags") additional_description = models.CharField(max_length=50, blank=True) def __str__(self): return f"{self.description} {self.file}" # Model for comments class Comment(models.Model): objects: models.Manager() file = models.ForeignKey('Uploaded', on_delete=models.CASCADE, related_name='comments') text = models.TextField() def __str__(self): return self.text HTML template: {% for comment in comments %} <div style="border:1px solid silver; border-radius:15px; padding:15px; margin:10px 0px;"> <p class="mb-auto" style="font-size:15px;">{{ comment.text }}</p> </div> {% empty %} <div style="border:1px solid silver; border-radius:15px; padding:15px; margin:10px 0px;"> <p class="mb-auto" style="font-size:15px;">No Comments</p> </div> {% endfor %} Views.py def index(request): url_parameter = request.GET.get("q") user … -
Django Custom User UUID Duplicated (cached?)
I'm Using Django with a custom user model with custom UUID and custom user manager: class CustomUser(AbstractUser): id = models.UUIDField(primary_key=True, default=generate_id(), editable=False) # ... As you can see, I'm NOT using default=uuid4(). Instead I've made a function my on my own that uses uuid() to generate the custom id also using the timestamp: from datetime import datetime as dt from uuid import uuid1, uuid3, uuid4 def generate_id(): timestamp = str(dt.timestamp(dt.now())) return uuid3(uuid4(),timestamp) Now if I open the interactive shell: python manage.py shell and I call my function several time, this is what I get: >>> generate_id() UUID('bd8279f1-9b4b-3d7d-8932-f9e725f17045') >>> generate_id() UUID('0c2ec2ad-b062-3915-a9e9-22842c6f5ea2') >>> generate_id() UUID('2289202b-f252-3b27-bcae-cd44825bf4e0') >>> generate_id() UUID('88676ea9-4902-36ac-857d-929cb133089c') >>> generate_id() UUID('4a18b33e-12f0-3803-8ff0-0c4f0d1c849c') but when I try creating 2 users: from users.models import CustomUser >>> one = CustomUser.objects.create_user(email='hhh@jaja.com',password='JJlsaks16112') >>> two = CustomUser.objects.create_user(email='ttth@jija.com',password='JJlsaks16112') Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/usr/local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.IntegrityError: (1062, "Duplicate entry 'b448f583acfb31b7955926689b60f28a' for key 'PRIMARY'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File … -
How to set backgroundcolor and border for each array element using javascript or jquery?
I am trying to set separate background and border for each element in the array using JavaScript something like this. Until now what I have done outputis below. As I add a new element to the array, it will stretch the background. let skills = []; function displayname() { console.log(document.getElementById("namehere").value); x = document.getElementById("namehere").value; skills.push(x); console.log(skills) document.getElementById("skill-set").innerHTML = skills document.getElementById("skill-set").style.border = "1px solid blue"; document.getElementById("skill-set").style.backgroundColor = "yellow"; document.getElementById("skill-set").style.padding = "5px"; document.getElementById("skill-set").style.display = "inline-block"; document.getElementById('namehere').value = " "; } <label>Enter the skills: </label><br> <input type=t ext id="namehere" onchange="displayname()"> <div id="skill-set"></div> -
Django CORS Headers not Working as Suggested in Docs
The DOCS for Django Cors Headers, https://pypi.org/project/django-cors-headers/ , clearly states that "CORS_ALLOWED_ORIGINS: Previously this setting was called CORS_ORIGIN_WHITELIST, which still works as an alias, with the new name taking precedence." From the code if I use CORS_ORIGIN_WHITELIST my requests go through, but if I use CORS_ALLOWED_ORIGINS, while commenting out CORS_ORIGIN_WHITELIST, my requests are blocked. In my options request I am not getting any response and the subsequent POST request is blocked. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #APPS .... #ADDL FRAMEWORKS 'corsheaders', 'rest_framework', 'oauth2_provider', 'django_extensions', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = [ 'http://127.0.0.1:3000', 'http://localhost:3000' ] # CORS_ALLOWED_ORIGINS = [ # 'http://127.0.0.1:3000', # 'http://localhost:3000', # ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] -
How to display related attribute and values properly with ajax?
Here based on the class selected I want to display it's related attributes on the select option with ajax and jquery(it works fine) and on the side of select option there is a input field for attribute's related values(here is the problem only while displaying in the template with ajax, in the view it is printing the related values). Below is my ajax call and there is a problem while displaying attributes related values in the side of the attribute select option. After selecting class it displays related attributes correctly but the related attribute's related values are not displaying. The error is Uncaught ReferenceError: Attributes is not defined at HTMLSelectElement.onchange views.py class_id = request.POST.get('class_id') qs = VariantAttribute.objects.filter(class=class_id) attribute_data = [] attribute_data_values = [] for obj in qs: attribute_data.append(obj.attribute) attribute_data_values.append(obj.attribute.attributevalues_set.all()) data = serializers.serialize('json', attribute_data) print(data) values = serializers.serialize('json', attribute_data_values) print(values) response_data = { 'attribute': data, 'values': values } return HttpResponse(json.dumps({'data': response_data})) html <td><select class="form-control attribute-options" name="name" type="text"> {% for attribute in attributes %} <option value="{{attribute.pk}}">{{attribute.name}}</option> {% endfor %} </select></td> <td><input class="form-control attribute-input" name="value" type="text"></td> script(main problem is here) function Attributes(value){ $.ajax({ url: '{% url "get_attribute" %}', data:{ 'class_id' : value, }, dataType: 'json', success: function(response) { // console.log(response.data.attribute) var attribute = … -
len() of unsized object in Django template
Basically, I have store array [{'A': 'aa'}, {'B': 'bb'}, {'C': 'cc'}] in django model CharField(). In Templates {% for arr in my_array %} {{ arr }} {% endfor %} But, I got [ { ' A ': ' a a ' }, { ' B ': 'b b ' } , { ' C ': ' c c ' } ]. In views.py print(type(my_array)) # Output: <class 'str'> Then, I edit my code as: import numpy as array my_array = array.asarray(my_array) print(type(my_array)) # Output: <class 'numpy.ndarray'> Then, I got an error at browser: len() of unsized object so, how can I fixed this error? -
Setup Jetsi in back-end with connection monitoring with Django
I want use jitsi meet for a project. I have to task: Monitoring internet connection of clients inside a room Saving some data inside the browser cookies or opening a session for each client For the first task I need to ping the clients in some intervals to check the internet speed and also if a client gets disconnected I need to log it somewhere in the back-end server( Due to bad internet connections in my country this kind of monitoring is necessary for me). Also Might to write to browser cookies for some other purpose. I want to use Django for my web application.I know I have to use Jitsi meet api but unfortunately there is no good tutorial or answer for my work and couldn't find anything in the documentation. There are many codes describing how to implement the api in JS but that's mostyl front-end and custom UI or configs. Also I know I have to install jitsi-meet in a VM and give the domain to the web application. How ever I do not know the back-end development processes and since I need to monitor and probably save the data in a DB I really need help. … -
How to place a button in each row of table in django management form
In my Django application, I have a form with Parent/Child model objects laid out using loop. To dynamically add child form instances, I am using Django dynamic formset. Every thing works fine including saving of user inputs without hassle. So far, so good. However, now my user wants that I place one button before a particular field (spl_instructions) in each of the dynamically rendered rows (of fields). The instant field spl_instructions (of the child table) is a CharField of 255 chracters and is being rendered as Textarea in the page. The "button" is intended to be used to open the field spl_instructions if and when there is a need to enter text in the field. This route is being taken to conserve space. models.py class ProductAssy(models.Model): prod_assy_id = models.AutoField(primary_key=True, ...) prod_assy_num = models.CharField(max_length=24, ...) prod_assy_type = models.ForeignKey(MaterialType, ...) short_text = models.CharField(max_length=55, verbose_name="Description") # ... Rest of the fields class BillOfMatlItems(models.Model): bom_item_id = models.AutoField(primary_key=True, ...) prod_assy_id = models.ForeignKey(ProductAssy, ...) short_text = models.CharField(max_length=55, verbose_name="Description") spl_instructions = models.CharField(max_length=255, ...) # ... Rest of the fields forms.py class CreateProdAssyForm(forms.ModelForm): class Meta: model = ProductAssy fields = (...) class CreateAssyBomForm(forms.ModelForm): class Meta: model = BillOfMatlItems fields = (...) widgets = { 'short_text': forms.TextInput(attrs={'style': 'width:300px; text-align:right;'}), …