Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to make non-serializable object available within a session
My danjgo/python project consists of db-backed models and non-db-backed models. The non-db-backed models get data from the db-backed models and do some heavy computational stuff and they have a state. At the moment for every request the non-db-backed models get newly instantiated and I have to re-calculate everything. This makes everything very slow... How can I save the non-db-backed models to a django session or something similar? Its not feasable to serialize these objects (and it would also be very time consuming to serialize them or deserialize them). Therefore I cannot use the request.session dictionary. It also makes no sense to make these models db-backed, because their state depends on other API-Calls, current date, time and user input. I do not want them to be saved "forever". I want to use them just in the session to save computing time. I use the django.contrib.auth.models. Best would be, that I could add somehow these "expensive" models to my current user. I had a look into the django cache. But the cache is "static". If I set an object into the cache at the beginning of the function and change it afterwards, these changes are not reflected in the cache. Maybe I … -
bulk_upsert update based on existing value
I need to bulk_upsert some data set. But one field should be calculated based on the existing value that is already present. For simplicity, I have used the field IN_updated_at to update with the same value that already exists in the DB. i.e F('IN_updated_at') from django.db.models import F for i in some_list: sync_list.append( { 'id':'some_id', 'last_synced_time': Now(), 'IN_updated_at': F('IN_updated_at') } ) MyModel.objects.bulk_update([MyModel(**kv) for kv in sync_list], ['last_synced_time', 'IN_updated_at']) But I get the following error: TypeError: expected string or bytes-like object I also did the same with a JSON field and I get the following error: TypeError: Object of type 'F' is not JSON serializable How can I get this work? -
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. Django 3.1.4
I'm trying to learn about Django and REST framework and starting customize my model but went I use makemigration it show this error can someone lease help me out. This is my models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.forms import ModelForm, forms, TextInput class AccountManager(BaseUserManager, PermissionsMixin): def create_user(self, username, email, password = None): if username is None: raise TypeError('Username cannot be empty') if email is None: raise TypeError('Email cannot be empty') user = self.model(username = username,email = self.normalize_email(email)) user.set_password(password) user.save() return user def create_super_user(self, username, email, password = None): if password is None: raise TypeError('Password cannot be empty') user = self.create_user(username,email,password) user.is_super_user = True user.is_admin = True user.save() return user class Account(AbstractBaseUser): username = models.CharField('settings.AUTH_USER_MODEL', max_length=300, unique=True) email = models.EmailField(max_length=300, unique=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False)# only for superuser created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = AccountManager() def __str__(self): return self.email And this this the error raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. Thanks! -
Showing errors with LoginView in Django
I have a problem with displaying errors on the template for login page. I am using the Login built in view and I made a custom form which inherits from AuthenticationForm and I tried to override the clean() method but if the username or password is not correct is not displaying any ValidationErorr message. Any help? I created a custom view because I need to inherit from a custom mixin for some restrictions. my view: class UserLoginView(IsAuthenticatedMixin, LoginView): template_name = 'home/auth/login.html' authentication_form = UserLoginForm my form: class UserLoginForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput()) password = forms.CharField(widget=forms.PasswordInput()) def clean(self): cleaned_data = super().clean() username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username is not None and password: login = authenticate(self.request, username=username, password=password) if login is None: raise ValidationError('The username or password are incorrect') return self.cleaned_data url: path('auth/login/', UserLoginView.as_view(), name='login'), my template: {% extends 'home/auth/base.html' %} {% load widget_tweaks %} {% block content %} <!-- Outer Row --> <div class="row justify-content-center"> <div class="col-xl-10 col-lg-12 col-md-9"> <div class="card o-hidden border-0 shadow-lg my-5"> <div class="card-body p-0"> <div class="row"> <div class="col-lg-6 d-none d-lg-block bg-login-image"></div> <div class="col-lg-6"> <div class="p-5"> <div class="text-center"> <h1 class="h4 text-gray-900 mb-4">Welcome Back!</h1> </div> <form class="user" method="POST"> {% csrf_token %} <div class="form-group"> {% for error in form.non_field.errors … -
Trying to pass a foreign key of my model into URL for dynamic routing
I have 3 models, a custom user model (using AbstractUser - User/Brand models) and a Message model: class User(AbstractUser): is_brand = models.BooleanField(default=False) is_influencer = models.BooleanField(default=False) class Brand(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name="brand_info") email = models.EmailField() brand_name = models.CharField(max_length=100, blank=True) class Message(models.Model): recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='recipient') sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') message_content = models.TextField() send_time = models.DateTimeField(auto_now_add=True) I have a view where I want to load up all the messages associated with a particular Brand, and this page will also have the attribute (from Brand model) as a dynamic URL parameter. Here's my current code for views.py: def conversation_view(request, username): messages = Message.objects.filter(Q(message__sender=username) | Q(message__recipient=username)).order_by('send_time') return render(request, "conversation.html", { 'messages': messages }) And here's my urls.py: urlpatterns = [ path('conversation/<username>/', views.conversation_view, name='conversation_view') ] When I try and load up a page with the appropriate conversation/ URL, I get the following error message: invalid literal for int() with base 10: 'username' I'm not sure why Django is expecting an int() here? Is it because I'm using sender/recipient from Message model in my view, which are both foreign keys? -
How to save a foreignkey field while saving a HTML form in Django?
I want to save a html form data into django model but it has a foreign key field from another model. How can I save a form which has FK field?? My models: class Dish(models.Model): title =models.CharField(max_length=200) description =models.TextField(blank=True) price =models.IntegerField() photo_main= models.ImageField(upload_to="photos/%Y%m%d/") photo_1= models.ImageField(upload_to="photos/%Y%m%d/", blank= True) photo_2= models.ImageField(upload_to="photos/%Y%m%d/", blank= True) def __str__(self): return self.title class Order(models.Model): dishorder= models.ForeignKey(Dish,null=True,on_delete=models.CASCADE) name = models.CharField(max_length=200,blank=True) email = models.CharField(max_length=100,blank=True) phone = models.CharField(max_length=100,blank=True) quantity =models.IntegerField(blank=True) def __str__(self): return self.name My views: def order(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] quantity = request.POST['quantity'] order= Order( name=name, email=email, phone=phone, quantity=quantity) order.save() messages.success(request, "Your order has been submitted.") return render(request,"dishes/order.html") My urls: urlpatterns = [ path("dish",views.dish,name="dish"), path("dish/<pk>",views.dishsingle,name="dishsingle"), path("order",views.order,name="order"), ] My template dishes/order.html <form method="POST"> {% csrf_token %} <div> <label for="name">Name:</label> <input type="text" name="name" class="form-control" required> </div> <div> <label for="email">Email:</label> <input type="email" name="email" class="form-control" required> </div> <div> <label for="phone">Phone:</label> <input type="number" name="phone" class="form-control" required> </div> <div> <label for="quantity">Quantity:</label> <input type="number" name="quantity" class="form-control" required> </div> <hr> <input type="submit" value="MAKE AN ORDER"> </form> While submitting this html form, I would like the foreignkey field dishorder to be saved on the backend as well. When I check the admin page, order is saved but without … -
adding dropdown list for django
I am learning Django right now and I try to add a dropdown list to the website. The website right now will show a list of games. The dropdown list has different platforms and I want the list change after the user selects one platform. What should I do? At form.py: class platformSelectForm(forms.Form): platformsList = ( ('all', 'Please Select'), ('NS', 'Nintendo Switch'), ('PS4', 'PlayStation4'), ('PS5', 'PlayStation5'), ('XBO', 'Xbox One'), ('XS', 'Xbox Series S/X'), ); platforms_Select = forms.ChoiceField(widget = forms.Select, choices = platformsList, required = False); At view.py: class showGameLists(TemplateView): template_name = "showList/home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs); platformSelect = platformSelectForm(self.request.POST or None); context['platformSelect'] = platformSelect; games = getGames(nowDay.year, nowDay.month, platforms); context['games'] = games; context['year'] = nowDay.year; context['month'] = calendar.month_name[nowDay.month]; context['prevMonth'] = prevMonth(nowDay); context['nextMonth'] = nextMonth(nowDay); return context At urls.py: from django.urls import path; from .views import showGameLists; urlpatterns = [ path('', showGameLists.as_view(), name='home') ] At home.html: <form method = 'POST' action = '/'> {% csrf_token %} {{ platformSelect.as_p }} <input type='submit' value='Submit' /> </form> {% for game in games %} <div> <span><h2>{{game.0}}</h2> <p>Release Date: {{ game.1 }}, Metacritic: {{ game.3 }}</p> <p>Platform: {% for platform in game.2 %}{{ platform }}/{% endfor %}</p> {% if game.4 %} <img src={{game.4}} width="367" … -
Django Rest Framework - ManyToMany List of IDs disappearing
I have recently upgraded my Django to 3.1.5 and my DRF to 3.12.2, and something in my application has stopped working. I have the following structure in my models and serializers (simplified): Models: class A(models.Model): name = models.CharField(max_length=50) class B(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) class C(models.Model): b = models.ForeignKey(B, on_delete=models.CASCADE) class D(models.Model): c = models.ForeignKey(C, on_delete=models.CASCADE) name = models.CharField(max_length=50) items = models.ManyToManyField(Item,blank=True) class Item(models.Model): name = models.CharField(max_length=50) Serializers: class DSerializer(serializers.ModelSerializer): class Meta: model = models.D fields = ('name','items') class CSerializer(serializers.ModelSerializer): d_set = DSerializer(many=True, read_only=False) class Meta: model = models.C fields = ('d_set',) class BSerializer(serializers.ModelSerializer): c_set = CSerializer(many=True, read_only=False) class Meta: model = models.B fields = ('c_set',) class ASerializer(serializers.ModelSerializer): b_set = BSerializer(many=True, read_only=False) class Meta: model = models.A fields = ('name','b_set') def createD(d_set, c): for d in d_set: items = d.pop('items') newD = models.D(c=c,**d) newD.save() for item in items: newD.add(item) def createB(self, b_set, a): for b in b_set: newB = models.B(a = a) newB.save() c_set = b.get("c_set") for c in c_set: d_set = c.pop("d_set") newC = models.C(b = b, **c) newC.save() self.createD(d_set, c) def create(self, validated_data): b_set = validated_data.pop('b_set') newA = models.A(**validated_data) newA.save(); self.createB(b_set,newA) The issue is that d.items in createD() is empty, even when data is passed in the serializer. … -
Make it so the information the user provided in input field can be modified and redisplayed with Django
I am currently trying to make a password manager with Django. The code for it can be found here, and the version of the code I'm referencing is when commit id "39dd9110a8aa098399af0511a963e447a0d45afb" was pushed to GitHub. All code referenced will be in the django app titled "main". The home page looks like this: 2 This is what the page in question looks like: 3 (In the project, this page is displayed after clicking the text "GitHub") In the input area, the user provides their master password, and then clicks the submit button. I would like to retrieve that password and alter it(I will use it to decrypt their other passwords, but I do not need help decrypting, I need help altering it). And after altering it, I would like to display the altered text on the page. In the file named "detailed_view.html", the code containing the input field is wrapped in form tags. Code: <form method = "POST"> {% csrf_token %} <h1 style="display:inline; color: #4CAF50">Password</h1> <input type="password" name="Password" style="display:inline;"> <input style="position: absolute;left: 50%;display:block;" type="submit" value="Submit"> </form> After the user clicks "submit", the information is brought to the view() function in views.py (line 64): @login_required def view(request, pk): if request.method =="POST": … -
How can I update a many to many field in Django
I am trying to update a many to many field button when a user clicks a button The Payment model is to allow users to submit their receipts to be reimbursed. Each Payment has a "many to many" field named status. Currently, there are only two statuses a payment can have "complete" or "incomplete". When a user submits a payment the default is incomplete, and when the company issues a check to reimburse the user, the company needs to be able to click a button that will update the payment to 'complete'. To get a better idea of what this looks like, the HTML page looks like this. The Page My models.py from django.db import models from django.contrib.auth.models import User import uuid from django.urls import reverse # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return f'{self.name}' class Status(models.Model): type = models.CharField(max_length=100) def __str__(self): return f'{self.type}' class Payment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) amount = models.DecimalField(max_digits=14, decimal_places=2) receipt_img = models.FileField(default='default.jpg', upload_to='receipt_pics') author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) type = models.ManyToManyField(Category) time_posted = models.DateTimeField(auto_now_add=True) description = models.TextField(null=True) status = models.ManyToManyField(Status) def __str__(self): return f'{self.id} Contribution' def get_absolute_url(self): return reverse('contrib-home') The button that sends the request in payment_detail.html <a href="{% … -
Using DRF serializer to add custom details to multiple models
Suppose I have three models model A : class A(models.Model): field1 = models.CharField(max_length=100) field2 = models.CharField(max_length=255) class B(models.Model): field1 = models.ForeignKey(A, on_delete=models.CASCADE) field2 = models.FloatField() class C(models.Model): field1 = models.CharField(max_length=200) field2 = models.BooleanField(default=False) Now I want to update C based on values that I input in models A and B. Currently, I am writing pretty lengthy views and violating DRY principle by using the same logic over and again for any new view I write Currently, the serializer that I am using are simple model serializers. So basically, I have thick views and thin views. -
Copy value of html element in django (forms) template
django form with ChoiceField (1,2,3)--> {{Choices.sollicitanten}} django form with ChoiceField (1,2,3) -->{{ form.vacature_contract }} the choice options of both fields are the same 1,2,3 What i want is when i select for example, choice 1 in choices.sollicitanten it wil copy this choice to field {{form.vacature_contract}} so that the choice is this field is also 1. <td class="tg-0lax">{{ Choices.sollicitanten}}</td>. //and i have <td name="vacature_doel" class="tg-0lax">{{ form.vacature_contract }}</td> //and in html function FillForm(f) { { f.vacature_doel.value = f.vacature_bron.value; f.sollicitanten_doel.value = f.sollicitanten_bron.value; } } </script> //when i hit the submit button the function is run (onclick=FillForm). //the code above does not seem to do much..what is going wrong. -
Django dumpdata in .json collides in UTF-8 problem
I archived migrations in .json file. (venv) D:\scraping_service>python manage.py dumpdata scraping > scraping.json PyCharm informs that "File was loaded in the wrong encoding: 'UTF-8'" And Cyrillic symbols are not displaying. How to deal with this, if, in theory, UTF-8 is the right encoding for Cyrillic symbols? -
merge two id data in python
I want to merge two different id conversation data. I tried something like this below but didn't got helpful, If anybody could help me for what i exact want to achieve would be much appreciated. thank you so much in advance. output result: "data": [ { "id": 13, "conversation": [ { "id": 31, "from_user": "shopowner", "to_user": "carowner", "message": "hello", } ], }, { "id": 14, "conversation": [ { "id": 32, "from_user": "carowner", "to_user": "shopowner", "message": "hey", } ], } ] expected result: "data": [ { "conversation": [ { "id": 31, "from_user": "shopowner", "to_user": "carowner", "message": "hello", }, { "id": 32, "from_user": "carowner", "to_user": "shopowner", "message": "hey", } ], }, ] what i tried is: for record in data: data1 = str(record['conversation']) data2 = str(record['id']) from itertools import chain all_results = list(chain(data1,data2)) sort_data = all_results.sort(key=lambda x: x["created_on"], reverse=True) main_data = [x for x in record['conversation']] print(main_data) If anybody could help me for what i exact want to achieve would be much appreciated. thank you so much in advance. -
Call a particular function of Class based view Django from urls.py
I have this views.py where I've implemented Class based views, but let's say I want to call a function get_featured_products when the url is https://localhost:8000/featured_products. What sould my urls.py look like to call the get_features_products function? from django.shortcuts import render from rest_framework import views from rest_framework.response import Response from .models import * from .serializers import * # Create your views here. class ProductView(views.APIView): model= Product serializer = ProductSerializer def get(self,request): qs = self.model.objects.all() serializer = self.serializer(qs, many=True) return Response(serializer.data) def post(self,request): serializer = self.serializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.error_messages()) def put(self,request,pk): product = Product.objects.get(id=pk) serializer = self.serializer(instance=product, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.error_messages) def get_featured_products(self,request): #some code here return None How should I refer to get_featured_products in my urls.py -
How to display Console output or progress bar in Django fronted html?
In my python Django project, I have some background process and it will take 2 to 3 minutes for complete. in between the user close the browser or tab, the process will be stopped. So i am trying to display the console out put (same as " print() ") in front end HTML pages on real time or show a Progres bar with Live status. kindly advise me how to do this. (I have tried with Django Messages and JavaScript DOM based on change Text functions. but it need to wait until complete all the process to return the function or pass the data via context, so that method not success in my case.) -
dropdown select list for django
I am learning Django right now and I try to add a dropdown list at the website and the page will change after users submit their selection. At form.py: class platformSelectForm(forms.Form): platformsList = ( ('all', 'Please Select'), ('NS', 'Nintendo Switch'), ('PS4', 'PlayStation4'), ('PS5', 'PlayStation5'), ('XBO', 'Xbox One'), ('XS', 'Xbox Series S/X'), ); platforms_Select = forms.ChoiceField(widget = forms.Select, choices = platformsList, required = False); At view.py: class showGameLists(TemplateView): template_name = "showList/home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs); platformSelect = platformSelectForm(self.request.POST or None); context['platformSelect'] = platformSelect; At urls.py: from django.urls import path; from .views import showGameLists; urlpatterns = [ path('', showGameLists.as_view(), name='home') ] At home.html: <form method = 'POST' action = '/'> {% csrf_token %} {{ platformSelect.as_p }} <input type='submit' value='Submit' /> </form> right now, I can show the list and submit button. But I try lots of ways to get the value from the drop list, but it also wrong me: [17/Jan/2021 11:15:29] "POST / HTTP/1.1" 405 0 Method Not Allowed (POST): / Method Not Allowed: / what show I do? Thank you. -
Is this a circular import?
(follow up to: The included URLconf 'appName.urls' does not appear to have any patterns in it ) My site project directory looks like: (cryptocurrency, cryptoboard, cryptousers, frontend, leads, polls are apps). I think that: setup_debug_table.py(cryptocurrency): import random from datetime import timedelta from django.utils.datetime_safe import datetime from django.utils.timezone import now from .coins_constants import NO_OF_DAYS, NO_OF_HOURS, coins_ids from .models import Currency, Transaction, DebugConf from cryptoboard.cryptousers.models import CryptoUser def init_debug_tables(): # Check if debug table has already been initialized debug_conf = DebugConf.objects.all() if debug_conf.exists(): return # Clear tables CryptoUser.objects.all().delete() Currency.objects.all().delete() Transaction.objects.all().delete() specifically, line: from cryptoboard.cryptousers.models import CryptoUser is what's causing the error (CryptoUser is a model in a different app (cryptousers)), somewhat similar to this answer. models.py, on the other hand, looks fine: models.py(cryptocurrency) from django.db import models class DebugConf(models.Model): is_setup = models.BooleanField(default=False) debug_setup_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.is_setup class Currency(models.Model): currency_name = models.CharField(max_length=100, unique=True) currency_value = models.FloatField() currency_value_in_dollars = models.FloatField() currency_value_in_dollars_date = models.DateTimeField() def __str__(self): return self.currency_name class Transaction(models.Model): transaction_type = models.CharField(max_length=200) transaction_amount = models.FloatField() transaction_date = models.DateTimeField(auto_now_add=True) transaction_currency = models.ForeignKey(Currency, on_delete=models.CASCADE) transaction_buyer = models.ForeignKey('cryptousers.CryptoUser', related_name='transaction_buyer', on_delete=models.CASCADE) transaction_seller = models.ForeignKey('cryptousers.CryptoUser', related_name='transaction_seller', on_delete=models.CASCADE) def __str__(self): return self.transaction_currency Stack trace: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: … -
Django orm on apple m1
I'm trying to get concrete number of records in django model with 1m+ records through python manage.py shell using docker on apple m1 machine. Query: Model.objects.all()[:200000] But shell fails with message Killed. On machine with linux everything works fine. Any idea? -
Django doesn`t create locale files
I'm new at Django and can't solve the problem. I wanna realize multi-language on my django project but when I type django-admin makemessages -l ru, Django doesn`t create locale folder with files in it. I did everything according to the documentation. Maybe my English is bad. This is my settings from django.utils.translation import gettext_lazy as _ LANGUAGE_CODE = 'ru' USE_I18N = True LANGUAGES = [ ('ru', _('Russian')), ('uz', _('Uzbek')), ] This is views.py file from django.utils.translation import gettext as _ def index(request): phone = _('Welcome') return HttpResponse(phone) But in header.html (layout file) django translate one word, "Home" to "Начало" <li><a href="{% url 'index' %}" style="font-size: 18px;">{% trans "Home" %}</a></li> Thank you a lot -
Django RestFramework IsOwnerOrReadOnly
I create my permission class for everyone can read object and only admin create object. But when i log out and try to create object, permission class allowing me. What am i missing? models.py class Book(models.Model): title = models.CharField(max_length=20) content = models.TextField() page = models.IntegerField() views.py class BookAPIView( mixins.CreateModelMixin, generics.ListAPIView): permission_classes = [IsAdminOrReadOnly] serializer_class = BookSerializer queryset = Book.objects.all() def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) permissions.py class IsAdminOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method == 'GET': return True return request.user.is_staff -
Testing a query parameter in django restframework
I am testing a query parameter in djnago restframework to retrieve the detail of an object. The query works in the browser but not the test. I think I am not calling the response correctly with: response = self.client.get(reverse('quote-requests:get-calculator-detail', kwargs={'calculator_code': self.calc1.calculator_code})) the apps urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('api/v1/quote-requests/', include('quote_requests.urls')), ] which includes the quotes.urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter from quote_requests import views router = DefaultRouter() router.register('get-calculator', views.CalculatorCodeDetailViewSet, basename='get-calculator') app_name = 'quote-requests' urlpatterns = [ path('', include(router.urls)), ] The viewset is: class CalculatorCodeDetailViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = CalculatorCodeSerializer lookup_field = ('calculator_code') def get_queryset(self): return ( Calculator.objects.filter( calculator_code = self.request.query_params.get('calculator_code',) ) ) The CalculatorCodeSerializer is: class CalculatorCodeSerializer(serializers.ModelSerializer): class Meta: model = Calculator fields = ( 'name', 'calculator_code', ) The test is: def test_retrieving_calculator_detail_with_calculator_code(self): ''' test retrieving detail of a calculator ''' self.calc1 = Calculator.objects.create( name = "Calculator 1000", calculator_code = "HH1000", ) response = self.client.get(reverse('quote-requests:get-calculator-detail', kwargs={'calculator_code': self.calc1.calculator_code})) serializer = CalculatorCodeSerializer(self.calc1) self.assertEqual(response.data, serializer.data) This yields the error: Traceback (most recent call last): File "/app/quote_requests/tests/test_calculators_api.py", line 149, in test_retrieving_calculator_detail_with_calculator_code self.assertEqual(response.data, serializer.data) AssertionError: {'detail': ErrorDetail(string='Not found.',[14 chars]nd')} != {'name': 'Calculator 1000', 'calculator_cod[368 chars].25'} When checking the browser link: http://localhost:8000/api/v1/quote-requests/get-calculator/?calculator_code=HH1000 This works but test … -
Replace image src path using span
Is there any way how to replace the path location using span or etc. that comes from the Jquery, or is there any shorcut in Django?, Currently as you can see I'm trying to override the path that comes from my jquery src="/media/<span id=image></span>" It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance Jquery $(document).on('click', 'a[data-role=show_scanned]', function(){ let csrf = $('input[name=csrfmiddlewaretoken]').val(); var path = $(this).attr('id'); var assign = $("#image").html(path); $("#scanned_show").modal('show'); }); html retrieve <img class="card-img img-fluid mb-1" src="/media/<span id=image></span>" alt="Card image cap" style="width: 900px;height: 600px;"> -
How do I clear previous AJAX response data (NOT html/form data)? - Django/AJAX
I've built a Django app that submits an AJAX post request to my database. The initial post request works fine, but every previous request is also returned after the first response. Bottom line: Is there any way to clear the previous AJAX request/responses? Here's the first response when I start my server and submit my first request (the request is for pk:1): MedInput page loaded (index):46 Med Input Form Submitted (index):49 csrfmiddlewaretoken=i889gLsqdY9glqI59wRXLTOVehz9Lmp1i5IRikOsgvrGdBD9OpISolDrJ8pqJDmV&input_meds=lisinopril (index):53 (index):60 [{…}] (index):61 0: {model: "medrec_app.medication", pk: 1, fields: {…}} length: 1 __proto__: Array(0) This is what happens when I submit another request (this request is for pk:3): ... Med Input Form Submitted (index):49 csrfmiddlewaretoken=i889gLsqdY9glqI59wRXLTOVehz9Lmp1i5IRikOsgvrGdBD9OpISolDrJ8pqJDmV&input_meds=lisinopril (index):53 (index):60 (2) [{…}, {…}] (index):61 0: {model: "medrec_app.medication", pk: 1, fields: {…}} 1: {model: "medrec_app.medication", pk: 3, fields: {…}} length: 2 __proto__: Array(0) And here's what happens when I request pk:1 and pk:3 at the same time: ... Med Input Form Submitted (index):49 csrfmiddlewaretoken=i889gLsqdY9glqI59wRXLTOVehz9Lmp1i5IRikOsgvrGdBD9OpISolDrJ8pqJDmV&input_meds=lisinopril (index):53 (index):60 (4) [{…}, {…}, {…}, {…}] (index):61 0: {model: "medrec_app.medication", pk: 1, fields: {…}} 1: {model: "medrec_app.medication", pk: 3, fields: {…}} 2: {model: "medrec_app.medication", pk: 3, fields: {…}} 3: {model: "medrec_app.medication", pk: 1, fields: {…}} length: 4 __proto__: Array(0) I only want the responses from the … -
Updating the bulk_create objects in django
i have created the bulk_create and now i am not able to update that bulk objects.just pasting the piece of code of bulk_create. here is my views.py (specific code of bulk_create): UnsecuredTermLoanSetting.objects.bulk_create( [ UnsecuredTermLoanSetting(provience=provience_bc,perchentage=unsecured_rate_bc,cad=unsecured_cad_bc,mnthly_payment_percentage=unsecured_income_bc,min_days=unsecured_minimum_bc,max_days=unsecured_maximum_bc), UnsecuredTermLoanSetting(provience=provience_ab,perchentage=unsecured_rate_ab,cad=unsecured_cad_ab,mnthly_payment_percentage=unsecured_income_ab), UnsecuredTermLoanSetting(provience=provience_mb,perchentage=unsecured_rate_mb,cad=unsecured_cad_mb,mnthly_payment_percentage=unsecured_income_mb), UnsecuredTermLoanSetting(provience=provience_sk,perchentage=unsecured_rate_sk,cad=unsecured_cad_sk,mnthly_payment_percentage=unsecured_income_sk), UnsecuredTermLoanSetting(provience=provience_on,perchentage=unsecured_rate_on,cad=unsecured_cad_on,mnthly_payment_percentage=unsecured_income_on), UnsecuredTermLoanSetting(provience=provience_qc,perchentage=unsecured_rate_qc,cad=unsecured_cad_qc,mnthly_payment_percentage=unsecured_income_qc) ] ) Everything is working fine object creation has been done.But the question is how can i update those objects in one command. or something like that.