Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using a DRF JSONField as a Serializer
I have a custom JSONField which I would like to use as a serializer. Serializers provide a bunch of extra functionality that you don't get with a Field. Serializers are Fields but not the other way around. As an example, consider a field which has some complex dynamic data and needs to be validated manually: from rest_framework.serializers import JSONField, Serializer class MetadataField(JSONField): def to_internal_value(self, raw_data): data = super().to_internal_value(raw_data) # lengthy validation logic which is calling other methods on the class return data class ItemSerializer(Serializer): metadata = MetadataField() To keep this field reusable and to prevent bloating the ItemSerializer class we move the logic out into its own MetadataField. However, as a consequence, we no longer have access to things like self.instance, nor can we directly instantiate this class like a serializer and pass it some data. Generating a dynamic schema is not an option, and I would like if at all possible to keep the validation logic out of ItemSerializer. -
Universal method to merge duplicate objects in Django
I want to write a universal class to merge duplicate entries in django reassigning all many-to-one and many-to-many references from old to new object. Something like this: def form_valid(self, form): new_object = self.model.objects.get(id=form.cleaned_data['inst'].id) old_object = self.model.objects.get(id=self.kwargs['pk']) for obj in old_object.machine_set.all(): obj.company = new_object obj.save(update_fields=['company']) for obj in old_object.contact_set.all(): obj.company = new_object obj.save(update_fields=['company']) for obj in old_object.partquote_set.all(): obj.company = new_object obj.save(update_fields=['company']) for obj in old_object.trip_set.all(): obj.company = new_object obj.save(update_fields=['company']) for obj in old_object.address.all(): new_object.address.add(obj) for obj in old_object.email.all(): new_object.email.add(obj) for obj in old_object.phone_number.all(): new_object.phone_number.add(obj) if not new_object.website and old_object.website: new_object.website = old_object.website new_object.save(update_fields=['website']) if not new_object.comments and old_object.comments: new_object.comments = old_object.comments new_object.save(update_fields=['comments']) return redirect(new_object.get_absolute_url()) But I don't want to hard-code it manually for all related fields. Instead I want to do something like this: def form_valid(self, form): new_object = self.model.objects.get(id=form.cleaned_data['inst'].id) old_object = self.model.objects.get(id=self.kwargs['pk']) for related_object in self.model._meta.related_objects: for obj in related_object.SOMEHOW_GET_QUERYSET(): // Assuming the field we are looking for is lower case model name SOMEHOW_GET_FIELD_FROM_SELF_MODEL = new_object obj.save(update_fields=['SOMEHOW_GET_FIELD_FROM_SELF_MODEL']) for related_object in self.model._meta.many_to_many: for obj in related_object.SOMEHOW_GET_QUERYSET(): new_object.SOMEHOW_GET_FIELD_FROM_RELATED_OBJECT.add(obj) Is it posssible to do something like that? -
How to create multiple models from a single endpoint w/ Django
I want to have an single endpoint that accepts a POST request and creates an "Order" that can be one of two types. The User should be able to submit an order (of either type) as JSON, and create a new Order. Behind the scenes, two models are created. One "Base Order" Model that describes some common characteristics, and one "Type A Order" or "Type B Order" that describes the characteristics specific to that order. The actual order types and their fields will be vastly more complicated so here are just described as A and B with a few charFields. The general idea though is that the same endpoint is used to create two models, a BaseOrder model, and a model of a type determined by the order_type field submitted. I think the conditional part of this (which order to make) should not be too difficult. But I'm unsure how to create two separate models from the same endpoint, even if it was always of the same type. Models: class BaseOrder(models.Model): name = models.CharField(max_length=80) timestamp = models.DateTimeField(null=False) class OrderType(models.TextChoices): TYPEA = "A", "Placeholder A" TYPEB = "B", "Placeholder B" order_type = models.CharField( max_length=16, verbose_name="Order Type", choices=OrderType.choices, ) class TypeAOrder(models.Model): a_field1 … -
How do I fix Django returning 'self' not defined NameError on queryset filtering of ModelChoiceField?
I have 2 models, Type and Measure. Each Measure object has a typeid ForeignKey field that refers to the id field of a Type object. Each Type is viewed on it's own page where the id is passed through URL. urls.py urlpatterns = [ path('type/<int:id>', views.type, name='type'), ] The view had been working with this as it is before I added the ModelChoiceField to the form. views.py def type(request, id): mytypes = Type.objects.all().values() mytype = Type.objects.get(id=id) mymeasures = Measure.objects.filter(typeid=id) template = loader.get_template('type.html') if request.method == 'GET': form = ConvForm(request.GET) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: if request.from_type != None: redir = f"/type/{id}" # create a form instance and populate it with data from the request: return HttpResponseRedirect(redir) # if a GET (or any other method) we'll create a blank form else: form = ConvForm(id) context = { 'form' : form, 'mytype': mytype, 'mytypes' : mytypes, 'mymeasures' : mymeasures } return HttpResponse(template.render(context, request)) It is once it imports the form that it runs into a problem with the following code. forms.py class ConvForm(forms.Form): from_value = forms.DecimalField(label='From Value', max_digits=256, decimal_places=255) from_measure = forms.ModelChoiceField(queryset=Measure.objects.none()) class __init__(self, … -
Django admin panel: select a group in many to many list
I have 3 models as follows: class ColorGroup(models.Model): name = models.CharField(max_length=255) class Color(models.Model): color_group = models.ForeignKey(ColorGroup) name = models.CharField(max_length=255) class Item(models.Model): colors = models.ManyToManyField(Color) For my project, I need to add/remove colors in the admin panel for my items. Currently I have to add them one by one. But in many occasion I want to set all the colors from a ColorGroup at once (and maybe select other colors also). Example: I want my item to be orange, yellow and all colors of group blue (including teal, navy blue etc.) Is there a way to display both colors and group of colors in the ManyToMany list, and if I select a Group it auto select all the colors of this group ? I checked this question but the smart_select doesn't seems to allow both color and group color selection. Edit: The solution I have in mind for now is to add a field 'color group' in item and let user select the group on another list. Then handle logic in the back end. But I would like to avoid adding complexity and redundancy to the DB -
Need to write some tests for OrderDetailView
Need to write test_order_details method to verify receipt of the order: 1)make sure that the order address is in the response body; 2)make sure that there is a promo code in the response body; 3)make sure that the response context is the same order that was created before the test (compare by primary key). This is model: class Order(models.Model): delivery_address = models.TextField(null=True, blank=True) promocode = models.CharField(max_length=20, null=False, blank=True) created_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.PROTECT) products = models.ManyToManyField(Product, related_name="orders") This is view: class OrderDetailView(DetailView): queryset = ( Order.objects .select_related("user") .prefetch_related("products") ) This is tests.py: from django.contrib.auth.models import User, Permission from django.test import TestCase from django.urls import reverse from .models import Order class OrderDetailViewTestCase(TestCase): @classmethod def setUpClass(cls): cls.user = User.objects.create(username='test', password='qwerty') permission_order = Permission.objects.get(codename='view_order') cls.user.user_permissions.add(permission_order) @classmethod def tearDownClass(cls): cls.user.delete() def setUp(self) -> None: self.client.force_login(self.user) self.order = Order.objects.create( delivery_address='ul Verona, d 13', promocode='SALE_123', user=self.user) def tearDown(self) -> None: self.order.delete() def test_order_details(self): response = self.client.get(reverse( 'shopapp:order_details', kwargs={'pk': self.order.pk}) ) self.assertContains(response, self.order.delivery_address) self.assertContains(response, self.order.promocode) I don't know how to make sure that the response context is the same order that was created before the test (compare by primary key). Can you help me please? -
Redmine returned internal error, check Redmine logs for details (Only from Webserver)
I build a Webinterface for Redmine for a better looking experience. Everything works just fine on the virtual development server from django. But when the application runs on my Webserver (IIS) the Python Redmine API seems to have a problem to establish a connection to Redmine. Redmine is installed on the same Server with the help of the Bitnami Redmine Stack. server = Redmine('http://10.0.121.245:81/redmine/', username='user', password="password") server.issue.create( ..... ) This code for the Python Redmine API works just fine on my virtual Server when building the Application, but when published on the Webserver the connection seems to be failing. The Redmine Logs do not show this error. For me it seems to be a problem with the url. Also tried with localhost, but still the same problem. Any idea why this is happening ? -
How to make a default value in ForeignKey using User
I was going through "Django for Beginners", there is a project that make posts with title, author and body fields, u can add posts via admin where in author field u choose either -- or the admin itself, what I'd like to do is if this field is not edited then then its value would be a string that i can pass (i. e. in that case 'anon') . I've found a way to make a default for ForeignKey but without models.User so how to do it in that case? from django.db import models from django.urls import reverse def anon(): return 'User.username="Anon"' class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( "auth.User", on_delete=models.CASCADE, default=anon ) body = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse("post_detail", kwargs={"pk": self.pk}) Firstly I've tried to plainly type in author = models.ForeignKey("auth.User", on_delete=models.CASCADE, default='anon'). Then to make a function that would return the desired string, then looked up models.User fields and found username field, tried to return it in anon() but only got SyntaxError: expression cannot contain assignment, perhaps you meant "=="? when entered makemigrations command -
How to merge two JSONField fields
Postgres allows merging/concatenating two JSONB fields into one. Quoting the relevant Postgres docs: jsonb || jsonb → jsonb - Concatenates two jsonb values. As far as I can see, the Django ORM does not provide an operator for this type of concatenation. django.db.models.expressions.Combinable does not have a || operator. django.contrib.postgres.search.SearchQueryCombinable has a || operator, but this class does not seem to apply here. -
Railways.app postgres database is too slow
DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', 'ENGINE': 'engine url', 'NAME': 'railway', 'USER': 'postgres', 'PASSWORD': 'pass', 'HOST': 'host', 'PORT': 'port', } } here is the code for the connection of postgress database to my django app it is feeling too slow. I don't know my even while developing my app(local server) it takes about 2sec to just start the server after every save. and even basic urls like of admin panel took 2sec each time. My plan of railways.app is developer plan. did i did something wrong? but as I switched to mine localone app becomes faster I am expecting it to be little faster. Even when in past in works with herku its faster then this. -
I want to return Subcategory (ManyToManyField to Category---another Class) with def __str__(self):
in the last line i want to return sub category it didn't show any error but it is not show as i am expecting it is showing like NEW ITEM--**Shop.Category.None** new arrival--**Shop.Category.None** Adidas Shoes blue color--**Shop.Category.None** class Category(models.Model): CHOICES = ( ('Accessories','Accessories'), ('Fashions','Fashions') ) class IndexProduct(models.Model): Title = models.CharField(max_length=50) Subcategory = models.ManyToManyField(Category) def __str__(self): return self.Title + '--' + str(self.Subcategory) -
React Django Google Sign In
I am trying to implement google sign in my Django rest react application. This is my front-end function that gets the access token and then sends it to the backend. const gLogin = useGoogleLogin({ onSuccess: tokenResponse => { axios.post('http://127.0.0.1:8000/api/auth/google/signin/', {token: tokenResponse.access_token}) .then(response => { console.log('Successfully logged in'); }) .catch(error => { console.error('failed to login'); }) }, }); This is my backend code for verifying the access token and then getting the user details from google. @csrf_exempt def google_signin(request): if request.method == 'POST': data = json.loads(request.body) token = data.get('token') print(token) if token is None: return JsonResponse({'error': 'Token is missing.'}, status=400) try: idinfo = id_token.verify_oauth2_token( token, requests.Request(), settings.GOOGLE_CLIENT_ID ) email = idinfo['email'] print(email) user = authenticate(request, email=email) if user is not None: login(request, user) return JsonResponse({'success': True}) else: return JsonResponse({'error': 'User does not exist.'}, status=404) except ValueError: return JsonResponse({'error': 'Invalid token.'}, status=400) else: return JsonResponse({'error': 'Invalid request method.'}, status=405) This is the error in the backend. Making request: GET https://www.googleapis.com/oauth2/v1/certs Starting new HTTPS connection (1): www.googleapis.com:443 https://www.googleapis.com:443 "GET /oauth2/v1/certs HTTP/1.1" 200 1577 Bad Request: /api/auth/google/signin/ Bad Request: /api/auth/google/signin/ HTTP 400 response started for ['127.0.0. I tried reworking the code many times but no use. Still the same error -
How to make that users of a certain group in Geonode, can only edit/delete the resources they have created
I am using geonode-project and I want to to create the following permissions for geonode. I have previously created the "Institution" group. An user of the Institution Group can only Edit/Delete the resources(Datasets, Maps, Documents, etc.), he/she have created. How can I do it? I also want to create an "Managers" group that can create/edit/delete all resources -
In django, how can I have two different methods for instantiating the same model?
I am building a system to register parts for manufacturing (for context: temperature sensors). As I'm dealing with many different subtypes of actual physical parts, I'm using django-polymorphic to define the models for the actual temperature sensors: class TempSensor(PolymorphicModel): """Abstract model for temperature sensors"""" part_number = models.OneToOneField(Part, on_delete=models.CASCADE) class TempSensorA1(TempSensor): calibration = models.CharField(max_length=1, choices=Calibration.choices) junction = models.CharField(max_length=1, choices=Junction.choices) def __str__(self): return f"A1-{self.calibration}{self.junction}" class TempSensorB1(TempSensor): calibration = models.CharField(max_length=1, choices=Calibration.choices) termination = models.CharField(max_length=1, choices=Termination.choices) def __str__(self): return f"B1-{self.calibration}{self.termination}" The Part model acts as a container for the TempSensor instances. This lets me assign a simpler consecutive part number and associate them with orders. class Part(models.Model): part_number = models.AutoField(primary_key=True) order = models.ManyToManyField(Order, through="OrderDetail") production_notes = models.TextField(blank=True) sales_notes = models.TextField(blank=True) class Meta: ordering = ["part_number"] Right now, I have the django admin interface working as expected. When adding a new Part instance, I can add a TempSensor, select the correct child type and input the fields manually, all through an inline. This works great when working from raw specifications. However, since model codes are often provided directly, I also need to be able to instantiate TempSensor directly from the model code. To solve this, I've created a create_from_model_code method that takes the model code, … -
you need to register and authorize on django. How to add models and views
On the main page, I made a pop-up window with a registration form. How to attach registration to it now, I searched everything, but found only registration through a separate page. ` <button type="button" class="btn btn-light" data-bs-toggle="modal" data-bs-target="#staticBackdrop1">Log In</button> <button type="button" class="btn btn-dark" data-bs-toggle="modal" data-bs-target="#staticBackdrop">Sign Up</a> </div> </div> </nav> <!-- Modal sign up--> <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content rounded-4 shadow"> <div class="modal-header p-5 pb-4 border-bottom-0"> <!-- <h1 class="modal-title fs-5" >Modal title</h1> --> <h1 class="fw-bold mb-0 fs-2">Sign up for free</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body p-5 pt-0"> <form class="" method="POST"> {% csrf_token %} <div class="form-floating mb-3"> <input type="email" class="form-control rounded-3" id="floatingInput" placeholder="name@example.com"> <label for="floatingInput">Email address</label> </div> <div class="form-floating mb-3"> <input type="password" class="form-control rounded-3" id="floatingPassword" placeholder="Password"> <label for="floatingPassword">Password</label> </div> <button class="w-100 mb-2 btn btn-lg rounded-3 btn-primary" type="submit">Sign up</button> <small class="text-muted">By clicking Sign up, you agree to the terms of use.</small> <hr class="my-4"> <h2 class="fs-5 fw-bold mb-3">Already have an account? <a type="button" class="btn btn-link fs-5 fw-bold mb-2 " data-bs-toggle="modal" data-bs-target="#staticBackdrop1"> Log in</a></h2> </form> </div> </div> </div> </div>` -
How to set up types in graphene-django project?
After upgrading django graphql project reqirements to latest django (4.1.7) and latest graphene (3.2.2) following error is displayed: raise cls(f"{self.name} fields cannot be resolved. {error}") from error TypeError: Query fields cannot be resolved. Argument type must be a GraphQL input type. Does anyone facing such issue and has idea how to get rid of it? I tried to change argument type but it didn't help. Error is still displayed (output type instead of input but still does not work). -
Django signals and proxy models
From what I tested, if I have a model (Vehicle) and 2 proxy models (Car and Bike, proxies of Vehicle) and I want to trigger a post_save signal, the signal will be triggered only by the save operation on the Vehicle model. I was expecting the signal to be triggered by the save operation also for Car and Bike because it's the same db table. Does anyone knows where I can find an explanation for this behavior? -
Problems writing "Add to wishlist" function
So I've been stuck on the issue of now really knowing how to write an add to wishlist function. I've been battling it in my head for 10 hours as I'm unsure how to get a product to the wishlist and I'm wondering how you guys would write the whole function of it. I know that this is not a specific issue, but I'm kind of new to this and just trying to learn. Please do tell if I'm missing to hand you some information. views.py def all_products(request): """ A view to show all products, including sorting and search queries """ products = Product.objects.all() query = None categories = None sort = None direction = None if request.GET: if 'sort' in request.GET: sortkey = request.GET['sort'] sort = sortkey if sortkey == 'name': sortkey = 'lower_name' products = products.annotate(lower_name=Lower('name')) if sortkey == 'category': sortkey = 'category__name' if 'direction' in request.GET: direction = request.GET['direction'] if direction == 'desc': sortkey = f'-{sortkey}' products = products.order_by(sortkey) if 'category' in request.GET: categories = request.GET['category'].split(',') products = products.filter(category__name__in=categories) categories = Category.objects.filter(name__in=categories) if 'q' in request.GET: query = request.GET['q'] if not query: messages.error(request, "You didn't enter any search criteria!") return redirect(reverse('products')) queries = Q(name__icontains=query) | Q(description__icontains=query) products … -
Django AWS Secrets Manager password authentication failed
I have a working database connection with AWS Secrets Manager storing the username and password. Below is my implementation get_secrets_manager.py import os import json import boto3 import botocore.session from botocore.exceptions import ClientError from aws_secretsmanager_caching import SecretCache, SecretCacheConfig def get_rds_credentials(): secret_name = os.environ.get( "RDS_Secret", "rds!cluster-552a7c8b-8e0f-40e6-96f1-91a124066c58" ) region_name = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") session = boto3.session.Session() client = session.client( service_name="secretsmanager", region_name=region_name, ) cache_config = SecretCacheConfig() cache = SecretCache(config=cache_config, client=client) secret = cache.get_secret_string(secret_name) rds_credentials = json.loads(secret) os.environ['POSTGRES_USER'] = rds_credentials['username'] os.environ['POSTGRES_PASSWORD'] = rds_credentials['password'] return rds_credentials settings.py import environ from apps.utils.get_secrets_manager import get_rds_credentials get_rds_credentials() env = environ.Env() DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": env.str("POSTGRES_DB"), "USER": env.str("POSTGRES_USER"), "PASSWORD": env.str("POSTGRES_PASSWORD"), "HOST": env.str("POSTGRES_HOST", default="postgres"), "PORT": 5432, }, } It works initially but after a few days it will throw an authentication failed error. How to solve this? I am expecting either an auto-rotation mechanism or a continuous connection from my Django to DB(despite password rotation) but neither seems to be the case -
choose option in django fetching from different django application
i am new to djano and working on an Django project where I have to put categories from different application like I have two application product application - Here will manage my products and want t drop down, where I want to show the categories created in another application. 2 category application - here I am creating the category with its code please let me know how I can access the category application in product application how to save the category in database note - I am not using django form.* please let me know the steps by which I can user to complete this task. need to know about the html part also I have implemented these things in my code I model class I have create class(model:Model): choose_category={ ('g', "Jeans"), ('p', "pant"), product_category = model.charFiel(choose=chooose_category, default = 'g') error I am receiving a null value from the html -
Django "Unknown column 'userdata.password' in 'field list'" >> fix WITHOUT deleting existing table?
I have a table that is now called "userdata" in an AWS RDS mysql database. In a past migration, the table had a different name, "users". Now, with the new name, I cannot access the data in the table. I get the error >> 1054, "Unknown column 'userdata.password' in 'field list'". Other Stack Overflow posts suggest dropping the table and starting over to fix the problem. Is there a way to fix this problem without dropping the table? Here is my user model, in which I specify the table name "userdata": import uuid from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(_("email address"), unique=True) is_premium = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) plan_signup_date = models.DateTimeField(null=True, blank=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) ## default inclusions: id, password, last_login, is_superuser, groups, user_permissions USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() class Meta: db_table = "userdata" def __str__(self): return self.email Thanks. -
How to show several objects with for loop in get_context_data
I have requests_cache and i want to show parsed info from json on my page with get_context_data But it shows only first dict with values and if i place context after for loop it shows second one how to fix that? views.py def get_context_data(self, *, object_list=None, **kwargs): context = super(ShowProjectBudgetList, self).get_context_data(**kwargs) session = requests_cache.CachedSession('project_budget_cache') url = config('REPORT_PROJECT_BUDGET') response = session.get(url=url, auth=UNICA_AUTH).json() for item in response: my_js = json.dumps(item) parsed_json = ReportProjectBudgetSerializer.parse_raw(my_js) obj = parsed_json.ObjectGUID context['response_json'] = obj return context -
Im getting this error while working in javascript ... Uncaught TypeError: $(...).popover is not a function
When I try to initialize popovers, I am getting the error 'Uncaught TypeError: $(...).popover is not a function.' I have included the Bootstrap 5 links and jquery link, but for some reason, it is still not working. I am unsure why this error is occurring and would appreciate any guidance on how to resolve this issue. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js" integrity="sha384-mQ93GR66B00ZXjt0YO5KlohRA5SY2XofN4zfuZxLkoj1gXtW8ANNCe9d5Y3eG5eD" crossorigin="anonymous"></script> **And this is my Html popover button ** <button type="button" class="btn btn-secondary" id="popcart" data-bs-container="body" data-bs-toggle="popover" data-bs-html="true" data-bs-placement="bottom"> Cart(<span id="carting">0</span>)</button> And this is how i initialize my popover //initialize popovers $("#popcart").popover(); updatePopover(bag); function updatePopover(bag) { console.log('We are inside updatePopover'); var popStr = ""; popStr = popStr + "<h5> Cart for your items in my shopping cart </h5><div class='mx-2 my-2'>"; var i = 1; for (var item in bag) { popStr = popStr + "<b>" + i + "</b>. "; popStr = popStr + document.getElementById('name' + item).innerHTML.slice(0, 19) + "... Qty: " + bag[item] + '<br>'; i = i + 1; } popStr = popStr + "</div>" console.log(popStr); document.getElementById('popcart').setAttribute('data-bs-content', popStr); $('#popcart').popover('show'); } When I click on the + (plus) or - (minus) button to update my cart, the popover that shows all … -
Django broken pipe during authentication form post
I am trying to develop a website with Django 4, and I am puzzled by my authentication system behaviour. I am trying to develop the sign up feature, and it has not worked yet, my auth_user table is still empty. When I try signing up using Firefox, the POST request generates this error : Broken pipe from ('127.0.0.1', 52245) - when retrying, the numbers inside the parenthesis change, and I don't know the meaning of these and couldn't find it. My request seems to not be handled as the database stays empty. When I try the same thing using Edge, the database stays empty too, but the POST request generates no error. I have read that broken pipe errors were errors on the client part (the client closes the connection without waiting for the server's response), but I can't see where I need to alter things to solve that... I have also read about this happening when using ajax requests, and the way to solve it was to make the input a button type and not a submit type, but this is not an ajax request. I tried doing that because you never know, but having a button instead of … -
How to parse and show info in template with requests_cache
I have several general questions about requests_cache and how is it working and how can i use that How can i get json from 3rd party and parse that in my template? I have some information from api that i dont need to write in model in db and i want just to parse that but need just to show that in parsed info in template views.py def customer_view(request): session = requests_cache.CachedSession('project_budget_cache') session.get('http://someurl.com/api') return render(request, 'customer/customer_home.html', {'context': session}) I can get request with that but i actually dont know how to show my json in template {{ context }} cant help there Another question: How can i synch request every 5 min? Last question: How can i avoide problems with 3rd party api? Like if api is closed or they have problems and i cant get json how can i use previous request that was working? I mean if they have problems and cant accept requests rn i need to use request that was made 5 mins ago