Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allauth get_user_model() CustomUser issue
I am currently trying to get the user model in a function-based view but keep getting the following error. I have allauth installed and created a customer user using the allauth.account model. I attached my model and the migration. I have looked in my database and have users in, however every time I call the user in the view it gives me a customer user error. I have tried the other 2 methods that are commented out in the function view. error { Environment: Request Method: POST Request URL: http://127.0.0.1:8000/store/add_listing/ Django Version: 3.1.14 Python Version: 3.9.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'crispy_forms', 'allauth', 'allauth.account', 'accounts', 'web_pages', 'store'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/get_printed/store/views.py", line 93, in AddListing current_user = request.CustomUser #.objects.filter(current_user) #get_user_model() Exception Type: AttributeError at /store/add_listing/ Exception Value: 'WSGIRequest' object has no attribute 'CustomUser' Views.py def AddListing(request): if request.method == 'POST': form = List_Item_Form(request.POST) if form.is_valid(): itemName = form.cleaned_data['item_name'] price = form.cleaned_data['price'] desc = form.cleaned_data['description'] quan = form.cleaned_data['quantity'] main_img = form.cleaned_data['main_image'] current_user = request.CustomUser #.objects.filter(current_user) … -
Reuse same image Django
I have a django model that has an image field. I want to change the field so it can upload a new image or reuse the same image that was already been uploaded. But I want the field so it can have an option to reuse the same image only on admin. If it is on form, it only can upload an image. How can I do that? The main thing is that the admin can have an option to upload a new image or reuse the same image that was already been uploaded. But the regular user can only upload a new image and doesn't have an option to reuse an image. Is there any way to solve this problem? -
django unable to create superuser
models from django.contrib.auth.models import User from django.db import models from django.contrib.auth.models import AbstractBaseUser, UserManager, PermissionsMixin class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True) objects = UserManager() USERNAME_FIELD = 'username' error: (env) ➜ autherization python manage.py createsuperuser Username: soubhagya Password: Password (again): Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/contrib/auth/models.py", line 163, in create_superuser return self._create_user(username, email, password, **extra_fields) File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/contrib/auth/models.py", line 144, in _create_user user = self.model(username=username, email=email, **extra_fields) File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/db/models/base.py", line 503, in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: User() got an unexpected keyword argument 'email' (env) ➜ autherization I am trying to create superuser inside django shell Getting above error. Please take a look what can be the reason -
Disable login form alert for IsAuthenticated API views - DRF
I have some views that have the IsAuthenticated permission class. However, whenever I access these views, a JS alert pops up asking for credentials like so: How can I disable this, so that users are unable to log in via this view? I want users to only be able to log in via the Login view, which has a 2FA system. -
HTML for loop won't pickup the variable I ask for
I have a for loop in my HTML template, I want it to display certain information for the author of the posts but it won't display anything: {% for post.author in post %} <img class="rounded-circle profile-img" src="{{ post.author.profile.image.url }}"/> <div class="media-body"> <h2 class="account-heading">{{ view.kwargs.username }}</h2> <!-- only This works --> <p class="text-secondary">{{ post.author.first_name }} {{ post.author.last_name }}</p> <p class="text-secondary">{{ post.author.email }}</p> <div class="container"> <p class="lead"><Strong>Sobre mi:</strong></p> <p class="lead">{{ post.author.description }}</p> </div> <br> <p class="text-secondary">Se unió el {{ post.author.date_joined }}</p> <p class="text-secondary">Última vez visto: {{ post.author.last_login }}</p> <p class="mb-0">{{ post.author.about }}</p> </div> {% endfor %} Before I made those changes to the for loop it was working, but not exaclty like I wanted it to. The loop is made to display certain user's information, so I can't have it display the same info more than 1 time, that's why I'm not satisfied with the for loop here: {% for post in posts %} <img class="rounded-circle profile-img" src="{{ post.author.profile.image.url }}"/> <div class="media-body"> <h2 class="account-heading">{{ view.kwargs.username }}</h2> <!-- only This works --> <p class="text-secondary">{{ post.author.first_name }} {{ post.author.last_name }}</p> <p class="text-secondary">{{ post.author.email }}</p> <div class="container"> <p class="lead"><Strong>Sobre mi:</strong></p> <p class="lead">{{ post.author.description }}</p> </div> <br> <p class="text-secondary">Se unió el {{ post.author.date_joined }}</p> <p class="text-secondary">Última … -
geodjango creating GEOS multi geometries fails after python upgrade (M!)
I have an @property on a model that gets a bounding box for all the geometries associated with a dataset. This code has worked fine for a couple of years. Now, on a new M1 mac laptop, I upgraded Python (3.7.4 to 3.9.7) and the configuration of GDAL and GEOS was difficult. But as I understand, django.contrib.gis includes its own versions of those libraries. Relevent code snippets: from django.contrib.gis.geos import GeometryCollection, MultiPoint, Point from places.models import PlaceGeom from datasets.models import Dataset class Dataset(models.Model): fields … @property def bounds(self): dsgeoms=PlaceGeom.objects.values_list(‘geom’,flat=True).filter(place__dataset=self.label) print(tuple(dsgeoms[:2])) # (<Point object at 0x12ee39988>, <Point object at 0x12ee39a08>) gc = GeometryCollection(tuple(dsgeoms[:2])) return json.loads(gc.envelope.geojson) if pg_geoms.count() > 0 else None This crashes when creating the GeometryCollection with no real clue as to why, in PyCharm: “process finished with exit code 138 (interrupted by signal 10: SIGBUS)” in django shell: “67692 bus error ./manage.py shell” in browser: simply quits runserver So I simply tried the examples from the Geodjango docs at https://docs.djangoproject.com/en/2.2/ref/contrib/gis/geos/, and though the Point and LineString creation worked, GeometryCollection and MultiPoint did not, with the shell error "68483 segmentation fault ./manage.py shell" I'm stumped, but before I try building the bbox with Shapely and multiple transformations, thought I'd ask … -
supervisor-win How to use for windows server
I downloaded it using pip install supervisor-win, but I didn't know how to configure my Django project file.ini and give Supervisor to manage it. I know how to operate on Linux, not how to write configuration files and use them on Windows. this is supervisor-win https://pypi.org/project/supervisor-win/ -
how can i change this SQL to Django ORM code? (group by)
I need to retrieve the process element (by maximum processid) per unique serial number. I'm using mysql and this is my django model. class Sample(models.Model): processid = models.IntegerField(default=0) serialnumber = models.CharField(max_length=256) ## create_at = models.DateTimeField(null=True) class Process(models.Model): sample = models.ForeignKey(Sample, blank=False, null=True, on_delete=models.SET_NULL) And this is sql query what i need to change to django. SELECT process.* FROM process WHERE id in ( SELECT max(sample.processid) as processid from sample group by serialnumber ); -
Using the django registration redux package for user authentication
Whenever I try to go to .../accounts/register/ it just seems to give me a blank white page, it won't even display an error. I'm not sure why this is happening because I have previously tried out the same code for user registration on another web application (using the Django registration redux package) and it seemed to work fine! Would appreciate any ideas or help on how to fix this. how my files are organised (uni_fit is the app name) html code for registration_form.html html code for registration_closedd.html code in urls.py code in settings.py code in settings.py (2) the results on chrome when I search for [http://127.0.0.1:8000/accounts/register/] This is what I'm trying to get What I'm trying to get -
django-apscheduler don't in django-admin
I install django-apscheduler ,an I acording to document registed in the view ,but it don't in the admin site,how can I get it? import time from apscheduler.schedulers.background import BackgroundScheduler from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job scheduler = BackgroundScheduler() scheduler.add_jobstore(DjangoJobStore(), "default") @register_job(scheduler, "interval", seconds=1) def test_job(): time.sleep(4) print("I'm a test job!") # raise ValueError("Olala!") register_events(scheduler) scheduler.start() print("Scheduler started!") -
Set is_staff to true for userthat login via django allauth google
I am using allauth in Django in order for users to login via their Google accounts. Everything works fine, user logs in, account is created and saved in the db, but the problem is I want the new users to automatically be staff members by setting is_staff to true. I was looking at the official docs on how to override data and I did this: in settings.py: ACCOUNT_FORMS = { 'signup': 'myapp.forms.MyCustomGoogleSignupForm' } and in myapp/forms.py (the directory that has the wsgi.py file. Is this the right location? I have not created a new app directory for loggin in with google.) class MyCustomGoogleSignupForm(SignupForm): def save(self, request): # Ensure you call the parent class's save. # .save() returns a User object. user = super(MyCustomGoogleSignupForm, self).save(request) # Add your own processing here. user.is_staff = True # You must return the original result. return user but this does not work. Anyone has any ideas? Thank you -
Data cannot saved in django formview
I'm going to receive data and save it using form and save it. But I can't get any result. Let me know what I'm doing wrong. I set up a model. And I wrote a form to get the input. Forms.Form was used. At first, I used modelform, but I wrote it like this because there seemed to be no difference. Is label important in the form? You can't get the data value because you can't connect the label? heeelp! models.py class PayHistory(models.Model): branch = models.ForeignKey(Branch, on_delete=models.CASCADE, null=True) package_recommandation_date = models.DateField(null=True) package_payment_date = models.DateField(null=True) ... forms.py class PackageForm(forms.Form): package_recommandation_date = forms.CharField(label='package_recommandation_date') package_payment_date = forms.CharField(label='package_payment_date') ... views.py class PackageView(FormView): model = PayHistory template_name = 'branches/package-create.html' success_url = reverse_lazy('/') form_class = PackageForm def form_valid(self, form): form = form.save(commit=False) form.save() return super().form_valid(form) # HTML {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="table-content"> <!-- 검색 --> <table border="0"> <tr class="input-tr"> <td><input type="date" class="input1" name="package_recommandation_date" value="{{ form.package_recommandation_date.value|default_if_none:'' }}" required> </td> <td><input type="date" class="input2" name="package_payment_date" value="{{ form.package_payment_date.value|default_if_none:'' }}"> </td> ... <td><button type="submit" class="input-button input16">적용</button></td> # static/js const package_recommandation_date = document.querySelector("package_recommandation_date"); const package_payment_date = document.querySelector("package_payment_date"); console.info(package_recommandation_date, package_payment_date) #output -> null null -
can I build django project use javascript api and react? [closed]
as title I want to build a Django project use javascript(or node.js) write api and react Can it be achieved? thx -
Using unittest.mock to mock a DRF response
My example is pretty basic: # urls.py from django.urls import include, path from rest_framework.routers import DefaultRouter from core import views router = DefaultRouter() router.register(r'core', views.CoreViewSet) urlpatterns = [ path('', include(router.urls)), ] # views.py from rest_framework import mixins, viewsets from .models import Numbers from .serializers import NumbersSerializer class CoreViewSet(viewsets.GenericViewSet, mixins.ListModelMixin): queryset = Numbers.objects.all() serializer_class = NumbersSerializer # serializers.py from rest_framework import serializers from .models import Numbers class NumbersSerializer(serializers.ModelSerializer): class Meta: model = Numbers fields = '__all__' # models.py from django.db import models # Create your models here. class Numbers(models.Model): odd = models.IntegerField() even = models.IntegerField() class Meta: db_table = 'numbers' What I'm trying to do is mock the request to the /core/ URI so it returns a mocked response and not the response from the database. For example, considering unit testing in a CI pipeline when the database isn't available. The below is what I have, but print(response.data) returns the actual response and not the mocked one: import unittest from unittest.mock import patch from rest_framework.test import APIClient class CoreTestCase(unittest.TestCase): @patch('core.views') def test_response(self, mock_get): mock_get.return_value = [{'hello': 'world'}] client = APIClient() response = client.get('/core/') print(response.data) Not finding the documentation very intuitive in figuring this out, so asking how I should be implementing … -
how to use css that's in another file django
this is probably a stupid question. I'm new to django and i was wondering how to use css when the css is in a different file. right now my file paths look like this: css: web/static/web/style.css Html: web/templates/web my Html file looks like this: {% load static %} <!--HTML--> <body> <div class="topnav"> <a class="active" href="/">Home</a> <a href="/donate">Donate</a> </div> </body> my css looks like this: .topnav { background-color: #333; overflow: hidden; } .topnav a { float: left; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } .topnav a:hover { background-color: #ddd; color: black; } .topnav a.active { background-color: #04AA6D; color: white; } how can i get the html to use the css from a different file? -
Can't get Bootstrap navbar to work properly in Django project
I'm trying to get Bootstrap working on my Django project but can only manage getting the CSS to work but not the navbar functionalities. For example, the dropdown doesn't work and when making the window smaller, the 3-bar icon that substitutes as the navbar doesn't work either. The navbar is ripped straight from Bootstrap's documentation. I've been going at this for some time and have looked at solutions online but nothing seems to work for me. I have already tried swapping the JQuery script tag and the Bootstrap JS tag and moved my script tags to just before my </body> tag. Here is the relevant code below: base.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <title>{% block title %}{% endblock title %}</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div … -
Form not saving to model with two Foreign Keys - Django
I'm having trouble saving my form to a model that has two foreign keys: User who is submitting the form The current price of the Crypto submitted. The form values seem to through the AssetView but not being saved. Could anyone help to why they aren't saving. I've provided Models, Views, Form, HTML. Django Models from django.contrib.auth.models import User class CryptoPrices(models.Model): symbol = models.CharField(max_length=20) current_price = models.FloatField(default=0.0) class CryptoAssets(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) symbol = models.CharField(max_length=20) amount = models.FloatField(default=0.0) purchase_price = models.FloatField(default=0.0) crypto_prices = models.ForeignKey(CryptoPrices, on_delete=models.CASCADE) Django View from coinprices.forms import AssetForm class AssetView(TemplateView): template_name = 'coinprices/my-dashboard.html' def get(self, request): form_a = AssetForm(prefix='form_a') return render(request, self.template_name, {'form_a': form_a}) def post(self, request): form_a = AssetForm(request.POST, prefix='form_a') if form_a.is_valid(): post = form_a.cleaned_data post.save() form = AssetForm() args = {'form': form} return render(request, self.template_name, args) args = {'form_a': form_a} return render(request, self.template_name, args) Django Form from coinprices.models import CryptoPrices tickers = (('BTC', 'BTC'), ('ETH', 'ETH')) class AssetForm(forms.ModelForm): symbol = forms.ChoiceField(choices=tickers, required=True, label='') amount = forms.DecimalField(decimal_places=2, max_digits=20, required=True, label='') purchase_price = forms.DecimalField(decimal_places=2, max_digits=20, required=True, label='') class Meta: model = CryptoAssets fields = ( 'symbol', 'amount', 'purchase_price' ) HTML {% extends 'base.html' %} {% block head %} <title>My Dashboard</title> {% endblock %} {% block body … -
Should blockchain technology be handled on the client side or the server side?
I'm a full-stack developer (specifically Django web developer). Blockchain is new to me. I heard that blockchain applications can be written with both python (on the server side) and javascript (on the client side). So, what programming langue is to write Blockchain? Do I write it on the server side or the server side? My guess is handling it in the server would be more secure because hackers can read client code and inject malicious javascript code through the console panel. Am I right? To be concise, my question is Should blockchain technology be handled on the client side or the server side? -
Django only one default row
I have a ManyToMany relationship that indicates a Doctor can have many specialties, but only one of them is the PRIMARY one. I've designed a custom M2M class as follows: class Doctor(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE) specialty = models.ManyToManyField(Specialty, through='DoctorSpecialty') ..... class Specialty(models.Model): title = models.CharField(max_length=45) ..... class DoctorSpecialty(models.Model): doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) specialty = models.ForeignKey(Specialty, on_delete=models.CASCADE) default = models.BooleanField(default=True) The doctor can have many specialties, but only one of them can be the default one. He or she can have many specialties with the default field set as False, but cannot have more than one with the default field set as True I wanted to do something like this: class Meta: constraints = [ models.UniqueConstraint(fields=['doctor', 'specialty', 'default'], name='unique specialty') ] But this will mean that the doctor can have only one specialty as a default one, and only one other as a non default one. How can we achieve this with the minimum of code? PS: I could leave it without constraints and try to validate adding new entries by checking if another default specialty exists, but this will add a lot of overhead and exception raising. -
Django complex json response for ohlc dataset
I'm trying to pull my data at json response in Django views to make simple financial ohcl chart https://github.com/MarcinLinkl/chartjs-chart-financial To do this, I need the following js structure: const data = { datasets: [{ data: [ { x: 1647280800000, o: 1, h: 0.75, l: 0.75, c: 1.25 }, { x: 1647281700000, o: 1.20, h: 1.5, l: 0.75, c: 0.9 },{ x: 1647282600000, o: 1.20, h: 10.5, l: 0.75, c: 10.9 },{ x: 1647283500000, o: 12.20, h: 14.5, l: 12.75, c: 10.9 } ], }] }; But I can't send that by context, or even make view with a JsonRespone like : def apidata(request): data = {{ x: 1647280800000, o: 1, h: 0.75, l: 0.75, c: 1.25 }, { x: 1647281700000, o: 1.20, h: 1.5, l: 0.75, c: 0.9 },{ x: 1647282600000, o: 1.20, h: 10.5, l: 0.75, c: 10.9 },{ x: 1647283500000, o: 12.20, h: 14.5, l: 12.75, c: 10.9 }} return JsonResponse(data, safe=False) TypeError at /api-data/ unhashable type: 'dict' How could I send this data like structure to template (might by with ajax) (and ofcourse for getting latter some dynamic data) -
django-ckeditor is not display in django admin panel
I use django-ckeditor package in my website but it not work and text box is default django text box like this picture: enter image description here models.py: from ckeditor.fields import RichTextField class Post(models.Model): body = RichTextField(null = True, blank = True) note: I have added 'ckeditor' in settings.py -
Dependent Dropdown List not workfing (No Dynmic effect) -Django
HiI want to relate a field1 to another field2, Tha story that I have 2 fields,(the two of them are selectable) *The first field is about category family (the user will select :rectangular or cerculaire), What I want that if the user will select in the field1: the option rectangular, in the field 2 there was a group of selectable values will be appear related to this category selected)(in field1) otherwise if the user will select another category(in field 1) there was other values that will be displayed to select it on the field2. I have tried doing that using Jquery but it seems that it doesnt work ad I do no , because there was no error: Here is the models.py of the 2 fields: About the field1: class Category(models.Model): name = models.CharField(verbose_name=" Name ", max_length=60) pid = models.CharField(max_length=20, choices=ID_CATEGORY) def __str__(self): return self.name About the field2: class ProfileSize(models.Model): name = models.CharField(verbose_name=" Name ", max_length=60) pid = models.CharField(max_length=20, choices=ID_CATEGORY) def __str__(self): return self.name Here is another model where i am calling the model of the field1 and the model of the field2: class Geometry(models.Model): profile_family = models.ForeignKey(Category, on_delete=models.CASCADE) profile_size = models.ForeignKey(ProfileSize, on_delete=models.CASCADE) Here is the views.py : def form_geometry(request): … -
Django model update with race condition protection
Let's say we have the database table workers with the following fields: id [int] active [bool] Let's assume we have N > 1 records in the database. These records are representing background processes. It's required to allow exactly one process to work. My question is: how to avoid race conditions when all background processes are trying to become an active process. In plain SQL, I would try around something like this: UPDATE workers SET active = (SELECT MAX(*) FROM workers) XOR 1 WHERE id=...; It seems that only one worker can be lucky enough to survive the XOR. My real question is: how to achieve the same effect using Django models. I'm looking around F expressions but haven't found inspiration yet. -
How to retrieve foreignkey in django forms and view
I find it very difficult to retrieve field in model foreignkey of this example instance code in my views.py. am using forms.ModelForm can someone help me out models.py class tableA(models.Model): name = models.CharField(max_length = 30) class TableB(models.Model): number = models.CharField(max_length = 30) class TableC(models.Model): amount = models.CharField(max_length = 30) class TableD(models.Model): identity_number = models.CharField(max_length = 30) case_number = models.CharField(max_length = 30) tablea = models.ForeignKey(tableA, related_name='tableas') tableb = models.ForeignKey(tableB, related_name="tablebs", on_delete=models.CASCADE) tablec = models.ForeignKey(tableC, related_name="tablecs", on_delete=models.CASCADE) forms.py class TableDDataForm (forms.ModelForm): class Meta: model = TableD fields = '__all__' views.py def tabledviews(request): form = TableDDataForm (request.POST or None ) if request.method == "POST": if form.is_valid(): identity_number = form.cleaned_data['identity_number'] case_number = form.cleaned_data['case_number'] tablea = form.cleaned_data['tablea'] tableb = form.cleaned_data['tableb'] tablec = form.cleaned_data['tablec'] post = Post.objects.create( name = tablea.name, number = tableb.number, amount = tablec.amount, case_number = case_number, ) return render(request, 'table/success.html', 'tablea':tablea, 'tableb':tableb, 'tablec':tablec, 'post':post,) else: form = TableDDataForm() context = { 'form':form, } return render(request, 'table/tabled.html', context) This foreignKey fields object are not retrieving in my views and i will need help. i want to be able to retrieve name on TableA in TableDDataForm likewise number in Tableb in TableDDataForm and Amount in Tablec in TableDDataForm. any help will be highly appreciated. -
{'index': 0, 'code': 2, 'errmsg': "No array filter found for identifier 'i' in path 'Comments.$[i].Replies.$[j].Reply'"}
enter image description here WriteError: No array filter found for identifier 'i' in path 'Comments.$[i].Replies.$[j].Reply', full error: {'index': 0, 'code': 2, 'errmsg': "No array filter found for identifier 'i' in path 'Comments.$[i].Replies.$[j].Reply'"} I just want to update the reply in my data. I'm getting this error. Is there any other way to update? If yes. Then please kindly answer. Thank you. Code article_id = "6223bf189ee543673ca35940" comment_id = "2d1ae2a7-1488-44b0-8ba3-9e946ed8cca9" reply_id = "c0b9d54a-416f-4598-bf7b-33be80faa5c3" article_collection.update_one({'_id': ObjectId(article_id)}, { '$set': {'Comments.$[i].Replies.$[j].Reply': reply}, 'arrayFilters': [{'i.ID': comment_id}, {'j.ID': reply_id}] }, upsert=False) Data { "_id" : ObjectId("6223bf189ee543673ca35940"), "Comments" : [ { "ID" : "2d1ae2a7-1488-44b0-8ba3-9e946ed8cca9", "User_id" : 1, "Comment" : "Thank you for this simple explanation.", "Date" : ISODate("2022-03-13T02:13:09.022Z"), "Replies" : [ { "ID" : "c0b9d54a-416f-4598-bf7b-33be80faa5c3", "User_id" : 1, "Reply" : "You're welcome", "Date" : ISODate("2022-03-13T12:53:39.046Z") } ] } ] } Can anyone help me with this one.