Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework pagination asking for authentication each time?
i have created an ListApiView with django rest framework. i have allotted isAuthenticated permissions for the users and it is processing well. i want to allow paginations in to ApiView. ok i have set paginations permission globally. when i want to render data in to html template using JavaScript the rest framework asking me for the user authentication which i have already authenticate. if i disable the paginations permission the data is rendering well but when i enable the paginations the system asking me again authentications. can anybody know where i make the mistake? api_viwes.py class ApprovedArticleList(ListAPIView): queryset = Article.objects.all() serializer_class = NewsSerializer filter_backends = (SearchFilter,) search_fields = ('title', 'author__username', 'content', 'category__name') settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 2, } -
Cannot resolve keyword 'post_id' into field. Choices are: comment, id, name, post_list
FieldError at /posts/1/ Cannot resolve keyword 'post_id' into field. Choices are: comment, id, name, post_list Request Method: GET Request URL: http://127.0.0.1:8000/posts/1/ Django Version: 3.1.4 Exception Type: FieldError Exception Value: Cannot resolve keyword 'post_id' into field. Choices are: comment, id, name, post_list Exception Location: C:\Users\Emiedonmokumo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py, line 1481, in names_to_path Python Executable: C:\Users\Emiedonmokumo\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.0 Python Path: ['C:\Users\Emiedonmokumo\Documents\mysite\admin', 'C:\Users\Emiedonmokumo\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\Emiedonmokumo\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\Emiedonmokumo\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\Emiedonmokumo\AppData\Local\Programs\Python\Python39', 'C:\Users\Emiedonmokumo\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Sun, 13 Dec 2020 11:42:03 +0000 -
Django - Catching UNIQUE costraint failed
I have a class method for creating a slug from title for url, which must be unique. In case the title is taken I would like to add id at the start of the slug, but my exception block is completely ignored and I have tried already with quite a few options. class Book(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=255, unique=True, null=True, blank=True) def save(self, *args, **kwargs): try: self.slug = slugify(self.title) except IntegrityError as e: if 'UNIQUE constraint failed' in e.args[0]: self.slug = slugify(str(self.id) + "-" + self.title) super(Book, self).save(*args, **kwargs) -
Django Ajax Call and response with Render
I am new to Python and Django and I would like to do a task where the user have 2 drop downs. Item drop down and Machine drop down. The Machine drop down is filled depending on the selection of the Item drop down and at the same time a table is refreshed depending on the selection of the 2 drop downs. I was thinking to do so, from JavaScript, onChange of Item drop down, I use an AJAX function which calls a function in view.py by providing Item selection as show in the Javascript part. On return of the Django function I use render return. Both the JavaScript and def load_machines seems to work fine but the return render(request, 'home.html', {'machines': machines}) is calling home.html but machines is empty. How shall I tackle such problem, any hint what to look at? JavaScript part <script> $("#exampleFormControlSelect1").change(function () { const url = $("#mainForm").attr("data-machines-url"); const itemId = $(this).val(); $.ajax({ // initialize an AJAX request url: url, data: { 'itemId': itemId // add the item id to the GET parameters }, success: function (data) { // `data` is the return of the `load_cities` view function } }); }); </script> Django Part view.py def … -
How to use something like a logout required in django views?
I have a login and sign_up view like this: def sign_up(request): form = UserCreationForm() registered = False if request.method == 'POST': form = UserCreationForm(data=request.POST) if form.is_valid(): form.save() registered = True context = { 'form':form, 'registered':registered, } return render(request, 'users/sign_up.html',context) def login_page(request): form = AuthenticationForm() if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username,password=password) if user is not None: login(request,user) return HttpResponseRedirect(reverse('index')) context = { 'form':form, } return render(request, 'users/login.html',context) What I actually want is that if the user is not logged out first and tries to access the sign up or login page, they are redirected to the logout page to first logout. So, they can't access these 2 pages unless they are logged out. How can I do this? -
ModuleNotFoundError: No module named in django
I want to generate some random information with faker. but when i execute the populating file an error showing ModuleNotFoundError: No module named 'practice'. here is my directory and code. I am beginner in python.project folder directory INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'first_app' ] `import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'practice.settings') import django django.setup() import random from first_app.models import AccessRecords,Webpage,Topic from faker import Faker fakegen = Faker() topics = ['search','social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def pupulate(N=5): for entry in range (N): top = add_topic() fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() webpg = Webpage.objects.get_or_create(topics=top,url=fake_url,name=fake_name)[0] acc_reg = AccessRecords.objects.get_or_create(name=webpg,date=fake_date)[0] if __name__ == '__main__': print ("populating script") pupulate(20) print('populating complete')` -
How to connect React to Django?
I am using reactJS as the frontend while Django at the backend. When I make a request from react to Django(react is running at http://127.0.0.1:3000 while Django is running at http://127.0.0.1:8000), Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/categories. (Reason: CORS header 'Access-Control-Allow-Origin' missing). Most likely, it's occurring due to CORS issue. So I installed django-cors-headers and make following changes in my settings.py:- INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_cleanup.apps.CleanupConfig', 'myapp', 'corsheaders' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:3000" ] But the error still persists. How can I make it work? -
Where to put Django permissions logic?
I have a 'View' which is mostly contain a 'Form', I need one User-Group with edit-permission to see it and edit form, And another User-Group with just view-permission to only can view information, And they can't edit information. What is the best way to achieve this behavior? I'm aware of 'permission_required' decorator and 'PermissionRequiredMixin' mixin but they are effect on entire view which is not my goal. I guess i should use user.has_perm() but I'm not sure where to put the logic, in views or forms or somewhere else... -
Inlineformset_factory: validation failed (this field is required)
I have inlineformset_factory form with 3 fields. But when I update form, a new blank line is created. And if I decide to leave this line empty, validation failed because field required So issue come from "extra" parameters in inlineformset_factory MenuFormset. I thought about using a specific inlineformset_factory UpdateMenuFormset with extra=0 for Update view but it is probably not a good way doing this How can I manage this validation? models.py class Orders(SafeDeleteModel): """ A class to create a new order instance in the Schitt's Creek Cafe Tropical. """ _safedelete_policy = SOFT_DELETE_CASCADE order_id = models.AutoField("Order id", primary_key = True) table = models.ForeignKey(Tables, on_delete = models.CASCADE) # related table customers = models.IntegerField("Number of customer", null=True, blank=True) split_bill = models.IntegerField("Split bill", null=True, blank=True) delivered = models.BooleanField("Delivered", null=True, blank=True, default=False) paid = models.BooleanField("Available", null=True, blank=True, default=False) created_at = models.DateTimeField("Date created", auto_now_add = True) log = HistoricalRecords() class Orders_Menus(SafeDeleteModel): """ A class to create a new Orders_Menus instance in the Schitt's Creek Cafe Tropical. """ _safedelete_policy = SOFT_DELETE_CASCADE order = models.ForeignKey("Orders", on_delete = models.CASCADE) menu = models.ForeignKey("Menus", on_delete = models.CASCADE) cooking = models.IntegerField("Cooking", default=0, null=True, blank=True) tone = models.IntegerField("Tone", default=0, null=True, blank=True) log = HistoricalRecords() class Meta: db_table = 'Orders_Menus' forms.py MenuFormset = inlineformset_factory( … -
Failed lookup for key [category] in [{'True': True, 'False': False, 'None': None}, {}, {},
I'm getting this error Failed lookup for key [category] in [{'True': True, 'False': False, 'None': None}, {}, {}, .... in my application i have category and subcategory which repeated too much in my view for every function and for child or subcategory i used pip install django-mptt but it was Ok and worked will. so i decided to use custom template tags instead but right now I'm facing with this error for more info you can take a look to my code. myapptags.py from django import template from django.db.models import Sum from django.urls import reverse from mysite import settings from order.models import ShopCard from product.models import Category register = template.Library() @register.simple_tag def categorylist(): return Category.objects.all() code for views.py import json from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.urls import reverse from django.shortcuts import render, redirect from django.contrib import messages from django.template.loader import render_to_string from . models import Settings, ContactMessage, FAQ from product.models import Category, Comment, Images, Product, Variants from . forms import ContactForm, SearchForm from product.forms import CommentForm def index(request): setting = Settings.objects.get(pk=1) # category = Category.objects.all() products_slider = Product.objects.all().order_by('id')[:4] #first 4 product products_latest = Product.objects.all().order_by('-id')[:4] # latest products_picked = Product.objects.all().order_by('?')[:4] # random page = "index" context = { 'setting': … -
NoReverseMatch at /job_category/IT/
Reverse for 'job_category' with keyword arguments '{'id': <Category: Government>}' not found. 1 pattern(s) tried: ['job_category/(?P<category_slug>[^/]+)/$'] {% extends 'base1.html' %} {% block content %} <div class="left col-sm-4" style="float:left; width: 360px;"> <h6 class="p-2" style="background:#A9CCE3; color:#2F4F4F;">JOB CATEGORIES</h6> <ul class="list-group"> {% for x in categories %} <li class="list-group-item c1 list-group-item-action" style="color: rgb(2,96,170);"> <a href="{{ x.get_absolute_path }}"></a> <div class="p-2"> <h7 class="card-title"> {{x.name}} </h7> </div> <div class="overlay1"></div> </li> {% endfor %} </ul> </div> <div class="right col-sm-8" style="float: right; width:825px;"> <!--{% if category %}{{category.name}}{% endif %} !--> <div class="row container-fluid"> {% for i in jobs %} <div class="col-sm-3 mt-3"> <div class="card c1"> <div class="overlay1"></div> <div class="card-body"> <h5 class="card-title" style="color: rgb(2,96,170);"> {{job.post}}</h5> <h6 class="card-text" style="color: rgb(85, 85, 85);"> {{job.job_id.comp_name}}</h6> <p><i class="fas fa-map-marker-alt mr-1"></i>{{job.address}}<i class="far fa-calendar-alt ml-3 mr-1"></i>{{job.todate|date:'d M, Y'}}</p> <a href="{% url 'job_detail' job.job_id.id %}" class="btn btn-primary btn-sm right" style="position:relative; float:right;">View more</a> </div> </div> </div> {% endfor %} </div> </div> {% endblock content %} views.py def job_category(request, category_slug=None): category = None job_requirements = [] categories = Category.objects.all() jobs = Job.objects.all() if category_slug: category = Category.objects.get(slug=category_slug) print(category.slug) jobs = Job.objects.filter(job_category=category.slug) for job in jobs: job_requirements.append(JobRequirements.objects.get(job_id=job)) return render(request, 'JobCategory/category.html', {'categories': categories, 'jobs': job_requirements}) urls.py path('job_category/<str:category_slug>/', views.job_category, name='job_category'), Models.py class Category(models.Model): name = models.CharField(max_length=40, blank=True, null=True) slug = models.CharField(max_length=4, unique=True) def … -
Specify size of images in django
I am currently working on a django blog. However, I am experiencing some difficulties with the size of the post thumbnails. Here's a picture: What I marked in yellow is how the image should be filling the space. The width is fine, but the heigh isn't working well as you can see. Here's the code: {% extends 'base.html' %} {% load static %} {% block content %} <style> img { height: 100%; width: 100%; } </style> <!-- Post--> {% for obj in object_list %} <div class="row d-flex align-items-stretch"> {% if not forloop.first and not forloop.last %} <div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div> #Here's the image {% endif %} <div class="text col-lg-7"> <div class="text-inner d-flex align-items-center"> <div class="content"> <header class="post-header"> <div class="category"> {% for cat in obj.categories.all %} <a href="#">{{ cat }}</a> {% endfor %} </div> <a href="{{ obj.get_absolute_url }}"> <h2 class="h4">{{ obj.title }}</h2> </a> </header> <p>{{ obj.overview|linebreaks|truncatechars:200 }}</p> <footer class="post-footer d-flex align-items-center"><a href="#" class="author d-flex align-items-center flex-wrap"> <div class="avatar"><img src="{{ obj.author.profile_picture.url }}" alt="..." class="img-fluid"></div> <div class="title"><span>{{ obj.author }}</span></div></a> <div class="date"><i class="icon-clock"></i> {{ obj.timestamp|timesince }} ago</div> <div class="comments"><i class="icon-comment"></i>{{ obj.comment_count }}</div> </footer> </div> </div> </div> {% if forloop.first or forloop.last %} <div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div> #Here's the … -
Disallowed host in django
I am trying to deploy django app using apache2 and mod_wsgi. Below is the error it is throwing: DisallowedHost at / Invalid HTTP_HOST header: '10.1.1.1:9090'. You may need to add '10.1.1.1' to ALLOWED_HOSTS. My settings.py has ALLOWED_HOSTS = [] Why I am getting disallowed host? -
how to update plotly graph using ajax in django
I want to update my plotly graph using ajax in my Django project. This is what I tried so far. I'm following this guide to doing it and I'm totally new in jquery and ajax. urls.py urlpatterns = [ path('', views.index, name='index'), path('get/ajax/updategraph', views.updategraph, name = "updategraph") ] In views.py I defined a updategraph function(view) to do the job for GET request. def updategraph(request): # preparing my data data = pd.read_excel("/Sensorik.xlsx") columns = [] df_new = pd.DataFrame() df_georgian = pd.DataFrame() # selecting needed columns for item in data.columns: if not ("Unnamed" in item): columns.append(item) for item in columns: df_new.loc[:, item] = sensor.loc[:, item] df_new = df_new.drop(df_new.index[[0, 1]]) ind = df_new.index.size df_new.index = range(ind) df_georgian = df_new.set_index('Timestamp') # request should be ajax and method should be GET. if request.is_ajax and request.method == "GET": # get the data from the client side. coding = request.GET.get('coding') # check for the data in the database. if coding: trace2 = go.Scatter(x=df_georgian.index, y=df_georgian.loc[:, df_georgian.columns[2]], mode='lines') fig_new = go.Figure(data=[trace2]) plot_div_new = plot(fig_new, config=config, output_type='div') ser_instance = serializers.serialize('json', [ plot_div_new, ]) # send to client side. return JsonResponse({"instance": ser_instance}, status=200) else: # if data not found, then graph wont change return JsonResponse({}, status = 200) return JsonResponse({}, status … -
python (django) - conditional list comprehension db query
I have a table of selling offers for a book where one user may offer more copies (only one active, meaning not sold per user) and I would like to return true if at least one offer is set to is_sold = False. Can this be achieved with list comprehension? I am not really sure if this actually checks each book.is_sold and returns True when it finds False, but I'm not really getting result I'm looking for. return render(request, 'books/book.html', { 'book': book, 'is_offered': [True if not book.is_sold else False for book in BookSellers.objects.filter(book=book)], }) -
How can i receive JSON data from Django backend to Angular frontend
i have an application with Django on backend and i am using Angular 11 on my front. How could i receive data from db (sending JSON from back? or any other ways) and use it on my templates in Angular? I would be grateful if you provide any nice articles or guides with code examples. -
I want to run my Django project from a local branch. Is there a way to do this?
I'm working on a project and I want to test a feature locally for which I created a local git branch. I want python manage.py runserver to run changes made in the feature branch but it still runs from the master branch. It would be great if someone can explain why it does this as well. -
modelformset_factory duplicate queries issue
I want to know if there's a way to cache queryset when rendering each form of formset, like similar way as select_related. My formset made by modelformset_factory causes db hits for every form generated. If I have 100 instances, queries are dupliacated 100 times plus. I used select_related when I made queryset as an argument to formset, but it doesn't seem to cache it. views.py .... queryset=Allocate.objects.select_related('license').filter( date=date, license__number__range=(2101, 2105) ) # formset 설정 AllocateFormSet = modelformset_factory( Allocate, form=AllocateModelForm, extra=0 ) if request.method == 'GET': formset = AllocateFormSet(queryset=queryset) .... models.py class Allocate(models.Model): license = models.ForeignKey( 'license.License', verbose_name='차번', on_delete=models.CASCADE, ) morning_driver = models.ForeignKey( 'employee.Employee', verbose_name='오전기사', on_delete=models.CASCADE, related_name='morning_drivers', blank=True, null=True ) afternoon_driver = models.ForeignKey( 'employee.Employee', verbose_name='오후기사', on_delete=models.CASCADE, related_name='afternoon_drivers', blank=True, null=True ) forms.py class AllocateModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.label_suffix='' for key in self.fields.keys(): self.fields[key].required = False self.fields['license'].disabled = True license_qs = License.objects.filter(id=self.instance.license_id) self.fields['license'].queryset = license_qs self.fields['morning_driver'].queryset = Employee.objects.none() self.fields['afternoon_driver'].queryset = Employee.objects.none() When I see SQL section from django-debug-toolbar, it says I have quite many duplicate queries. For every form it adds up 3 queries even when I set queryset of both morning_drvier and afternoon_driver none. Imagine how much pain I would have if I include actual queryset for the two … -
Django redirect link
I am working on a Django project and want to redirect the user to the download page when the user click on the button. I have tested the attribute store in book.download_url tested view enter image description here HTML file enter image description here -
NameError: name 'o' is not defined Error in django app
hi i'm soo new in django ,i'm try to learning this and i'm sorry i'm not so good in English I have a problem with my django app,I remove my products app for more practicing and when i use 'migrate' or 'makemigrations' code ,i get an error Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle self.check(databases=[database]) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\clpxv\Desktop\Projects\venv\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return … -
Django python regex to include dollar symbol in URL
I have a Django 1.5 app wherein a particular URL is used to generate code 128 barcodes. I have a regular expression written for this URL which is as follows ... url(r'^code/(?P<barcode>[.a-zA-Z0-9_-]+)/$', CreateBarcode.as_view(), name='create_barcode'), ... This works fine for generating barcodes for values such as www.xyz.com/code/123ABC456/ www.xyz.com/code/AAA-BBBB-CCC/ www.xyz.com/code/A_B_C/ I recently had a problem where I had to generate a barcode for a value which contains a dollar symbol $ in it. I have tried out the below regular expressions but to no success url(r'^code/(?P<code>[$.a-zA-Z0-9_-]+)/$', ....), url(r'^code/(?P<code>[\$.a-zA-Z0-9_-]+)/$', ....), url(r'^code/(?P<code>[.a-zA-Z0-9_-][$]+)/$', ....), url(r'^code/(?P<code>[.a-zA-Z0-9_-\$]+)/$', ....), All of these return a 404 response since the URL patterns could not be matched. Let me know if there is any way of getting this implemented? -
Establishing M2M relationship with auth_user model
I am making a webapp based on django and kinda new to it , learning from the documentation. I am leveraging the default User model by django to create the customer database and authenticate them . Now I want to relate a field of a custom model e.g. iname with an M2M relationship to User . Usually I can create an M2M field and foreign key among two custom models , but here one of them is defined by default , so not sure how to use its fiels. Looking for a suggestion here. class sale_info(models.Model): icategory = [('chair', 'Chair'), ('table', 'Table'), ('book', 'Book'),('overcoat', 'Overcoat')] iname = models.CharField(max_length=20, choices=icategory) idesc = models.TextField(max_length=300, null=True) def __str__(self): return self.iname, self.icategory -
cart.js:6 Uncaught SyntaxError: missing ) after argument list
please answer this question i'm working on ecommerce website following the youtube chhanel name Dennis lvy https://www.youtube.com/channel/UCTZRcDjjkVajGL6wd76UnGg and i got this error in my js file var updateBtns = document.getElementByClassName('update-cart') for(var i=0;i<updateBtns.length; i++){ updateBtns[i].addEventListener('click', funcation(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', product, 'action:',action) }) } error in line 6 updateBtns[i].addEventListener('click', funcation(){ like cart.js:6 Uncaught SyntaxError: missing ) after argument list can anyone tell me how can i solve it? <button data-product={{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> -
How to connect Django and .net core project as a single application?
I want to connect Django project and .NET core project because I want it tack advantage of good library available in python so I will make one strong .NET core project.so through some lite on it. -
Hiding some of the fields in django forms
I am using modelformse_factory, where I can set extra value, which corresponds to the number of file inputs, that are in my form. ImageFormSet = modelformset_factory(PostImage,form=ImageForm, extra=3) Can I somehow limit the fields to some number, lets say 1 and then show 2 other by clicking some button? So basically the form renders all 3 fields, but two of them are hidden until I press a button?