Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to stop videos from autostart in html
i m working on django where i need to show more than one video in one page . can anyone help me how to stop autostart my videos in iframe. thank you and here is my code. <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" width="1280" height="720" src="/static/assets/img/examples/vi.mp4?&autoPlay=0" frameborder="0" &autoPlay="false"></iframe> </div> -
Django deployment error on console when opening through Public IP
I am deploying a django site for the first time on aws ubuntu linux ec2 instance. I used Apache and mySQL database. I was able to successfully deploy the site and it was accessible through my public IP but it gave a warning in the Chrome console: [Deprecation] The website requested a subresource from a network that it could only access because of its users' privileged network position. These requests expose non-public devices and servers to the internet, increasing the risk of a cross-site request forgery (CSRF) attack, and/or information leakage. To mitigate these risks, Chrome deprecates requests to non-public subresources when initiated from non-secure contexts, and will start blocking them in Chrome 92 (July 2021). My project uses Django Rest Framework to post and get requests. I have used react for frontend so I use its build folder as a template in django and my frontend sends request to the public ip of my server. I am also attaching my settings.py file in case any of my settings might be a problem. I read somewhere that using a domain name would solve this error but I wasn't sure whether the issue was the same as mine. Also if this … -
Django login() authenticate always returns None
I have this code written up and it correctly registers users, though when it comes to the login function, it only works for the superuser i have in the database. Every time I try to log in a user that i greated using the register form, authenticate returns None. I'm having it print the form data and can confirm that the form being submitted has accurate info, yet it fails authentication every time unless i login the superuser. Views: def register(request): print(request.method) if request.method == 'POST': form = reg_form(request.POST) print(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') email = form.cleaned_data.get('email') phone = form.cleaned_data.get('phone') first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') user = Users.objects.create( username=username, email=email, password=password, phone=phone,first_name=first_name, last_name=last_name ) try: user = Users.objects.get(phone=form.cleaned_data.get('phone')) print("User exists") except Users.DoesNotExist: print("DoesNotExist") return render(request, 'register.html', {'form': reg_form}) login(request, user) return render(request, 'profile.html') else: print(form.errors) return render(request, 'register.html', {'form': reg_form}) else: return render(request, 'register.html', {'form': reg_form}) def log_in(request): if request.method == 'POST': form = log_form(request.POST) print(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) print(user) if user is not None: print("user exists") login(request, user) return render(request, 'profile.html') else: print("user does not exist") print(form.errors) return render(request, 'login.html', { 'form2': log_form }) … -
django handling a form in a different view
I have three views : home, Product_List , Product_Detail that use the same form the addToCart form so i have to repeat the same code in these views to handle the form submission , so how to avoid that ?? i tried to create a function in the Cart model manager but when i call that function it retrun context errors and template tags errors this is the product_detail view : def product_detail(request, slug): if not request.session.exists(request.session.session_key): request.session.create() product_detail = get_object_or_404(Product, slug=slug) cart_obj = Cart.objects.new_or_get(request) object_viewed_signal.send(product_detail.__class__, instance=product_detail, request=request) if request.method == 'POST': Cart_Item_Post_Form = CartItemPostForm(request.POST or None) if Cart_Item_Post_Form.is_valid(): quantity = Cart_Item_Post_Form.cleaned_data['quantity'] product_id = request.POST.get("product_id") product_obj= Product.objects.get(id=product_id) try: get_cart_item = Cart_Item.objects.get(cart=cart_obj,products= product_obj) pre_quantity = get_cart_item.quantity new_quantity = pre_quantity + quantity get_cart_item.quantity = new_quantity get_cart_item.save() object_added_signal.send(product_detail.__class__, instance=product_detail, request=request) return redirect('cart_home') except(Cart_Item.DoesNotExist): Cart_Item_Post_Form.instance.products = product_obj Cart_Item_Post_Form.instance.cart = cart_obj Cart_Item_Post_Form.save() object_added_signal.send(product_detail.__class__, instance=product_detail, request=request) return redirect('cart_home') else: Cart_Item_Post_Form = CartItemPostForm() context = { 'product_detail' :product_detail, 'form' :Cart_Item_Post_Form, } return render(request,'product_detail.html', context) i want to replace the form handling code by some kind of a function -
Passing arguments to URL in template: No reverse match
I am using Django 3.2 I have a URL defined as follows urls.py app_name = event ... path('path/to/<int:event_id>/<slug:event_slug>', views.detail, name='detail'), ... mytemplate.html <a href="{% url 'event:detail' event_id=item.pk event_slug=item.slug %}" class="btn btn-primary">Find out more ...</a> When I visit the page in the browser, I get the error: NoReverseMatch at /path/to/ Reverse for 'detail' with keyword arguments '{'event_id': '', 'event_slug': ''}' not found. 1 pattern(s) tried: ['/path/to/(?P<event_id>[0-9]+)/(?P<event_slug>[-a-zA-Z0-9_]+)$'] Note: item is a variable passed to the template -
Django: I have a question about making an API in Django
guys! I'm doing a test that asks me to make an API and I don't have experience with that. The test says: "In order for us to know who the debtors are, the status of their credit recovery and more information, create an API to save and provide information about the cases and the people involved(credtors and debtors)." I'm confusing about the "to save" part. Do I have to make routes to save new creditors, debitors and cases, or the admin panel of Django is responsible for that and I have to just create routes to return information about the cases, creditors and debitors in json? -
Nginx redirecting to welcome page
I'm trying to deploy my Django app on VPS for the testing domain "yatsekk.pl". This is my first time deploying an app from scratch and I mostly follow the instructions from https://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/. The VPS server which I have runs with Centos 7. Almost everyting seems to be prepared and when I test it by gunicorn --bind 0.0.0.0:8000 strona.wsgi it seems to run correctly when I run it by "yatsekk.pl:8000" in the browser. I created the "gunicorn_run" file in the following way: NAME="polwysep" # Name of the application DJANGODIR=/root/Polwysep # Django project directory SOCKFILE=/root/run/gunicorn.sock # we will communicte using this unix socket USER=root # the user to run as GROUP=webapps # the group to run as NUM_WORKERS=3 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=strona.settings # which settings file should Django use DJANGO_WSGI_MODULE=strona.wsgi # WSGI module name echo "Starting $NAME as `whoami`" cd $DJANGODIR source ../env/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR exec env/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- Just to test it, I previosuly tried to change the --bind=unix:$SOCKFILE part to --bind=0.0.0.0:8000 and it once again did correctly run the page … -
Django - Is My Static File in the Wrong Place?
I'm creating a project for a weather app with Django, and I think my Javascript file is in the wrong place. I have it in a static folder. But I'm getting the console error GET http://127.0.0.1:8000/static/capstone/capstone.js net::ERR_ABORTED 404 (Not Found) Here is how my project files are set up. Is this correct? In settings.py I also have: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') -
Unable to calculate percentage with django and python
I know am doing something wrong here. Am trying to create an app where a user will deposit an amount and 8 percent of that amount deposited will be returned to the user in 10 days. Can someone please help me out. I want Eight percent of the deposited amount returned to the user in 10 days after the deposit to the user Models.py class Profile(models.Model): user = models.ForeignKey(UserModel, on_delete=models.CASCADE) balance = models.DecimalField(default=Decimal(0),max_digits=24,decimal_places=4) class Investment(FieldValidationMixin, models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) fixed_price = models.DecimalField(max_digits=7, decimal_places=2, nulll=True, blank=True) percentageee = models.DecimalField(max_digits=3, decimal_places=0, nulll=True, blank=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) def __str__(self): return _("{0}: (#{1} {2}%, ${3})".format(self.__class__.__name__, self.amount, self.percentage, self.fixed_price) ) This code intends to fetch the percentage of user amount payed in the investment models and calculate the percentage Views.py def get_percentage(self): pec_of_amount = Investment.objects.filter(amount=self.amount).annotate(percentageee=Sum('amount')) return '{:%}'.format(amount.percentageee / 8) def percentile(self, days=10): percent=Investment.objects.filter(self.amount*self.percentage)/100 in days return percentile #get the percentage balance of the amount invested after ten days def get_current_balance(self,percentile): total_expenses = Profile.objects.all().aggregate(Sum('balance')).annonate(percentile) return get_current_balance -
Django Integrity Error: Foreign Key Issue
I am creating an application where I have multiple stores and each store has an owner. One owner can own multiple stores but for a single store, there will only be one owner. I defined the store and owner models as follows:- ''' Store Owner Class ''' class Owner(models.Model): # Define the fields for the Customer first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone = models.CharField(max_length=15) email = models.EmailField() password = models.CharField(max_length=500) ''' Store Model''' class Store(models.Model): """Model for the market which will hold all our stores and products Args: models: Inherits the model class """ # Define the fields of the market class name = models.CharField(max_length=100, null=False) description = models.CharField(max_length=1000, default="", null=True, blank=True) address = models.CharField(max_length=1000, null=True, default=" ", blank=True) logo = models.ImageField(upload_to='uploads/images/logos') owner = models.ForeignKey(Owner, on_delete=models.CASCADE) When I run migrate command on the models, I get the following error. django.db.utils.IntegrityError: The row in table 'market_store' with primary key '1' has an invalid foreign key: market_store.owner_id contains a value '1' that does not have a corresponding value in market_owner.id. I understand that this is a foreign key error in the store and owner table but I cannot seem to find a way through which I can connect my models without … -
Passing only one product to Stripe checkout from Django
I've integrated Django with Stripe and seems that works ok. However i have a problem by showing all products in stripe checkout page. I need to tell stripe which products we're going to buy. If i have 2 products in cart i see only one product in stripe checkout. views.py def payments_stripe(request): YOUR_DOMAIN = "http://127.0.0.1:8000/orders" print(request.body) body = json.loads(request.body) cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = cartItem.objects.filter(cart=cart, is_active=True) print(cart_items) order = Order.objects.get(cart=cart, is_ordered=False, order_number=body['orderID']) print(order) for cart_item in cart_items: quantity = cart_item.quantity print(quantity) name = cart_item.product.name print(name) try: checkout_session = stripe.checkout.Session.create( customer_email=order.email, billing_address_collection='auto', payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'eur', 'unit_amount': int(order.order_total * 100), 'product_data': { 'name': name, 'images': ['https://i.imgur.com/EHyR2nP.png'], }, }, 'quantity': quantity, }, ], metadata={ 'order_number': body['orderID'], 'payment_method': body['payment_method'], 'cart_id': cart, }, mode='payment', success_url=YOUR_DOMAIN + '/success/', cancel_url=YOUR_DOMAIN + '/cancel/', ) return JsonResponse({'id': checkout_session.id}) except Exception as e: return JsonResponse(error=str(e)), 403 I iterate over cart items and Iteration gives: 1 Golden Arrow 1 Silver Heart However in Stripe dashboard i see only one product 1 Golden Arrow. I suppose i need to create a new list. Is that right? How can i do that in my case? Thank you -
KeyError: 'product_id'
So I am following along with a youtube course and create an e-commerce web application and customizing it for specific needs. I am running into a KeyError in my api.py file when trying to assign product_id to the product_id SEE LINE BELOW: product_id = data['product_id'] from the request.body but this breaks the application as it cannot find that key. . After further inspection, I see that the request body dictionary only contains two of the three variables ('quantity' and 'update') and missing the 'product.id' variable. I am having trouble trying to figure out why that is. If anybody could help and kind of explain their reasoning that would be great(I am still learning so I would like to not just have the answer but know why as well). Below is the Vue code in cart.html and the api.py code which are where the issue is. Thnaks! I have been stuck on this for quite some time now and would like to understand and fix this so I can continue the project cart.html {% extends 'base.html' %} {% block title %}Cart | {% endblock %} {% block content %} <div id="hero" class="mid"> <div class="hero text-center"> <h2 class=" display-4 font-weight-bold">Cart</h2> <p class="text-light … -
Django DB API Response write in Model
i have a little Problem. Im trying to create an Calorietracker. The Calories for the meals are coming from an API. The Response of the API has many different listings in it which are similar to the food i searched for. Now i want to save my choice in the Django DB. Therefore i created a Model. The problem now is, i dont have any clue how to allocate my choice to the model. i would much appreciate it, if someone could give me some help ! Here is the code im using: Model: class Product(models.Model): productname = models.CharField(max_length=150) calories = models.FloatField(default=0) carbs = models.FloatField(default=0) protein = models.FloatField(default=0) fat = models.FloatField(default=0) views.py: def foodSearch(request): search_result = {} if 'food' in request.GET: searchform = APISearchForm(request.GET) if searchform.is_valid(): search_result = searchform.search() #print(search_result) context = {'searchform': searchform, 'search_result': search_result} else: searchform = APISearchForm() context = {'searchform': searchform, 'search_result': search_result} return render(request, 'search.html', context) search.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>search</title> </head> <h1> Lebensmittelsuche</h1> {% block content %} <label> When ? <input type="date" id="fooddate"> <input type="number" id="mealtime"> </label> <form method="get"> {{ searchform.as_p }} <button type="submit">Search</button> </form> {% if search_result %} <hr> {% for result in search_result.hints %} <form method="POST"> {%csrf_token%} <h3>{{ result.food.label … -
Change model field WITHIN model via method
I created a model that allows for courses and supporting info to be uploaded models.py from django.db import models from django.urls import reverse from datetime import datetime # Create your models here. class Course(models.Model): title = models.CharField(max_length=80) description = models.CharField(max_length=400) thumbnail = models.ImageField(upload_to="images/") video = models.FileField(upload_to="videos/") notes = models.FileField(upload_to="notes/") issued_at = models.DateField(auto_now_add=True) featured = models.BooleanField(default=False) is_fresh = models.BooleanField(default=True) def get_absolute_url(self): return reverse("courses:course_detail", kwargs={"pk": self.pk}) def time_passed(self): delta = datetime.now().date() - self.issued_at print(delta, "today: ", datetime.now().date()) return delta.days def is_fresh_check(self): if self.time_passed() >= 1: self.is_fresh = False return self.is_fresh As you can probably guess, I'm trying to see wether after ONE day or more of uploading the course, it should automatically change the value of 'is_fresh' attricbute to False. However, this isn't the case. I've also created an apiview to see the Course objects in json serializers.py from rest_framework import serializers from .models import Course class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ('title', 'description', 'issued_at', 'is_fresh') def to_representation(self, instance): data = super().to_representation(instance) data['time_passed'] = instance.time_passed() data['is_fresh_check'] = instance.is_fresh_check() return data Finally, here's the rendered json for the object: [ { "title": "course_name", "description": "course_description", "is_fresh": true, "time_passed": 1, "is_fresh_check": false } ] I don't know why my 'is_fresh_check' method … -
IntegrityError in djnago
Help I m getting IntegrityError can't find a solution to this error please help or show me how to fix this. The error is showing as follows: (1048, "Column 'targetDefn_id' cannot be null") this error is showing when I post data. This is my views.py in Post method I m getting this error: def setTarget(request): if request.method == 'POST': data=JSONParser().parse(request) print(data) serial=TargetSerializers(data=data) print(serial) if serial.is_valid(): serial.save() print("done") return JsonResponse(serial.data,status=status.HTTP_200_OK,safe=False) return JsonResponse(serial.errors, status=status.HTTP_400_BAD_REQUEST) This is my Serializer.py as follows: class TargetSerializers(serializers.ModelSerializer): targetDefn=serializers.SerializerMethodField() roleId=serializers.SerializerMethodField() empId=serializers.SerializerMethodField() class Meta: model = Target fields = ( 'id', 'targetDefn', 'roleId', 'empId', 'startDate', 'endDate', 'value' ) def get_targetDefn(self,obj): trgt = TargetDefination.objects.get(id=obj.targetDefn_id) serial = TargetDefinationSerializers(trgt) return serial.data def get_empId(self,obj): emp= Employee.objects.get(id=obj.empId_id) serial= OnlyEmployeeSerializers(emp) return serial.data def get_roleId(self,obj): role=Role.objects.get(id=obj.roleId_id) serial=RoleSerializers(role) return serial.data This is models.py as follows: class Target(models.Model): targetDefn=models.ForeignKey(TargetDefination,on_delete=models.CASCADE) roleId=models.ForeignKey(Role,on_delete=models.CASCADE) empId=models.ForeignKey(Employee,on_delete=models.CASCADE) startDate= models.DateField(default=datetime.date.today) endDate= models.DateField(null=True,blank=True) value=models.PositiveIntegerField(default=0) def __str__(self): return str(self.empId) + ' ' +str(self.targetDefn) -
Django Linking 2 tables through a foreign Key
i'm starting with django, and i'm trying to make an app that links orders to clients, for the user to be able to click a client and see wich orders that client have made. The issue is, every single tutorial uses either the command prompt or the admin screen to do those links manually, and i need them automatically from the code. This code is the one that i'm using for the Orden form. I get 2 errors, the first one is an 404 error ordenfill page not found, this after i click the guardar button, i suppose this is happening because after i click the guardar button, the form is not valid and is trying to reach an ordenfill url without the "nombre" parameter, but i'm not sure. If i remove the nombre parameter from the view and the url, then i dont know how to get that name and link the form to it, with this the 404 error stops but i never get a valid form because the system tells me the client field is needed. This ones are the models class Cliente(models.Model): nombre = models.CharField(max_length=100) email = models.EmailField(max_length=50) direccion = models.CharField(max_length=100, default='direccion') class Meta: db_table = … -
How to uniquely identify a model instance in django
I have program that keeps book records for different schools I have a Student model that enables each school to upload the students from an excel. I however get an error because already there are two schools each having form 1 form 2 and form 3. It returns MultipleObjectsReturned error. Setting the filed as unique also does not allow other schools to create the same klass. How is it that I can be able to uniquely identify every instannce ok Klass model so it returns no error. get() returned more than one Klass -- it returned 2! class ImportStudentsResource(resources.ModelResource): school = fields.Field(attribute = 'school',column_name='school', widget=ForeignKeyWidget(School, 'name')) klass = fields.Field(attribute = 'klass',column_name='class', widget=ForeignKeyWidget(Klass, 'name')) stream = fields.Field(attribute = 'stream',column_name='stream', widget=ForeignKeyWidget(Stream, 'name')) class Meta: model = Student fields = ('school','student_id','name','year','klass','stream') import_id_fields = ('student_id',) import_order = ('school','student_id','name','year','klass','stream') class uploadStudents(LoginRequiredMixin,View): context = {} def get(self,request): form = UploadStudentsForm() self.context['form'] = form return render(request,'libman/upload_student.html',self.context) def post(self, request): form = UploadStudentsForm(request.POST , request.FILES) data_set = Dataset() if form.is_valid(): file = request.FILES['file'] extension = file.name.split(".")[-1].lower() resource = ImportStudentsResource() if extension == 'csv': data = data_set.load(file.read().decode('utf-8'), format=extension) else: data = data_set.load(file.read(), format=extension) result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) if result.has_validation_errors() or result.has_errors(): messages.success(request,f'Errors experienced during import.') print("error", result.invalid_rows) … -
How to verify users email with token generator link for signup in django webapp
I am doing a web app in Django. I hardly tried to create a TokenGenerator for verifying the user's email to activate the user's account coming to the problem, 1) how to send the verification email to the user account while signup. while signup, users can receive a verification link email with a token generator 2) the user has to input the password at the time of account signup 3) After verifying the email user can log in to the respective page via their mail id and password 4) while login it should check whether an email is present in the DB (DB will be updated with user emails ) -
how to store variables in django cache db
i am making a cache db using the django cache module i configured it in my settings.py like this CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'my_cache_table', } } so in my something.py file example def function(): log=cache['default'] log["cal"]+=1 can i do this so that a variable like cal would be formed and it would increase every time i call that function -
run django related script in crontab
Hi in my local python interpreter I run ./manage.py shell < slack_application/slack_notifications.py in my activated venv and everything works... How can I do the same via a crontab that should work on my ubuntu server? I am trying: cd Django django_env/bin/activate ./manage.py shell < slack_application/slack_notifications.py) Any ideas? Thank you very much. -
Refresh UUID on model object save
so I have a model and I am using a UUID field. I just simply want to change the UUID(refresh the UUID) to a new UUID every time a model object is saved. import uuid from django.db import models class MyUUIDModel(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True) # other fields def save(self, *args, **kwargs): //refresh the uuid. what do i do here? super(MyUUIDModel, self).save(*args, **kwargs) -
How to show name of the foreign key field instead of its id?
I need to show the names of 'user_permissions' instead of their id's. Serializers.py : class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name', 'username', 'email','password','is_active', 'date_joined', 'groups', 'user_permissions') extra_kwargs = {'username' : {'read_only': True},'password': {'write_only': True}, 'is_active': {'read_only': True}, 'date_joined': {'read_only': True}, 'groups':{ 'read_only' : True} , 'user_permissions':{ 'read_only' : True} } Views.py: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer -
Iterate over a list of django forms, give each form its own div in template
I'm working on an app that lets restaurants/venues update their current state (i.e occupancy, or music type) I have a model called State and a ModelForm that corresponds. In my python view I've created a list of forms. Each form field is set with the existing value of a particular venue. I'm rendering a page where I'd like a user to see all of the venues they have, in its own div, that has the form from that list that corresponds. This way if they only want to update one field of a particular venue then they only have to set one field, instead of having a blank form and resetting everything. Currently all the preferences load correctly. However each Venue is showing the form and preferences for EVERY venue in its particular div. I can't workout out how to iterate. I've tried hardcoding setForms[0] and it throws an error pictures below show webpage with 4 venues (each in its own row), each venue div have all four forms models.py: class Venue(models.Model): owner = models.ForeignKey("User", on_delete=models.CASCADE) name = models.TextField(blank=False) rawAddress = models.TextField(blank=False) area = models.TextField(blank=True) locationPoint = models.PointField(srid=4326) objects = GeoManager() class State(models.Model): venue = models.ForeignKey("Venue", on_delete=models.CASCADE, related_name="states") venueType = … -
Django Rest framework GET request on db without related model
Let's say that we have a database with existing data, the data is updated from a bash script and there is no related model on Django for that. Which is the best way to create an endpoint on Django to be able to perform a GET request so to retrieve the data? What I mean is, that if there was a model we could use something like: class ModelList(generics.ListCreateAPIView): queryset = Model.objects.first() serializer_class = ModelSerializer The workaround that I tried was to create an APIView and inside that APIView to do something like this: class RetrieveData(APIView): def get(self, request): conn = None try: conn = psycopg2.connect(host=..., database=..., user=..., password=..., port=...) cur = conn.cursor() cur.execute(f'Select * from ....') fetched_data = cur.fetchone() cur.close() res_list = [x for x in fetched_data] json_res_data = {"id": res_list[0], "date": res_list[1], "data": res_list[2]} return Response({"data": json_res_data) except Exception as e: return Response({"error": 'Error'}) finally: if conn is not None: conn.close() Although I do not believe that this is a good solution, also is a bit slow ~ 2 sec per request. Apart from that, if for example, many Get requests are made at the same time isn't that gonna create a problem on the DB instance, e.g … -
checkboxes form from database and initials
Assume that we have some languages for our dictionary (which is a model and its name is Lang), English, 2. Spanish, 3. German These languages can be increased or decreased later on by the admin. I want the user to choose between them and save them in the User model. But a user previously chose some or all of them. So, How can I build a form that has the form grabbing the languages from the database and it has also the initial value of True for the chosen languages by the user, in the checkboxes?