Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting Intermittent 403 error while making a fetch request from JS
I am trying to call a POST API via fetch await in JS which sometimes gives 201 and sometimes it gives 403. const apiCalls = number_arr.map(async (event) => { const response = await fetch(`{% url 'base_check_url' %}?number=${event.attrs.value}`, { method: "POST", credentials: 'include', headers: {'Content-Type': 'text/plain'}, }); APIs are written using django framework Attaching screenshot of error response logged in console: This is an intermittent issue, if I hit the API via JS 10 times, 70% of the time I would get 403. Also, do let me know if any other info is required to debug this issue. Thanks in advance. -
Django can't find existing html file in template folder
I'm trying to get the login page working on a seperate Django app. My register.html works just fine but i can't do the same with login html. The Error: TemplateDoesNotExist at /members/login/ registration/login.html Request Method: GET Request URL: http://127.0.0.1:8000/members/login/ Django Version: 4.2.4 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Exception Location: C:\Users\Furkan\AppData\Roaming\Python\Python311\site-packages\django\template\loader.py, line 47, in select_template Raised during: django.contrib.auth.views.LoginView Python Executable: C:\Program Files\Python311\python.exe Python Version: 3.11.5 Python Path: ['C:\\Users\\Furkan\\desktop\\dcrm\\dcrm', 'C:\\Program Files\\Python311\\python311.zip', 'C:\\Program Files\\Python311\\DLLs', 'C:\\Program Files\\Python311\\Lib', 'C:\\Program Files\\Python311', 'C:\\Users\\Furkan\\AppData\\Roaming\\Python\\Python311\\site-packages', 'C:\\Program Files\\Python311\\Lib\\site-packages'] Server time: Fri, 06 Oct 2023 13:59:43 +0000 views.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('website.urls')), path('members/', include('django.contrib.auth.urls')), path('members/', include('members.urls')), ] members/views.py: from django.shortcuts import render from django.views import generic from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy class UserRegister(generic.CreateView): form_class = UserCreationForm template_name = 'registiration/register.html' success_url = reverse_lazy('login') members/templates/registiration/login.html: {% extends 'base.html' %} {% block title %} Login {% endblock %} {% block content %} <div class="col-md-7 offset-md-3"> <h1 class="heading-one">Login</h1> <br> <br> <div class="form-group"> <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-success">Login</button> </form> </div> </div> {% endblock%} website/templates/navbar.html: <nav class="navbar navbar-expand-lg navbar-dark nav-color fixed-top"> <a class="navbar-brand" href="{% url 'home' %}" ><b>Furkan Çelik</b></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" … -
Classification ai model is integrated in Django app. I have configured using nginx for production purpose but i am facing an issue. "Trusted origin"
when i run project using local host on port 8000 then my project runs and displays the result but when i run it on port 81 project runs but doesn't display result. Error: Forbidden (Origin checking failed - http://textapp.local:81 does not match any trusted origins.): I have done "inginx" config. -
How to include Flask routes inside the Django
I wanted to use the Plotly Dash inside the Django. I don't want to use the django-plotly-dash python library because it have compatibility issues and all. Is there any way to include the Flask routes other than that Suggest a way to include the flask routes -
update the object in the database to indicate that a payment has been successfully processed
` @csrf_exempt def stripe_webhook(request): stripe.api_key = settings.STRIPE_SECRET_KEY time.sleep(30) payload = request.body signature_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, signature_header, settings.STRIPE_WEBHOOK_SECRET) except ValueError as e: logging.error(f"ValueError: {e}") return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: logging.error(f"SignatureVerificationError: {e}") return HttpResponse(status=400) if event['type'] == 'checkout.session.completed': session = event['data']['object'] session_id = session.get('id', None) if session_id: try: user_payment = UserPayment.objects.get(stripe_checkout_id=session_id) user_payment.payment_bool = True user_payment.save() logging.info(f"Updated payment_bool for session_id: {session_id}") except UserPayment.DoesNotExist: logging.error(f"UserPayment not found for session_id: {session_id}") else: logging.error("session_id is missing in the event data.") return HttpResponse(status=200)` I have been trying to update the 'UserPayment' object in the database to indicate that a payment has been successfully processed, but it doesn't work, even though the payment is successful in sripe -
I recently deployed my website and while submitting the forms or logging in on admin, I get this error
I get this problem almost every time I tried to do login admin and submit forms. After logging in admin and sending form same error is occuringg. I have left the default admin panel of django for site updates and used crispy forms for form in my website. -
My static files are not coming in my Django API project after deploying it in AWS EC2
I have created a simple API with django but after deploying it on AWS EC2 the admin panel is not showing any CSS or design. Please Help. Like This: enter image description here nginx file: server { listen 80; server_name 0.0.0.0; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/sweetraga_django/static/; } location / { proxy_pass http://0.0.0.0:8000; } } settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') -
Gym system managment [closed]
I need to develop a financial control system for a gym and also include student registration. Because of this, I am unsure about which programming language to use. I have more knowledge in Javascript and Python, but I have also studied a bit of PHP and C#. While searching on the internet, I found that most gym management systems are developed in PHP or C#. However, I had in mind to use React with TypeScript for the front-end, and I am uncertain about what would be more feasible for the back-end: Node, Django, PHP, or C#. Some things I need to implement in the future include printing documents, a mobile app, and integration with a turnstile system. These are some factors that will weigh in on the decision, as the chosen language needs to be compatible with these elements to avoid headaches when implementing them in the future. Does anyone have any suggestions? As I have more expertise in TypeScript and Django, I am considering using one of these two options. However, if another option is deemed necessary, that wouldn't be a problem. -
Database trigger on update, remove, create
I want some code to be executed after every change in the database in a specific table. Meaning, if an entry was inserted, removed or updated. I found this https://stackoverflow.com/a/15712353/2813152 using django signals. Is this the recommended way for this? Can I use it for any changes at this table? Not just when an instance is saved? Can the code run async in the background? -
Django urls cannot find a view
I'm getting an error under views.LessonLike.as_view(), saying that Module 'roller_criu_app' has no 'LessonLike' member Does anyone know why? The other views (LessonList and LessonDetail) seem to be fine. I tried to use the from .views import LessonLike instead and I also get an error saying that it doesn't exists. Really confused as why the linter is saying that it doesn't esxist views.py from django.shortcuts import render, get_object_or_404, reverse from django.views import generic, View from django.http import HttpResponseRedirect from .models import Lesson from .forms import FeedbackForm class LessonList(generic.ListView): model = Lesson queryset = Lesson.objects.filter(status=1).order_by('lesson_level') template_name = 'index.html' paginate_by = 6 class LessonDetail(View): def get(self, request, slug, *args, **kwargs): queryset = Lesson.objects.filter(status=1) lesson = get_object_or_404(queryset, slug=slug) feedbacks = lesson.feedbacks.filter(approved=True).order_by('created_on') liked = False if lesson.likes.filter(id=self.request.user.id).exists(): liked = True return render( request, "lesson_detail.html", { "lesson": lesson, "feedbacks": feedbacks, "submitted_feedback": False, "liked": liked, "feedback_form": FeedbackForm(), }, ) def post(self, request, slug, *args, **kwargs): queryset = Lesson.objects.filter(status=1) lesson = get_object_or_404(queryset, slug=slug) feedbacks = lesson.feedbacks.filter(approved=True).order_by('created_on') liked = False if lesson.likes.filter(id=self.request.user.id).exists(): liked = True feedback_form = FeedbackForm(data=request.POST) if feedback_form.is_valid(): feedback_form.instance.email = request.user.email feedback_form.instance.name = request.user.username feedback = feedback_form.save(commit=False) feedback.lesson = lesson feedback.save() else: feedback_form = FeedbackForm() return render( request, "lesson_detail.html", { "lesson": lesson, "feedbacks": feedbacks, "submitted_feedback": True, "liked": … -
update_or_create for specific table rows
I got a model like this: class AssignedTip(models.Model): """Model representing a tip (but not a specific copy of a tip).""" user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(null=True) note = models.CharField(max_length=50, default="Tip") amount = models.FloatField() minutes = models.FloatField(default=0) class Meta: unique_together = ('user', 'date',) so there is a unique constraint with user+date. Now I want to insert new data into the table. but if the unique constraint is matched, it should update the object instead of creating a new one. How can I do this. Using create_or_update gives me an error and is not updating the item. How can I tell it to update if constraing is matched?: AssignedTip.objects.update_or_create(user=User.objects.get(id=user), amount=user_amount, date=day.date(), minutes=minutes) I get this error: Environment: Request Method: GET Request URL: http://0.0.0.0:8000/tasks/ Django Version: 4.0.8 Python Version: 3.10.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'tasks.apps.TasksConfig', 'tips.apps.TipsConfig', 'ratings.apps.RatingsConfig', 'procedures.apps.ProceduresConfig', 'inventory.apps.InventoryConfig', 'registration.apps.RegistrationConfig', 'ckeditor', 'crispy_forms', 'crispy_bootstrap4', 'django_crontab'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', 'login_required.middleware.LoginRequiredMiddleware'] Traceback (most recent call last): File "/home/raphael/.conda/envs/iaro/lib/python3.10/site-packages/django/db/models/query.py", line 657, in get_or_create return self.get(**kwargs), False File "/home/raphael/.conda/envs/iaro/lib/python3.10/site-packages/django/db/models/query.py", line 496, in get raise self.model.DoesNotExist( During handling of the above exception (AssignedTip matching query does not exist.), another exception occurred: File "/home/raphael/.conda/envs/iaro/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in … -
How to ensure that my Django view ouputs a file download?
My view transcribes a file and outputs the SRT transcript. Then it locates and is supposed to auto download the transcript but nothing happens(the file was submitted on a previous page that uses the transcribeSubmit view. The view that handles and returns the file is the initiate_transcription view). Here is my views.py: @csrf_protect def transcribeSubmit(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) request.session['uploaded_file_name'] = filename request.session['uploaded_file_path'] = fs.path(filename) #transcribe_file(uploaded_file) #return redirect(reverse('proofreadFile')) return render(request, 'transcribe/transcribe-complete.html', {"form": form}) else: else: form = UploadFileForm() return render(request, 'transcribe/transcribe.html', {"form": form}) @csrf_protect def initiate_transcription(request): if request.method == 'POST': # get the file's name and path from the session file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path') if file_name and file_path: with open(file_path, 'rb') as f: path_string = f.name transcribe_file(path_string) file_extension = ('.' + (str(file_name).split('.')[-1])) transcript_name = file_name.replace(file_extension, '.srt') transcript_path = file_path.replace((str(file_path).split('\\')[-1]), transcript_name) file_location = transcript_path with open(file_location, 'r') as f: file_data = f.read() response = HttpResponse(file_data, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename="' + transcript_name + '"' return response else: #complete return render(request, 'transcribe/transcribe-complete.html', {"form": form}) def transcribe_file(path): #transcription logic I used similar code on another view/page that worked but when adapted to this page it … -
Direct assignment to the reverse side of a related set is prohibited. Use user.set() instead
I'm working on a project where user is able to register an account using referral code. During the process of a user registering an account, this error occur. "Direct assignment to the reverse side of a related set is prohibited. Use user.set() instead." What should be the cause of this error message? Note: I'm using Django UserCreationForm Views.py def RefSignupView(request): profile_id = request.session.get('ref_profile') print('profile.id', profile_id) form = UserCreationForm(request.POST or None) if form.is_valid(): if profile_id is not None: recommended_by_profile = Profile.objects.get(id=profile_id) instance = form.save() #The error points to instance=form.save() registered_user = User.objects.get(id=instance.id) registered_profile = Profile.objects.get(user=registered_user) registered_profile.recommended_by = recommended_by_profile.user registered_profile.save() else: form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('site:profile', username=username) context = { 'form': form, } return render(request, 'ref_signup.html', context) -
Can i disable default ordering in Django admin panel?
I'm trying to use 'liczba_glosow' field for ordering in Django admin panel. The problem is that the model itself has ordering by "numer_na_liscie" in Meta method and admin uses default ordering and than 'liczba_glosow'. I would like admin to use ONLY order_by("-_liczba_glosow") and bypass default. I can't use simple ordering="liczba_glosow" because this field is created only for admin display purpose and it's not part of a model itself. class KandydatDoSejmuAdmin(admin.ModelAdmin): list_display = ("imie_nazwisko", "numer_na_liscie", "okreg_wyborczy", "komitet_wyborczy", "liczba_glosow") raw_id_fields = ("okreg_wyborczy", "komitet_wyborczy") list_filter = ("komitet_wyborczy__nazwa", "oddanyglos__kod_pocztowy__wojewodztwo", "okreg_wyborczy__nazwa",) search_fields = ( "imie_nazwisko", "okreg_wyborczy__nazwa", "komitet_wyborczy__nazwa", "oddanyglos__kod_pocztowy__wojewodztwo") list_per_page = 10 def liczba_glosow(self, obj): return obj.oddanyglos_set.count() liczba_glosow.admin_order_field = "_liczba_glosow" def get_queryset(self, request): qs = super().get_queryset(request) return qs.annotate( _liczba_glosow=Count("oddanyglos__kandydat") ).order_by("-_liczba_glosow") According to Django docs: Set ordering to specify how lists of objects should be ordered in the Django admin views. This should be a list or tuple in the same format as a model’s ordering parameter. If this isn’t provided, the Django admin will use the model’s default ordering. According to the above provision, any attempt to disable the default sorting like ordering=None, get_ordering() returning None or empty list doesn't work. Is there an option to override the default sorting in the admin panel without interfering … -
Migrate `DateTimeField` to `DateField` in Django
I got objects that have an attribute that is a DateTimeField now I want to change this to a DateField. But I already have data in my database so just doing this migration: migrations.AlterField( model_name='assignedtip', name='date', field=models.DateField(), ), will not work, as the table is broken afterwards. How can I make sure, that when executing this migration with makemigration the DateTimeField values are first converted to DateFields? -
Annotate on Django model property to filter
I've this property: class PropModel(TimeStampedModel): content = models.CharField(max_length=255) class PropertyChoices(models.TextChoices): OK = "OK" NOTOK = "NOT_OK" NONE = "NONE" @property def prop_func(self): if self.start_date < datetime.now(): return self.PropertyChoices.OK elif self.start_date > datetime.now(): return self.PropertyChoices.NOTOK else: return self.PropertyChoices.NONE And I would like to filter on this prop_func model class property this filter is working fine: class PropFilter(filters.FilterSet): prop = filters.CharFilter(method="filter_prop") class Meta: model = PropModel fields = ["prop"] def filter_prop(self, queryset, name, value): matching_items = [ item.id for item in queryset if value.lower() in item.prop_func.lower() or value.lower() in item.content.lower() ] return queryset.filter(id__in=matching_items) but I would like to have the exact same behavior. To get my queryset items which have value into the field content or if value into the prop_func return -
django admin site logging in error: CSRF verification failed. Request aborted
When I try to log in to Django admin site I get the following error: CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. I'm using Django 4.2.5. I can login on my local machine. However, I can't login to the site running in the server. I have added the following settings to my settings.py file CSRF_TRUSTED_ORIGINS = ["https://*.mydomain.ir","http://*.mydomain.ir","http://127.0.0.1","http://localhost","http://127.0.0.1:8000"] SECURE_SSL_REDIRECT = False SESSION_COOKIE_SECURE = True SESSION_COOKIE_DOMAIN = None CSRF_COOKIE_DOMAIN = 'mydomain.ir' if os.environ.get("IS_SERVER", "False") == "True": SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = ["*"] CORS_ALLOW_HEADERS = ['*'] SESSION_COOKIE_HTTPONLY = False CORS_ALLOW_ALL_ORIGINS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' I'm using Nginx and Gunicorn. here's my Nginx config file: server { server_name api.mydomain.ir; listen 80; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/mydomain.ir/fullchain.pem; # managed … -
How to create django backend for alexa account linking
I want to know how can i use django auth toolkit for alexa accountg linking. I have completed from my side but when backend authrize user and send requeust to alexa redirect uri It,s throing error enter image description here I tried with creating application. -
Integrating Django and Socket Communication in a Kivy Chat Application
I've developed a chat application using Kivy. Within the application, the server and client establish communication via pythons built-in socket. While it functions adequately, I'm considering incorporating Django on the server side. Navigating through various libraries like pythons built-in socket, Django WebSocket, and websockets has left me somewhat perplexed. I would greatly appreciate your assistance in clarifying at least one of the following queries: 1- Could you elucidate the distinctions between pythons built-in socket, socketio, and websockets in Django, as well as the websockets library in Python? 2- Is it feasible to employ different libraries on the client and server sides, such as using pythons built-in socket (or websockets) on the client side and Django WebSocket on the server side? 3- Does Django Channels offer support for Python's native socket, rather than relying exclusively on channel websockets? 4- Is it plausible to integrate Django into a Python chat application centered around pyhon socket, leveraging its functionalities for user authentication, database management, and static content handling in conjunction with real-time communication? -
Django post request failing silently
I have a Django - React project. I am having an issue where one of my post APIs is throwing an error message which I am not being able to resolve. Following is the class from my views.py class OrdersList(generics.ListCreateAPIView): queryset = models.Order.objects.all() serializer_class = serializers.OrderSerializer Following is the urls.py path('orders/', views.OrdersList.as_view()), Following is the post call from react.js const formData = new FormData(); formData.append('customer_id', customerId); axios.post(createOrderUrlRef.current, formData).then((response) => { console.log(`${TAG} ${JSON.stringify(response)}`); }).catch((error) => { console.log(`${TAG} error: ${JSON.stringify(error)}`); }); My environment is currently DEBUG and I see following error in console of Firefox, OrderConfirmation error: {"message":"Request aborted","name":"AxiosError","stack":"AxiosError@http://localhost:3000/static/js/bundle.js:88555:18\nhandleAbort@http://localhost:3000/static/js/bundle.js:87934:14\..."headers":{"Accept":"application/json, text/plain, */*"},"method":"post","url":"http://127.0.0.1:8000/api/orders/","data":{}},"code":"ECONNABORTED","status":null} There is no error message seen in django console. -
Cannot assign "'12'": "Receive.registerleson" must be a "Registerleson" instance
error : ValueError at /operation/member/RecivVoucher/339/ Cannot assign "'3'": "Receive.registerleson" must be a "Registerleson" instance. model : class Receive(models.Model): student = models.ForeignKey("user.Profile", on_delete=models.CASCADE, verbose_name='زبان آموز', related_name='receives') factor = models.ForeignKey("product.Factor", on_delete=models.CASCADE, verbose_name='فاکتور', null=True, blank=True) registerleson = models.ForeignKey("member.Registerleson", on_delete=models.CASCADE, verbose_name='ثبت نام', null=True, blank=True) term = models.ForeignKey("term.Term", on_delete=models.CASCADE, verbose_name='سال', null=True, blank=True) personnel = models.CharField(max_length=150, verbose_name='ثبات', null=True, blank=True) price = models.CharField(max_length=100, verbose_name='مبلغ دریافتی') code_peygiri = models.IntegerField(verbose_name='کد پیگیری', unique=True) date_pardakht = models.DateField(verbose_name='تاریخ پرداخت', null=True, blank=True) bank = models.CharField(max_length=100, verbose_name='بانک', null=True, blank=True) description = models.CharField(max_length=150, verbose_name='توضیحات', blank=True) created_at = models.DateTimeField(auto_now_add=True, null=True) babat = models.CharField(max_length=10, choices=Babat, verbose_name='بابت', null=True, blank=True) def RecivVoucher(request, id): member = get_object_or_404(Profile, pk=id) term = get_object_or_404(Term, termjari=1) form = ReceiveForm() if request.method == 'POST': form = ReceiveForm(request.POST) price = request.POST['price'].replace(",", "") if form.is_valid(): fs = form.save(commit=False) fs.student = member fs.term = term fs.price = price fs.personnel = request.user.id fs.babat = request.POST['babat'] fs.registerleson = request.POST['hazine'] if request.POST['babat'] == 1: fs.registerleson = request.POST['hazine'] if request.POST['babat'] == 2: fs.factor = request.POST['hazine'] fs.save() messages.add_message(request, messages.INFO, 'ثبت با موفقیت انجام شد') redirect('RecivVoucher', id) else: messages.add_message(request, messages.WARNING, 'خطا در ثبت اطلاعات') redirect('RecivVoucher', id) context = { 'member': member, 'form': form, } return render(request, 'member/RecivVoucher.html', context) error : ValueError at /operation/member/RecivVoucher/339/ Cannot assign "'3'": "Receive.registerleson" must be a "Registerleson" instance. -
Programming language selection help. NOOBIES HERE [closed]
Which programming language is good for a startup for creating reddit like social medias, where we can iterate with clean code and learn simultaneously easily. We are looking to learn Python or JS. But what should we choose ? or is there any other language ? -
Is there a way to 'concatenate' a raw sitemap.xml with the generated in django sitemaps?
Django has a built in sitemaps app that create a sitemap.xml, but I need to integrate with another django project that has it's own sitemap.xml. So, the idea it's to make a call to https:another-django-project/sitemap.xml and with that xml 'append' to my django project sitemap.xml and use that as sitemap. There are 2 projects, in different containers, works like one site(one Web, one Wagtail) mysite.com. So, in mysite.com/sitemap.xml should return all info from both I've tried to implement the class WebSitemap(DjangoSitemap): and override something like 'generate_xml()' so I could make a http call to the another application and append the xml, but that doesn't exist. I've tried to make my own view that calls the django sitemaps programmatically, make a call to the another application xml, concatenate and return. doesn't look a good approach. how can I do that? -
VSCode, Django and javascript: Why does VSCode indicate an error when I use {{ }}?
I have the following code that works in my html file: {% for stocks_and_pair_data in stocks_and_pair_data_list %} <script> var ctxClose = document.getElementById('ChartOfClosePrices{{ forloop.counter }}'); new Chart(ctxClose, { type: 'line', data: { labels: {{stocks_and_pair_data.dates|safe}}, datasets: [{ label: '{{ stocks_and_pair_data.stock1_name|safe }}', data: {{stocks_and_pair_data.stock1_close_prices|safe}} },{ label: '{{ stocks_and_pair_data.stock2_name|safe }}', data: {{stocks_and_pair_data.stock2_close_prices|safe}} }] } }); </script> {% endfor %} But VSCode indicates the error "Property assignment expected" at 'labels' line and at both 'data' lines, which are where I use double {{ }} without quotes. I can't use quotes there because these are lists, not strings. Am I doing it wrong, despite of the code working? What should I do to correct it? -
django on update modelform not presenting stored value as selected
I have an uninteresting modelform. One of the model fields, occupation, is a foreignkey to a table containing a long, long list of options. The problem is for update, the rendered form, which is rendered via crispy, does not set focus to the stored value (mark it as the selected option in the <select><option...> code). Instead, it shows the empty choice. I see the initial value does point to the id of the database's record. To make this a little more "interesting," I want to change occupation.to_field_name to occupation.code (a charfield). I've been futzing with the form's init as given below. I can convert the option values to the form I want, but I cannot get the form to present the stored value as selected (and present as the field's selected value). How do I do this? Do I have to do it via JS or am I doing something wrong with the form? Thanks. class Meta: model = TutorOptionalServiceAndDemographics fields = ['highest_degree', 'country_of_birth', 'immigrant', 'us_citizen', 'employment_status_at_enrollment', 'occupation', 'employer_name', 'referral', ] labels = { 'highest_degree': 'Highest degree/diploma earned', 'us_citizen': 'US Citizen:', 'immigrant': 'Immigrant:', 'country_of_birth': 'Country of Birth:', 'employment_status_at_enrollment': 'Employment status at time of registration:', 'occupation': 'Occupation:', 'employer_name': 'Employer Name:', 'referral': …