Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unsure why Django model form many to many field validation failing on is_vaild()
I have the following form and model in my django app: Form: class AdditionalDealSetupForm(ModelForm): required_css_class = "required" lead_underwriters = forms.ModelMultipleChoiceField( queryset=Underwriters.objects.all(), label="Lead Underwriter(s):", required=False, widget=forms.SelectMultiple( attrs={"class": "lead_underwriter"} ), ) underwriters = forms.ModelMultipleChoiceField( queryset=Underwriters.objects.all(), required=False, label="Underwriter(s):", widget=forms.SelectMultiple(attrs={"class": "underwriter"}), ) class Meta: model = AdditionalDeal fields = [ "cutoff_date", "closing_date", "deal_private", "lead_underwriters", "underwriters", ] Model: class AdditionalDeal(TimestampedSafeDeleteModel): id: PrimaryKeyIDType = models.AutoField(primary_key=True) # Relations deal_setup: ForeignKeyType[t.Optional["DealSetup"]] = models.ForeignKey( "DealSetup", on_delete=models.SET_NULL, null=True, blank=True, related_name="additional_deal_set", ) if t.TYPE_CHECKING: deal_setup_id: ForeignKeyIDType lead_underwriters = models.ManyToManyField( Underwriters, related_name="DealLeadUnderwriter" ) underwriters = models.ManyToManyField(Underwriters, related_name="DealUnderwriter") class Meta: db_table = "Additional_Deal" verbose_name_plural = "Additional Deal" unique_together = ("deal_setup",) So I have a multi select form on the front end that can create new tags/ underwriters which are instances of the Underwriters model. When I try to submit the form the newly returned value from the form that does not exist in the Underwriters model already is failing validation. Right now I am creating the new Underwriter objects before I call is_valid() on the form object. I cant figure out why this is. I tried overriding some of the ModelForm clean_* methods but they are not getting called as I expected to before this failed validation: -
Django SimpleListFilter: ValueError not enough values to unpack (expected 2, got 0)
Context: I'm creating a custom input filter in Django using the SimpleListFilter class. I've followed the steps in here https://hakibenita.com/how-to-add-a-text-filter-to-django-admin, but I'm encountering a ValueError when trying to use the filter. Here is my code: filters.py: from django.contrib import admin from django.db.models import Q class InputFilter(admin.SimpleListFilter): title = 'Language' parameter_name = 'language' template = 'admin/input_filter.html' def lookups(self, request, model_admin): # Dummy, required to show the filter. return ((),) def queryset(self, request, queryset): if self.value(): return queryset.filter(Q(language__icontains=self.value())) def choices(self, changelist): all_choices = super().choices(changelist) query_params = changelist.get_filters_params() if not self.lookup_choices: return [] for lookup, title in self.lookup_choices: query_parts = changelist.get_query_string({self.parameter_name: lookup}).split('&') if query_parts and len(query_parts) >= 2: query = '&'.join([f'{k}={v}' for k, v in query_parts]) choice = { 'query_string': f'?{query}&{query_params}', 'display': title, 'selected': self.value() == lookup, } all_choices.append(choice) return all_choices I get the following error when accessing the admin page: ValueError at /repoman/admin/aws_storage/raw_file/ not enough values to unpack (expected 2, got 0) I'm not sure what is causing this error or how to fix it. Any help would be appreciated! -
CSRF error when making POST request to Django API
I am currently developing an application that has a React JS front end and Python Django backend. After successfully logging in, the backend created the necessary cookies, which includes the CSRF token, however when the front end makes a POST request the API returns an error with: "CSRF Failed: CSRF token missing or incorrect" even though the CSRF token is within the cookies that are passed to the API. I have looked online and the fix is to include the CSRF token in the X-CSRFToken header, which I have successfully tested by manually putting the CSRF token in the front end code when it makes the API call. When I try to use Cookies.get('csrftoken'), or even just console.log(document.cookie), it does not return anything because the domain of the CSRF token is the backend URL and therefore different to the front end domain so it does not let me use it within the frontend code. Is there a way for me to use the CSRF token in the cookie to validate the request within the API or can I somehow access it within the frontend to pass it via the X-CSRFToken header even though it is a different domain? I have … -
Using pyarmor in a django project with celery
I'm using pyarmor to obfuscate my django project, following this steps: pyarmor init --entry=manage.py pyarmor build Running the content in dist/, works fine. But I would like running celery too. It's possible? Do I need put it in init too? -
Django admin, how can I add the FK selector in a StackedInline record
Given the following models : class Person(models.Model): name = models.CharField(max_length=50) family = models.ForeignKey( "Family", related_name="members", on_delete=models.CASCADE ) def __str__(self) -> str: return self.name class Family(models.Model): name = models.CharField(max_length=50) def __str__(self) -> str: return self.name And the following admin settings : class PersonAdmin(admin.StackedInline): model = Person list_display = ("name", "family") extra = 0 class FamilyAdmin(admin.ModelAdmin): model = Family list_display = ("name",) inlines = [PersonAdmin] extra = 0 admin.site.register(Family, FamilyAdmin) I would like to be able, from the Family edit page, to change the family of a person. Say I have Person A belonging to Family 1, I would like to be able to "migrate" this person to another family from the family edit page. Unfortunately, even if I explicitly specify the fields in the PersonAdmin class, the dropdown won't show. Any help or even a simple tips to know where and what to look would be greatly appreciated. I've tried looking for a solution on Django Admin Cookbook, on Google and on SO, but haven't found a solution to this and I'm pretty much a django (admin) noob. -
Django Static File not Updated
I am working on Django 4.1 on Windows locally and found that my static file did not update when I modified it, even the content showed on http://127.0.0.1/static/app_name/styles/css_name.css is the old CSS file. This issue suddenly happened after almost 1 year of development. In setting.py: DEBUG = True STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') And I have already tried the following method: Hard Reload Ctrl+F5 Clear Browser Cache Reboot/Restarting Browser/Server/Computer Run server on another port Open in Incognito Window Use another Computer to Test Ran python manage.py collectstatic/python manage.py collectstatic --clear/python manage.py collectstatic --noinput --clear, in here I found that after I ran this command, the modified static files will change back to the original unmodified version. Add a random tag at the end when loading the static file, /static/app_name/styles/css_name.css?v=aCtZoGSzObVTeNCAbWjPyLpyStrYek6A In setting.py add STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' Add the following in urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, view=cache_control(no_cache=True, must_revalidate=True)(serve)) All of the above methods didn't solve my issue. I saw someone has suggested Restart gunicorn/nginx will help, but seem it is on Linux but not Windows. What can it be? Maybe Django is saving some old static files somewhere and fetches them every time? -
How to let an authenticated user like a blog post in Django, update the like count and change the color of the heart icon
I started building my first Django Project a few days ago and I've been making progress, but for the past two days I've been stuck with the problem stated in the post's title. I can't seem to implement the like functionality in my web application. I'm going to just post the parts of my code that I believe would be helpful in aiding me. so, in my models.py I have - class Post(models.Model): image = models.ImageField() title = models.CharField(max_length=255) slug = models.SlugField(unique=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='posts', default='uncategorized') post = models.TextField() date = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(default=0) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) in my views.py I have - @login_required def like_post(request, post_id): post = get_object_or_404(Post, pk=post_id) if request.method == 'POST': if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) post.like_count -= 1 else: post.likes.add(request.user) post.like_count += 1 like = Like(user=request.user, post=post) like.save() post.save() return JsonResponse({'like_count': post.like_count}) else: return HttpResponseBadRequest() in my urls.py I have - path('like_post/<int:post_id>/', views.like_post, name='like_post') in my post_list.html I have - <form method="POST" action="{% url 'article:like_post' post.pk %}"> {% csrf_token %} <button class="like-button" data-post-id="{{ post.id }}"><i class="fas fa-heart{% if post.likes.filter(id=request.user.id).exists %} liked{% endif %}"></i>{{ post.like_count }}</button> {% endif %} <button class="comment-button"><i class="fa-solid fa-comment"></i>5 comments</button> </form> underneath the … -
django "copyOnWrite" for default model instances
Suppose I have a django application that provides Exercises. Those exercises have sub-categories and principles they belong to. Each Exercise belongs to one or no user. Simplyfied, they look like that: model Category(models.Model): owner = models.ForeignKey(AUTH_USER_MODEL, null=True, default=None) name = models.TextField() model SubCategory(models.Model): name = models.TextField() category = models.ForeignKey(Category, null=False) model Exercise(models.Model): owner = models.ForeignKey(AUTH_USER_MODEL, null=True, default=None) sub_categories = models.ManyToManyField(SubCategory) principles = models.ManyToManyField(Principles) # some other fields # ... What I want, is provide defaults (owner = None) for newly registered users. This would mean copying all principles, categories, subcategories and exercises upon the users registration. In addition, if I want to add a new exercise as default, I have to copy it for every user. I have already implemented the logic for copying everything (exchanging the foreign keys, etc.) This means that every user operates on their own set of data. No special cases except for the creation of new defaults. However, suppose I have 500 users and 100 default exercises, this amounts to 50k exercises alone. (Not to speak about the ~10 categories, with ~20 sub-categories each and ~120 principles) Seems not to scale too well. My second approach is some sort of "copy on write", where I … -
DJango forms that allow you to change the database of a specific user
I'm creating a Django social network application. My function intakes the request from a logged in user and changed their respective details based on the input of their forms. Forms.py class ProfileForm(forms.ModelForm): class Meta: model = AppUser fields = ['bio','profileimg'] Model.py class AppUser(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(blank=True) profileimg = models.ImageField(upload_to='profile_images', default='blank-profile-picture.png') def __str__(self): return self.user.username settings.html <form id="profile_form" method="post" action="/home/" enctype="multipart/form-data"> {% csrf_token %} {{ profile_form.as_p }} <input type="submit" name="submit" value="submit" /> </form> This is my current views code: `def settings(request): user_profile = AppUser.objects.get(user=request.user) if request.method == 'POST': profile_form = ProfileForm(request.POST or None,request.FILES or None, instance=user_profile) if profile_form.is_valid(): profile_form.save() else: return HttpResponse('Form is invalid') else: profile_form = ProfileForm(instance=user_profile) return render(request, 'settings.html', {'profile_form': profile_form})` I tried running the code but nothing happens in the database -
Django and celery tasks - how to display celery progress when redirecting
Hi I have a broad question about using celery, redis and django (along with celery-progress). I have a django cbv with a form. Upon a post request this starts some celery processes and I use a modified version of celery-progress to update the page with a progress bar for each task. I'm struggling to find the best way to do this in terms of redirection of the request. I have tried two ways: 1. class MyView(FilterView) template_name = '/path/to/template1.html' # code to create form in django-tables2 def post(self, request, *args, **kwargs): self.context = {'server': SERVER} submit = request.POST.get('submit', None) if submit: ids = request.POST.getlist('report_form') # get queryset from selected IDs qs = MyModel.objects.filter(id__in=ids) # create empty dictionary to store id and celery task task_dict = {} # loop through queryset for obj in qs: # execute report creator method (celery task) task = self.celery_create_reports(id=obj.id, user_id=request.user.id) # add obj as key and task id as value to dict task_dict[obj] = task.id logger.info(task.id) logger.info(f"task_dict={task_dict}") # add dict to context context = {'task_dict': task_dict,} # direct to different template template_name = '/path/to/template2.html' return render(request, template_name, context) return render(request, self.template_name, self.context) def celery_create_reports(self, id, user_id): """ """ # execute task return download_technical_reports.delay(id=id, user_id=user_id) ^ … -
cumulative sum on jsonfield dict - django - postgresql
I have a fixed set of product_ids (eg 0, 1, 2, 3) My shoppingcart model has a jsonfield containing a dict indicating how many products it has of each product_id: from django.db import models class ShoppingCart(models.Model): stats = models.JSONField() With for one object stats may be: stats = { "0": 4, # has 4 products of id 0 "3": 1, # has 1 product of id 3 } And another object my have: stats = { "0": 1, # has 1 product of id 0 "1": 1 # has 1 product of id 1 } Now I would like to calculate how many products there are in total of each product id, preferably using database functions on the jsonfield in django. For this example, the result should be: counts = { "0": 5, "1": 1, "2": 0, "3": 1 } Is there an efficient way of calculating this? Don't really know how to tackle this without looping over all objects. -
Django rest framework permission by custom role
I using Django Rest Framework and I have custom User model where is column Role and Hash Model.py class User(AbstractUser): Role = models.CharField() Hash = models.CharField() Serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'Role', 'Hash','is_staff') View.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [IsAuthenticated] this working fine! And my question is possible create view which show fields according by Role? For example... If user with admin role login then see everything.. fields = ('id', 'username', 'first_name', 'last_name', 'Role', 'Hash','is_staff') But if login user with role for example mamager then he see just this. fields = ('id', 'username', 'first_name', 'last_name', 'Role','is_staff') -
zsh: command not found: python | I just want my python files to run again
I was messing around with Django for a task on my bootcamp and now my VSCode won't run my python files using the run button in the top right. Here's what I see in my IDE: garethmorton@MacBook-Pro T28 2D Lists % python -u "/Users/garethmorton/VSCode Python/T28 2D Lists/minesweeper.py" zsh: command not found: python garethmorton@MacBook-Pro T28 2D Lists % If I right click and select run Python file in terminal my code runs and I get this: /usr/local/bin/python3 "/Users/garethmorton/VSCode Python/T28 2D Lists/minesweeper.py" garethmorton@MacBook-Pro T28 2D Lists % /usr/local/bin/python3 "/Users/garethmorton/VSCode Python/T28 2D Lists/minesweeper.py" How do I fix the file path so that I can just run the code like I used to? thanks I have tried a few things I was told to do but to be honest I don't understand it enough to explain. I would love to just be able to delete the IDE and reinstall. By the way I'm on mac so I'm not sure if that makes things more complicated I definitely have the python extension installed.. everything should be installed and ready because ive been running python code for months on my bootcamp -
Does indentation matter in django?
{% if object.name== '' %} {% block name %}{{ object.name}}{% endblock name %} {% else %} {% block name %} {{ object.alternate_name}} {% endblock name %} {% endif %} I have this code in Django and for some reason, I get the error that the block name has been repeated twice and that seems impossible because they're inside an if-else statement. However, I realized my indentation looks like it did above. I'm not sure whats causing this. -
Ckeditor - RichTextField in Template doesn't work - Django
I am trying to display the RichTextField in a Django Template. In the Admin Panel it works but not in the template. My Template called create.html: {% block main %} <div class="blocker" style="height: 100px;"></div> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Absenden</button> </form> {% endblock %} Forms.py: class Create(forms.ModelForm): content = RichTextField() title = forms.CharField(label='title', max_length=100) class Meta: model = Post fields = ['title', 'content'] Views.py def create(request): if request.method == 'POST': form = Create(request.POST) if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] Post(title=title, content=content).save() return redirect("../blog") else: form = Create() return render(request, 'create.html', {'form': form}) Thanks for answering :D I tried different things in the forms. -
Task not executed in Django's Celery
Since I am not an English speaker, I use translation tools to write my text. Please help me. Task not executed Here are the execution environment and messages Local PC OS windows 10 Python 3.8 DB Server CentOS 7.3 Redis 4.0.6 psql (PostgreSQL) 10.4 pip Package (relevant parts only) Package Version celery 5.2.7 Django 3.2 django-celery-results 2.4.0 django-redis 5.2.0 redis 4.1.1 *PROJECT\prj\settings.py CELERY_BROKER_URL = 'redis://:' + REDIS_PASSWORD + '@' + REDIS_HOST + ':6379/1' CELERY_RESULT_BACKEND = 'django-db' CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TIMEZONE = 'Asia/Tokyo' CELERY_TASK_TRACK_STARTED = True CELERY_TASK_TIME_LIMIT = 30 * 60 PROJECT\prj_init_.py from .celery import app as celery_app __all__ = ('celery_app',) PROJECT\prj\celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'prj.settings') app = Celery('prj') app.config_from_object('django.conf:settings', namespace="CELERY") app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') PROJECT\common\task.py from celery import shared_task @shared_task def load_croeds_csv(csv_file): print("start") print("end") return "ok" PROJECT\manegements\view.py class ProhibitedAreaCsvRegView(ContextRootStaff, FormView): template_name = 'manage/prohibited_area_csv.html' form_class = ProhibitedAreaCsvForm def get_context_data(self, **kwargs): context = super(ProhibitedAreaCsvRegView, self).get_context_data(**kwargs) title = "" context.update({ 'title': title, 'form': self.form_class() }) return context def form_valid(self, form): context = self.get_context_data(form=form) csv_file = form.cleaned_data["csv_file"] temp_path = save_csv_file(csv_file) result = load_croeds_csv.delay(temp_path) print(result.state) context.update({ 'result': result }) return self.render_to_response(context=context) (venv) PROJECT>celery -A prj worker -l info -------------- celery@HP1-USER10 v5.2.7 (dawn-chorus) --- … -
Django model unique constraint based on existing model data?
Is it possible to make reference to existing model data, as part of a Django unique constraint check? For example, class MyModel(models.Model): .... my_field = models.IntField(...) class Meta: constraints = [ models.CheckConstraint( check=models.Q(my_field__gte=MyModel.objects.all().last().my_field, name="example_constraint" ] In this pseudocode example, I query MyModel, fetching the latest record, and use the value of it's 'my_field' property as part of the constraint, when adding a new MyModel. -
How to change string representation in django
I have model with a str function def __str__(self): return f"{self.first_name} {self.last_name}" //output for example foo bar Now i a specific form with a dropdown menu filled with the model above. In the dropdown menu the options are showed as the str from the model (sow foo bar). In this model however i want to show only the lastname. How can ik change the str function for just this form ? -
Why django showing 'function' object has no attribute 'objects'?
'function' object has no attribute 'objects' is being shown when I try to fetch objects from database I was following code with harry playlist on django ,and trying to fetch product from database my problem.I have created 3 products in admin panel. I saw some solutions to my problem ,where the problem was solved by changing the function name. But my problem seems to be different. this is my models.py enter image description here function in view.py where I make the call....error showing on the line7 enter image description here trying to render it in html enter image description here -
How do I stop the camera after QR code is scanned?
I am using instascan.min.js for my QR scanner. According to the documentation, I simply need to add in scanner.stop() to my script to terminate the camera session once it has scanned a QR code. I am not sure where in the javascript code I can add that line or am I supposed to write another function? Have been stuck on this for quite some time. Hope to seek any assistance. Thank you! <script> var app = new Vue({ el: '#app2', data: { scanner: null, activeCameraId: null, cameras: [], scans: [] }, mounted: function () { var self = this; self.scanner = new Instascan.Scanner({ video: document.getElementById('preview'), scanPeriod: 5}); self.scanner.addListener('scan', function (content, image) { self.scans.unshift({ date: +(Date.now()), content: content }); }); Instascan.Camera.getCameras().then(function (cameras) { self.cameras = cameras; if (cameras.length > 0) { self.activeCameraId = cameras[0].id; self.scanner.start(cameras[0]); } else { console.error('There is no camera.'); } }).catch(function (e) { console.error(e); }); }, methods: { formatName: function (name) { return name || '(unknown)'; }, selectCamera: function (camera) { this.activeCameraId = camera.id; this.scanner.start(camera); this.scanner.stop(camera) } } }); </script> -
Django use related_name in all query set
So I have model class Category(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='upload') created_at = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=128) updated_at = models.DateTimeField(auto_now=True) parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) I want to make response look like { title: '', children: { title: '', chidlred:{ title: '', children } } } Im trying to use this in my views: @api_view(('GET',)) @permission_classes((AllowAny,)) def get_all_cats(req): queryset = Category.objects.all() for item in queryset: item['sub'] = queryset.children But it gives me enter image description here I understand I can use single query like Category.objects.first() and them use .children on it But i need all categories Thanks you so much! -
Python or JavaScript POST HTTP 1.1 error 404
I use python and JavaScript to make the website that you can register by linking with SQl. However, when I use the command flask run, there is POST /register HTTP 1.1 error. I can't register on the website and the website shows "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again." I would like to know that is the py or js is incorrect or something with the server. Thank you in advance I would like to know that is the py or js is incorrect or something with the server. -
How to filter by request user in Django-filter model
Im using django-filter package and i want to know how can i pass queryset in ModelChoiceFilter of request user in my django-filter model filters.py class PresenceDateFilter(django_filters.FilterSet): presence_info__counter_presence = ModelChoiceFilter(queryset=CounterParty.objects.filter(counter_user=request.user)) #request.user is not working work_date = DateTimeFromToRangeFilter( widget=django_filters.widgets.RangeWidget( attrs={'type': 'date', 'class': 'form-control'}, )) class Meta: model = PresenceDetailInfo fields = ('presence_info__counter_presence', 'work_date', ) -
Django e-commerce
I am having trouble saving and viewing the order history of my shopping cart after checkout. I am saving the order in the checkout session and trying to view it with the order history view. @login_required def order_history(request): orders = Order.objects.filter(user=request.user).order_by('-date_ordered') return render(request, 'order_history.html', {'orders': orders}) stripe.api_key = settings.STRIPE_SECRET_KEY YOUR_DOMAIN = @csrf_exempt def create_checkout_session(request): if request.method == 'POST': try: cart_items = CartItem.objects.filter(user=request.user) line_items = [] total_price = 0 for item in cart_items: line_items.append({ 'price': item.item.stripe_price_id, 'quantity': item.quantity, }) # Create checkout session with line items and total price checkout_session = stripe.checkout.Session.create( line_items=line_items, mode='payment', success_url=YOUR_DOMAIN + '/success', cancel_url=YOUR_DOMAIN + '/cancel.html', automatic_tax={'enabled': True}, ) # Create a new Order object and save it to the database order = Order.objects.create( user=request.user, total_price=sum(item.item.price * item.quantity for item in cart_items), ) order.checkout_session_id = checkout_session.id order.save() # Associate each cart item with the order instance for item in cart_items: item.order = order item.save() # Clear the user's cart cart_items.delete() except Exception as e: return HttpResponse(str(e)) return redirect(checkout_session.url) else: return HttpResponse("This page is only accessible via POST requests") @csrf_exempt def complete_hook(request): # Retrieve the request body and the Stripe signature header payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: # Verify the Stripe signature event … -
Access multilevel v-model from HTML (Nested element)
The HTML code is here <section id="id_element"> <label for="x1">x1 </label> <input type="text" id="x1" v-model="product.xs.x1" ></input> <label for="x2">x2</label> <input type="text" id="x2" v-model="product.xs.x2" ></input> </section> here is my javascript : <script> const create = Vue.createApp({ delimiters: ['[[', ']]'], data() { return { product : { xs: { "x1" : "alpha", "x2" : "beta" }, ys: { "y1": "one", "y2": "two", "y3": "three", "y4": "four" } } } } create.mount("#id_element"); </script> I want to access a nested element, but i had the error of Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'x1') how to access a multi level vue.js element from HTML. I tried both : v-model="product.xs["x1"]" and v-model="product.xs.x1" So please anyone having a solution for this, it will be great.