Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: models setup for using one database to populate another
I'm rebuilding a personal project in Django, (a family tree), and I'm working on migrating the actual data from the old awkward database to my new model/schema, both Postgres databases. I've defined them in the DATABASES list on settings.py as 'default' and 'source'. I've made my models and I'd like to copy the records from the old database into their corresponding table in the new database, but I'm not quite understanding how to set up the models for it to work, since the Django code uses the models/ORM to access/update/create objects, and I only have models reflecting the new schema, not the old ones. In a coincidental case where I have a table with the exact same schema in the old and new database, I have a management command that can grab the old records from the source using my new ImagePerson model (ported_data = ImagePerson.objects.using('source').all()), since it the expected fields are the same. Then I save objects for them in the 'default': (obj, created_bool) = ImagePerson.objects.using('default').get_or_create(field=fieldvalue, etc), and it works just like I need it to. However when I have a table where the old version is missing fields that my new model/table have, I can't use the model … -
defined class and function not recognized
I defined a board object as follow: class Board(models.Model): #let's do the relational part after I've done the other fields Title = models.CharField(max_length=255) Description = models.TextField(blank=True) #where I got the image https://mixkit.co/blog/trello-backgrounds-awesome-free-illustrations-for- trello-boards/ ImageUrl = models.URLField( default="https://mixkit.imgix.net/art/preview/mixkit-starry-night-sky-over-hills-and-water-85- original-large.png?q=80&auto=format%2Ccompress&h=700&q=80&dpr=1", blank=True, null=False) CreatedAt = models.DateTimeField(default=timezone.now) EndsAt = Board.return_date_time_in_one_year() def __str__(self): return self.title def return_date_time_in_one_year(self): now = timezone.now() return now + timedelta(years=1) When I try to migrate I get the following error, I'm not sure where I went wrong in how I defined the classes, I'm new to both python and django. File "C:\Users\Ameer\Documents\GitHub\Squasha_trello_clone\squasha\board\models.py", line 16, in Board EndsAt = Board.return_date_time_in_one_year() NameError: name 'Board' is not defined -
django view pass json to javascript
I try to pass json to javascript. I want make json like this data: [ { value: 335, name: 'Coding' }, { value: 310, name: 'Database' }, { value: 234, name: 'UIX' }, { value: 135, name: 'Manajemen' },] }] I want make json like this, so I can put to javascript { value: 335, name: 'Coding' }, And this is my code cursor.execute('SELECT u.nama_ktgu, COUNT(m.nim) as jml FROM mahasiswa_mhs_si m, mata_kuliah_kategori_utama u, mata_kuliah_kategori k WHERE k.kode_ktgu_id = u.id AND m.kode_ktg_id = k.id GROUP BY k.id') ktg_mhs = cursor.fetchall() #JSON CHART chart_ktg = {} for i in ktg_mhs: chart_ktg['value'] = ktg_mhs[i][1] chart_ktg['name'] = ktg_mhs[i][0] json = json.dumps(chart_ktg) -
Cannot login my DRF dashboard using simpleJWT, it only works when SessionBased authentication is used (I don't want SessionBased auth)
I have a django project that uses 'rest_framework_simplejwt.authentication.JWTAuthentication' as the default authentication class. To my understanding this is a stateless token that does not use SessionAuthentication. In my DRF home screen (the default dashboard created by drf), I'm trying to log-in, using the top-right button on the screen, however it's not working. Here is the error I get: { "detail": "Authentication credentials were not provided." } After testing, said login button only works when SessionAuthentication is the default class and path('home-auth/', include('rest_framework.urls', namespace='rest_framework')) is placed in my global urls.py. I read about scalability issues when having a Session based auth system, so I would like to refrain from using it. I have created an app, users, that has it's own login URL serializer/view, and uses the JWT authentication method, it works just fine without errors. I thought that method would be the default login verification method that DRF would use but that is not the case due to the error above. I can login just fine when I use my users login url. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'drf_yasg', # Third Party Apps #'admin_honeypot', 'rest_framework', 'django_filters', 'corsheaders', 'rest_framework_simplejwt.token_blacklist', # Apps 'users', ] REST_FRAMEWORK = { … -
Django allow user to edit information
I am trying to allow users to update their profile information but nothing happens upon submit. I thought I had every part covered but clearly missing something. On submit the changes for name do not take effect, it reloads the page and shows the old name. Also, does anyone have any feedback on how to update data based on a select tag? My views.py def Info(request): if request.method == "POST": form = ProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('pages/info.html') else: form = ProfileForm(instance=request.user) args = {'form': form} return render(request, 'pages/info.html', args) My forms.py class ProfileForm(UserChangeForm): class Meta: model = Account fields = ( 'name', 'fruits' ) exclude = ( 'is_active', 'password' ) My template <form method="POST" action=""> {% csrf_token %} <div class="col-md-6"> <label class="labels">name</label> {{ form.name}} </div> <div class="col-md-12"> <label for="cars">fruits</label> <select name="fruits" class="custom-select"> <option value="ap">apple</option> <option value="ba">banana</option> </select> </div> <input type="submit" value="Update"> </form> -
A quick question regarding threading module in Django?
I'm building a scrapper that crawls through URLS and finds emails. I've found out that threading can make this crawling process faster and I'm trying to implement it on Django. But there is a lot of information lacking in regards to this module. One quick question I would like to ask is how would someone know if threading is running correctly on Django. Would this code be enough to run threading? from django.shortcuts import render from django.shortcuts import render from .scrapper import EmailCrawler from django.http import HttpResponse from celery import shared_task from multiprocessing import Process import threading def index(request): return render(request, 'leadfinderapp/scrap.html') t = threading.Thread(target=scrap) t.start() def scrap(request): url = request.GET.get('Email') crawl = EmailCrawler(url) target = crawl.crawl() email_list = crawl.emails # or whatever class-level variable you use return render(request, 'leadfinderapp/results.html', {"email_list": email_list}) Thank you very much any help I would really appreciate it. -
Django templates: if .. in
I have a list of products and want to display them in a template, depending on whether or not the product's dealer is "owned" by the current logged user or not. So here's my view: class ArticleListView(ListView, LoginRequiredMixin): template_name = "accounts/list_article_quentin.html" model = Product def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context["website"] = Website.objects.first() context["product_list"] = context["product_list"].filter(published=True) # Get a list of all dealers associated to the current users. currentUserDealers = self.request.user.dealers.all().values_list('id', flat=True) context["current_user_dealers"] = list(currentUserDealers) return context so currentUserDealers is the list of the dealers associated to the current user (It's a ManyToMany relationship between dealers and users). In my template, I would like to do something like that to decide wether to display the product or not: {% if product.dealer.all.0.pk in current_user_dealer %} (there can be multiple dealers for a product but I'll see that later, hence the all.0) Obviously this doesn't work but you get the idea, I want to see if the current product's dealer ID is in the list of current user's associated dealers, to see if we display it or not. What's the syntax to do it in the template? Or maybe there's a better way to do this directly in the view? -
How to render template tags in the views and send them to Ajax calls
In Django i am using bootstrap4 form from the package django-bootstrap4 it renderst the form using {% bootstrap_form form %} Now i just need only this part using a view like @api_view(['GET']) def rendertemplatetag(request) form = DeviceForm() rendered_template = bootstrap_form(form) <-- something like this where renedered_template can be string # return as json return HttpResponse(rendered_template,status=200,content_type="application/json") I am using DRF for this view this view can be called with ajax and then the returned html can be substituded at its place -
Testing a simple Django view gives 404
I have a simple view that returns <h1>Hello world</h1>. It works when running the server, but in tests, it 404s. I'm using reverse and it returns the right path in the test...so I know the view is registered even in the tests. I've followed Django 3.1's guides and many SO answers already, but can't figure it out. Any help's appreciated! Here's my code: foo/views.py from django.http import HttpResponse def hello(request): text = '<h1>Hello world</h1>' return HttpResponse(text) foo/urls.py from django.conf.urls import url from django.contrib import admin from django.urls import path from .views import hello urlpatterns = [ path('admin/', admin.site.urls), url(r'^hello/', hello, name = 'hello'), # I've also tried: path('hello/', hello, name = 'hello'), ] foo/tests/test_hello.py from django.test import TestCase from django.urls import reverse class SimpleTest(TestCase): def test_hello(self): path = reverse('hello') print(path) response = self.client.get(path) print(response.content) self.assertEqual(response.status_code, 200) Test output $ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). /hello/ b'\n<!doctype html>\n<html lang="en">\n<head>\n <title>Not Found</title>\n</hea d>\n<body>\n <h1>Not Found</h1><p>The requested resource was not found on this server.</p>\n</body>\n</html>\n' F ====================================================================== FAIL: test_details (foo.tests.test_hello.SimpleTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/-------/foo-project/foo/tests/test_hello.py", line 12, in test_details self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 ---------------------------------------------------------------------- Ran 1 test in … -
Django unlike button query for blog post
Hi I think i made a minor error but i'm unable to figure. Basically AttributeError: 'QuerySet' object has no attribute 'exist' This line is the problem: if blog_post.likes.filter(id=request.user.id).exist(): Can anyone advise me on how to change it for the query to work properly. thank you! Views.py def detail_blog_view(request, slug): context = {} #need to import a package get_object_or_404. return object or throw 404 blog_post = get_object_or_404(BlogPost, slug=slug) total_likes = blog_post.total_likes() liked = False if blog_post.likes.filter(id=request.user.id).exist(): liked = True context['liked'] = liked context['blog_post'] = blog_post context['total_likes'] = total_likes return render(request, 'HomeFeed/detail_blog.html', context) def LikeView(request, slug): context = {} #set a user variable user = request.user #if user is not authenticated, redirect it to the page call "must authenticate.html" which isnamed as must authenticate if not user.is_authenticated: return redirect('must_authenticate') post = get_object_or_404(BlogPost, slug=slug) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return redirect('HomeFeed:detail', slug=slug) html: <form action="{% url 'HomeFeed:like_post' blog_post.slug %}" method="POST" >{% csrf_token %} {% if liked %} <button type="submit" name="blog_post_slug" value="{{blog_post.slug}}" class='btn btn-danger btn-sm'>Unlike</button> {% else %} <button type="submit" name="blog_post_slug" value="{{blog_post.slug}}" class='btn btn-primary btn-sm'>Like</button> {% endif %} {{ total_likes }} Likes </form> This is the traceback: Internal Server Error: /HomeFeed/helloworld-1/detail/ Traceback (most recent call … -
django 'get_bound_field' error when rendering form with extra field in template
I'm using a modelformset using a modelform in which I created an extra-field. The formset is instanciated with a queryset.. all of this is working fine. My problems start when I want to assign a value to the extra_field in the init method of the form. here is the form : class SpotlerCreateForm(forms.ModelForm): name = ShrunkField( max_length=50, label=_("Name"), widget=forms.TextInput( attrs={ "placeholder": _("Give a name to this video... "), "help": _("name should have than 50 characters"), "class": "border-0 text-truncate pl-0", } ), required=True, ) duration = forms.TimeField( widget=forms.TimeInput( attrs={ "name": _("duration"), "readonly": True, "class": "duration text-center", } ), required=False, ) is_postedited = forms.BooleanField( widget=forms.CheckboxInput(), label=_("postedition"), label_suffix="", required=False, ) url = forms.URLField(widget=forms.HiddenInput()) class Meta: model = Spotler fields = [ "url", "name", "duration", "is_postedited", ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance: self.fields['url'] = self.instance.get_put_url(File.FULL) def clean_name(self): name = self.cleaned_data["name"] name = str_clean(name) if len(name) > 50: name = name[:50] return name I shortened my view in the code below: class AjaxSpotlerCreateView(View): def get(self, request): SpotlerFormSet = modelformset_factory(Spotler, form=SpotlerCreateForm, extra=0) s_formset = SpotlerFormSet( queryset=Spotler.objects.filter(id__in=[s.id for s in self.init_spotlers()]), prefix="spotlers", ) context = {"spotler_formset":spotler_formset} return render(self.request, "spotler/upload/sp2-upload_formset.html", context) and the part of the template using the formset is : <div class="border-top border-bottom … -
How to check if a user is logged in, in django token authentication?
Hi there I am currently starting a new rest api project with django. Normally when I start a new project I do a lot of planning and get a idea of how I want to build my app. For this app I want to use token authentication but can't find enough resources for this topic. Can anyone tell me these two things, how to check if a user is logged in/authenticated and how to check which user is logged in(of course with token authentication in django). Thank you in advance. Extra info(you don't need to read this): The reason I want to use this kind of authentication is because I don't want to use the built in django models for my user model because my User model has to have some specific fields for this web app, obviously I can work my way around this but its not very efficient so I figured I'd use token authentication. -
Django and mongoDb inspectdb command
this is the error I am getting whenever I am trying to inspect db through django in mongoDb: Unable to inspect table 'chats' # The error was: 'NoneType' object is not subscriptable. # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models # Unable to inspect table 'chats' # The error was: 'NoneType' object is not subscriptable -
Add form fields programmatically to Wagtail Form
I have a model which subclasses AbstractEmailForm.. I can create a new instance with: new_page = LanderPage(body='body text here', title='Test sub page', slug='testsub', to_address='j@site.com',from_address='j@site.com', subject='new inquiry') This works, but it produces a form without fields. I am not sure how to create the form fields using this structure, such as the form field for name and email address. Can someone point me in the right direction? For reference, this is the page being created: class LanderPageFormField(AbstractFormField): page = ParentalKey('LanderPage', related_name='form_fields') class LanderPage(AbstractEmailForm): body = RichTextField(blank=True) thank_you_text = RichTextField(blank=True) content_panels = AbstractEmailForm.content_panels + [ FieldPanel('body', classname="full"), InlinePanel('form_fields', label="Form fields"), FieldPanel('thank_you_text', classname="full"), MultiFieldPanel([ FieldRowPanel([ FieldPanel('from_address', classname="col6"), FieldPanel('to_address', classname="col6"), ]), FieldPanel('subject'), ], "Email"), ] -
How to embed a form multiple times with ListView (and once with DetailView)
I have the following listview and detailview structure. I would like to pass in a form to be shown with each object that is listed in the listview (and also with the one object when there is detailview). How can I get this to show up with each object? class ObjectListView(LoginRequiredMixin, ListView): model = Object ... date = (datetime.now() - timedelta(hours = 7)).date() queryset = Object.objects.filter(date=date) def get(self, request, *args, **kwargs): ... return super().get(request, *args, **kwargs) class ObjectDetailView(LoginRequiredMixin, DetailView): model = Object -
fetching data from backend with certain email address react native
I am having trouble trying to fetch only certain data entries from my backend with a specific email address. My backend stores data from multiple user but lets say I want to fetch only the data from johndoe@gmail.com rather than just fetching all the data. How would I go about putting a condition like that. Below is the code I am using to fetch data from my backend. fetchDataFromApi = () => { const url = "http://localhost:8000/api/list/"; fetch(url).then(res => res.json()) .then(res => { console.log(res) this.setState({myListData: res}) }) .catch(error => { console.log(error) }) }; So from the code, I am basically getting all the data and storing it into the state called myListData but I want to only store data for johndoe@gmail.com. Is there any where I can go about achieving this? Thank you in advance! -
Prepopulate Values of Edit Form from Table Selection
I am trying to create an Edit for that allows the user to scroll through a table and click a button existing in each row to edit the data within a modal. The issue that I am running into is when I try to prepopulate the form with the existing values. How would I convert the EditCommunicationsForm below to display the current values of the row that you selected edit for? I know I can make the initial value a default value like "Testing" but I am not quite sure how to tell it to say "grab the project field from the row that you selected" What I want to do is ID = {{ communications.id }} for my table, but obviously that's wrong since it's half HTML. I need some sort of variable to change that definition for each row views def communications(request): comms_list = Communications.objects.order_by('id') if request.method == "POST": new_form = CommunicationsForm(request.POST, request.FILES) edit_form = EditCommunicationsForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('http://127.0.0.1:7000/polls/communications/',{"new_form":new_form,"edit_form":edit_form,'comms_list':comms_list}) else: comms = Communications.objects.get(id=1) new_form = CommunicationsForm() edit_form = EditCommunicationsForm(instance=comms) query = request.GET.get('search') if query: postresult = Communications.objects.filter(id__contains=query) comms_list = postresult else: comms_list = Communications.objects.order_by('id') return render(request,'polls/communications.html',{"new_form":new_form,"edit_form":edit_form,'comms_list':comms_list}) forms class CommunicationsForm(forms.ModelForm): class Meta: model = Communications fields … -
whitenoise does not serve the changes on static files in django
I am using whitenoise in my django app on production but i noticed that wtenoise cannot serve the changes in statis files during the app is running what should i do to launch the app on production and serve the changes on static files? I have been installed whitenoise using pip and make debug = False then added my whitenose middleware into the MIDDLEWARE list after the SecurityMiddleware then added the following line in settings.py file STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' -
ModuleNotFoundError: No module named 'mysite' import from wsgi.py
I'm trying to run a python file in a django project and I get this error : Traceback (most recent call last): File "data.py", line 2, in <module> from Spiders.vb_json_cleaner import * File "/home/debian/repay-moi/phones/Spiders/vb_json_cleaner.py", line 9, in <module> from mysite.wsgi import * ModuleNotFoundError: No module named 'mysite' Here is my wsgi.py file : import os from django.core.wsgi import get_wsgi_application path = '/home/debian/repay-moi/mysite' if path not in sys.path: sys.path.append(path) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() And my vb_json_cleaner.py import os os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' from mysite.wsgi import * application = get_wsgi_application() from phones.models import * -
Dynamic initial form data
I am attempting to add a button to the customer's page to add a new device but when rendering the form I would like to pass the customer's name as an initial value. This was my personal Christmas project to make my work projects a bit more centralized in 2021. Im almost over the finish line but I've hit this bump. Any help would be appreciated. Thanks. I have two models in separate apps. class Customer(models.Model): nameF = models.CharField("First Name", max_length=255, blank = True, null = True) nameL = models.CharField("Last Name", max_length=255, blank = True, null = True) nameN = models.CharField("Nickname", max_length=255, blank = True, null = True) address = models.CharField("Address", max_length=255, blank = True, null = True) phone = models.CharField("Phone", max_length=255, blank = True, null = True) email = models.EmailField("Email", max_length=254, blank = True, null = True) dateC = models.DateTimeField("Date Created", auto_now_add=True) dateU = models.DateTimeField("Last Updated", auto_now=True) note = models.TextField("Notes", blank = True, null = True) def __str__(self): return self.nameF def get_absolute_url(self): return reverse ("cfull", kwargs={"pk": self.id}) and class Device(models.Model): CONNECTION = ( ('Local', 'Local'), ('IP/DOMAIN', 'IP/DOMAIN'), ('P2P', 'P2P') ) TYPE = ( ('DVR', 'DVR'), ('NVR', 'NVR'), ('Router', 'Router'), ('WLAN Controller', 'WLAN Controller'), ('AP', 'AP'), ('Doorbell', 'Doorbell'), ('Audio Controller', … -
Access Data in MS Access via Django
I have information that is stored in MS Access and I need to display it through a web application(Django). Is there a way to include the connection in the settings.py of Django , like other databases, so as to use Django features? -
Reverse for 'teamEdit' with no arguments not found. 1 pattern(s) tried: ['teams/teamEdit/(?P<team_id>[0-9]+)/$']
Error : NoReverseMatch at /teams/teamEdit/12/ I'm a beginner in Django. I'm trying to make a team app. But while Edit the team I'm facing some error. Already I've tried some solutions from stackover flow but still showing the error. Here Is The Code : teamlist.html : <a class="font-w500 align-items-center text-primary btn btn-link" href="{% url 'team:teamEdit' team.id %}"> Edit <i class="fa fa-edit ml-1 opacity-50 font-size-base text-primary"></i> </a> urls.py: path('teamEdit/<int:team_id>/', teamEdit, name='teamEdit'), views.py: @login_required def teamEdit(request, team_id): print(team_id) team = get_object_or_404(Team, pk=team_id, status=Team.ACTIVE, members__in=[request.user]) print(team.title) if request.method == 'POST': title = request.POST.get('title') if title: team.title = title team.save() messages.info(request, 'The changes was saved') return redirect('team:teamList') else: return render(request, 'teamEdit.html', {'team': team}) teamEdit.html: <h3 class="text-center">Eupdate Team</h3> <form class="mb-5" method="post" action="{% url 'team:teamEdit' team.id %}"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control form-control-lg form-control-alt" id="id_title" name="title" v-model="title" placeholder="Title"> </div> <div class="form-group"> <button type="submit" class="btn btn-block btn-success">Save</button> </div> </form> Error Traceback : Traceback (most recent call last): File "C:\Django\TaskTracker\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Django\TaskTracker\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Django\TaskTracker\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Django\TaskTracker\venv\ttm\apps\team\views.py", line 68, in teamEdit return render(request, 'teamEdit.html', {'team': team}) File "C:\Django\TaskTracker\venv\lib\site-packages\django\shortcuts.py", line 19, in render … -
Increase performance with prefetch and select related
I'm trying to export a csv with information from the model order which has a relation 1 to 1 with delivery channel and restaurant and a 1 to many relationship with orderlines. It is taking way too much time for download it (around 20 seconds for 10k lines). This is my code: orderlines = OrderLine.objects.select_related("product").only( "product__display_name", "quantity", "paid_amount", "discount_amount" ) return ( Order.objects.prefetch_related(Prefetch("orderlines", queryset=orderlines, to_attr="orderlines_list")) .select_related("delivery_channel") .select_related("restaurant") ) I thought about using only in the end but I can't use it on orderlines as it is a 1 to many relationship. I'm stuck on how to improve the performance. Many thanks. -
Django: How to enable users to delete their account
I am unsure of what went wrong but my I cannot delete my own account despite setting is_active=false I tried 3 different types of views in my views.py but to no avail.I'm not sure which view to use. Everytime i click delete account, i will be redirected to the homefeed page and nothing will happen as the account still remains. Please tell me if more information is required Views.py @user_passes_test(lambda account: account.is_superuser, login_url=reverse_lazy('login')) def delete_user_view(request, user_id): context = {} if not request.user.is_authenticated: return redirect("login") try: user_id = kwargs.get("user_id") account = Account.objects.get(pk=user_id) account.is_active = False account.save() context['msg'] = 'The user is deleted.' except Account.DoesNotExist: context['msg'] = 'User does not exist.' except Exception as e: context['msg'] = e.message return render(request, 'HomeFeed/snippets/home.html', context) def delete_user_view(request, user): user = request.user user.is_active = False user.save() logout(request) messages.success(request, 'Profile successfully disabled.') return redirect('HomeFeed:main') class CustomUserDeleteView(DeleteView): model = Account success_url = reverse_lazy('login') urls.py from account.views import ( delete_user_view, CustomUserDeleteView,) path('deleteaccount/<pk>', CustomUserDeleteView.as_view(template_name='account/account.html'), name='deleteaccount'), account.html <a class="mt-4 btn btn-danger deleteaccount" onclick="return confirm('Are you sure you want to delete your account')" href="{% url 'account:deleteaccount' user_id=request.user.id %}">Delete Account</a> -
AssertionError: `child` is a required argument [closed]
when developing my application I ran into a problem that is, I tried to update and create in the database a record of this kind [ { cpNameID: {cpSubName: "[JK]린다", cpName: "[JK]린다(비오엠)"}, docNumber: "OT201912270971-001", dvClass: "반품", odNumber: "[162-191217-001]", odQuantity: -1, pdID: null, phPrice: -19500, productID: {erpID: "9810779001060", pdName: "바비리스‥에어 브러쉬‥AS100VK‥3in1 멀티 에어 스타일러 900W", pdOption: null}, shippingDate: "2020-01-01", spPrice: -22364 }, { cpNameID: {cpSubName: "[JK]리빙픽", cpName: "[JK]리빙픽"}, docNumber: "OT201912307179-001", dvClass: "반품", odNumber: "77384890", odQuantity: -1, pdID: null, phPrice: -4195, productID: {erpID: "9810779003068", pdName: "CHI‥케라틴‥케라틴 컨디셔너", pdOption: "240ml"}, shippingDate: "2020-01-01", spPrice: -10055, }, { cpNameID: {cpSubName: "[JK]별난맘", cpName: "[JK]별난맘"}, docNumber: "OT201912310095-001", dvClass: "반품", odNumber: "201911290009", odQuantity: -1, pdID: null, phPrice: -44182, productID: {erpID: "9810779005184", pdName: "EMK‥가습기‥EK-H3C40WH", pdOption: null}, shippingDate: "2020-01-01", spPrice: -52727, } ] here is my serializer.py class OrderListSerializer(serializers.ListSerializer): def create(self, validated_data): Orders = [OrderList(**item) for item in validated_data] return OrderList.objects.bulk_create(Orders) class ComMappingSerializer(serializers.Serializer): cpSubName = serializers.CharField() cpName = serializers.CharField() class ProductListSerializer(serializers.Serializer): erpID = serializers.CharField(required=True) pdName = serializers.CharField(required=True) pdOption = serializers.CharField() class OrderSerializer(serializers.Serializer): shippingDate = serializers.DateField(required=True) dvClass = serializers.CharField(required=True) cpNameID = ComMappingSerializer(required=True) odNumber = serializers.CharField() docNumber = serializers.CharField(required=True) pdID = serializers.CharField() productID = ProductListSerializer(required=True) odQuantity = serializers.IntegerField(required=True) spPrice = serializers.IntegerField(required=True) phPrice = serializers.IntegerField(required=True) def valldate_cpNameID(self, value): exam, _ = ComMapping.objects.get_or_create( cpSubName=value.cpSubName, …