Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django importing a custom user model
I have a Django app with a custom user model. I am attempting to import this model into another app. So far I can't figure out how to do this. The customer user model at accounts/models.py is from django.db import models from machina.core.db.models import get_model from django.db.models import Q from django.contrib.auth.models import Group # signals imports from django.dispatch import receiver from django.db.models.signals import ( post_save ) Forum = get_model("forum", "Forum") class CustomUser(AbstractUser): first_name = models.CharField(max_length=250, null=True) last_name = models.CharField(max_length=250, null=True) age = models.PositiveIntegerField(null=True, blank=True) business_name = models.CharField(max_length=250, null=True) business_location_state = models.ForeignKey( Forum, null=True, on_delete=models.SET_NULL, limit_choices_to={"lft": 1}) business_location_county = models.ForeignKey( Forum, null=True, on_delete=models.SET_NULL, related_name='county') business_location_city = models.CharField(max_length=1024, null=True) business_zipcode = models.CharField(max_length=12, null=True) The code I most recently tried to import this model is: from django.db import models from django.contrib.auth.models import User from django_tenants.models import DomainMixin, TenantMixin from django.utils.translation import ugettext as _ from localflavor.us.models import USStateField from accounts.models import CustomUser class Tenant(TenantMixin): user = models.ForeignKey('CustomUser', on_delete=models.SET_NULL, null=True) company_name = models.CharField(max_length=100) address_1 = models.CharField(_("address"), max_length=128) address_2 = models.CharField(_("address cont'd"), max_length=128, blank=True) city = models.CharField(_("city"), max_length=64) state = USStateField(_("state")) zip_code = models.CharField(_("zip code"), max_length=5) created_on = models.DateField(auto_now_add=True) When I attempt to start the server I get this error: django.core.management.base.SystemCheckError: SystemCheckError: System check identified … -
AWS EB CLI deployment Dango - Static files showing for web app but not showing for Admin panel
I have recently managed to setup and deploy my Django web app to AWS via EB CLI, everything looks fine on the web app however when I visit the admin panel I noticed the static files are not loading at all (but load fine on local server). I see on the S3 bucket admin static files were uploaded in the following structure (my app is called wfi_workflow): .elasticbeanstalk admin/ css/ fonts/ img/ js/ resources/ wfi_workflow/ Please see following relevant code in my project for static files: Settings BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') .ebextensions/django.config container_commands: 01_sh_executable: command: find .platform/hooks/ -type f -iname "*.sh" -exec chmod +x {} \; option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: wfi_workflow.settings aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static /static_files: static_files aws:elasticbeanstalk:container:python: WSGIPath: wfi_workflow.wsgi:application .ebextensions/packages.config packages: yum: python3-devel: [] mariadb-devel: [] .platform/hooks/predeploy/01_migrations.ssh #!/bin/bash source /var/app/venv/*/bin/activate cd /var/app/staging python manage.py makemigrations python manage.py migrate python manage.py createsuperuser python manage.py collectstatic --noinput Help is much appreciated on this, Thanks. -
Field 'maca2' expected a number but got 'Select'
class Maca(models.Model): class Maca2(models.IntegerChoices): Personal = 1, Work = 2, Transport = 3, __empty__ = _('Select') When I submit as empty value I got the following error Field 'maca2' expected a number but got 'Select'. -
@login_required decorator is not working (Django)
I am trying to build a social media like thing and have created the login and signup feature. For home page I have added login_required decorator and even added LOGIN_URL in settings.py but still I am able to access the home page without login i.e login_required decorator is not doing its job. Here is my view function code @login_required def home(request): return render(request, 'home/home.html') Here is my code in settings.py LOGIN_URL = '/login' Can anyone find out what might be the problem? -
Create and Retrive django session objects
I have customised the django default user table and used it for user signup and login. Now I need to create django session object to create a shopping cart (like that of an ecommerce website) which is user specific.How to create and retrive session objects in django?? -
related_name in many to many field
Below is my code. class Thing(models.Model) : title = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] ) text = models.TextField() owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='fav_thing_owner') favorites = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Fav', related_name='favorite_things') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # Shows up in the admin list def __str__(self): return self.title class Fav(models.Model) : thing = models.ForeignKey(Thing, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='favs_users') # https://docs.djangoproject.com/en/3.0/ref/models/options/#unique-together class Meta: unique_together = ('thing', 'user') def __str__(self) : return '%s likes %s'%(self.user.username, self.thing.title[:10]) But I got confused related_name in ManytoMayFied. for example, in my code I can get user's Thing(my model name) using user.fav_thing_owner. But in ManyToManyField, I have two related_name(favorite_things, favs_users). user.favorite_things and user.favs_users get same object..? -
python single and multiple button operation
I have a concern on how to stimulate single or multiple button click operations. --code sample : .js file jQuery.ajax({ url : "/", type :"POST", data : { selected_obj : clicked_btn }) .py file object_selected = request.forms.get('selected_obj') # This (object_selected) return data like # data_returned = (0.48, 0.65, 2.32) -what i need is when the button clicked for the first time data_returned gets multiplied which it is no big deal. But when clicked for the second time either same or another button that has same output i need to (multiply the returned data) for the same or another button and sum it with the previous data(button clicked for the first time), and so on .. -
Django ORM DB Query Optimization
I have a Query that consists of two DB hits. which the first contains 'aggregate' - so it perform immediately. I want to know if I can reduce it to only one DB hit. The query is: "Find customers that their id's numbers are bigger than all of texas's customers id's." The two querysets are: highest_tx_id = Customer.objects.filter(state='TX').aggregate(Max('id')) res = Customer.objects.filter(id__gt=highest_tx_id['id_max']) Adding an example: >>> reset_queries() >>> highest_tx_id = Customer.objects.filter(state='TX').aggregate(Max('id')) >>> res = Customer.objects.filter(id__gt=highest_tx_id['id__max']) >>> connection.queries [{'sql': 'SELECT MAX("customer"."id") AS "id__max" FROM "customer" WHERE "customer"."state" = \'TX\'', 'time': '0.001'}] >>> res <QuerySet [<Customer: Customer object (550)>, <Customer: Customer object (551)>, <Customer: Customer object (552)>, <Customer: Customer object (553)>, <Customer: Customer object (555)>, <Customer: Customer object (661)>, <Customer: Customer object (665)>]> >>> connection.queries [{'sql': 'SELECT MAX("customer"."id") AS "id__max" FROM "customer" WHERE "customer"."state" = \'TX\'', 'time': '0.001'}, {'sql': 'SELECT "customer"."id", "customer"."fname", "customer"."lname", "customer"."address", "customer"."city", "customer"."state", "customer"."zip_code", "customer"."phone", "customer"."company_name" FROM "customer" WHERE "customer"."id" > 444 LIMIT 21', 'time': '0.001'}] >>> Any way to do these type of queries using 1 DB hit ? -
Don't render abel for id in django form
Is it possible not to render the for attribute of a label? I want <label>Text</label> instead of <label for="id_i">Text</label> ? -
why celery doesn't get the task in django?
i'm new in celery there is a simple task that I want to use celery in Django but in celery log there isn't any message to get task. these are my codes: celery.py: from __future__ import absolute_import, unicode_literals from celery import Celery app = Celery('kia', broker='redis://localhost:6379/0') app.conf.update( result_serializer='json', accept_content = ['application/json'], task_serializer = 'json' ) app.autodiscover_tasks() tasks.py: import section . . . logger = get_task_logger('__name__') @task(name="send_sms_task") def send_sms_task(text, phone_number): logger.info("sms sented") return sms(text, phone_number) views.py: import section . . . @api_view(['GET',]) @permission_classes((AllowAny,)) def TestSMS(request): if request.method == 'GET': x = send_sms_task.apply_async(["something", "somethingelse"]) data= {"OK"} return Response(data) sms.py: def send_sms(text,phone_number): print("an api service that work correctly") finally this is my tree project: ├── account │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── permisions.py │ ├── serializers.py │ ├── sms.py │ ├── tasks.py │ ├── urls.py │ ├── utils.py │ └── views.py ├── db.sqlite3 ├── project │ ├── celery.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py function in sms.py work without celery but when I try to use celery nothing happens in celery log in addition in 2 case(with celery and without it) I get 200 … -
Django repeated forms
I have a form with a dropdown select option with possible options of 1,2,3,4 or 5. Based on the user select option 'x', I render same form repeated 'x' many times. Upon submit, I try to fetch the data using following in my view userprofileForm(request.POST) but this fetches just the last entry or most recent entry and not all the 'x' entries. Here is the rough HTML for my rendered form. In this instance the user selects option 2 so the form has a div repeated 2 times. <form ... > <div> <label...> <input...> </div> <div> <label...> <input...> </div> </form> Upon hitting submit button, the view for registeration is triggered and like I explained above in the beggining doing userprofileForm(request.POST) does not fetch both the 2 entries but just the last one. How can this be fixed so I have all form data of both the divs and how do I access it? -
How to pass search input value in output
I have search bar that renders the list of elements that user whats to find. I'd like to pass the input value to output html so if user is searching for article 1 then I want to display above the list the query name. I tried to put query, lookup but it doesn't work. views.py def search_qa_results(request): query = request.GET.get('q') qa_list = QA.objects.filter(title__icontains=query) if query is not None: lookups = Q(title__icontains=query) qa_list = QA.objects.filter(lookups) context = { 'qa_list': qa_list } return render(request, 'search/search_qa.html', context) index.html <form action="{% url 'search_qa_results' %}" method="get" id="search"> {% csrf_token %} <div class="searchbar" id="autocomplete"> <input name="q" type="text" placeholder="Type your question" class="search_input"> <a href="{% url 'search_qa_results' %}" class="search_icon"><i class="fas fa-search"></i></a> <ul class="autocomplete-result-list"></ul> </div> </form> search_results.html {% extends 'base.html' %} <title>{% block title %}Q&A results{% endblock %}</title> {% block content %} <link rel="stylesheet" type="text/css" href="/static/search_qa.css"> <div class="d-flex justify-content-start"> Search results for my question: {{WHAT TO PUT HERE?}}</div> <div class="container h-100 pb-4"> <div class="d-flex justify-content-end h-100 pb-4"> {% for qa in qa_list %} <div class="card text-dark bg-light mb-3 text-left"> <a href="{{ qa.get_absolute_url }}"> <h5 class="card-header">Q: {{qa.title}}</h5> <div class="card-body"> <div class="card-title text-justify">A: {{ qa.answer }}</div> </div> <div class="card-footer"> <small class="text-muted">Published: {{qa.publish}}</small> </div> </a> </div> {% empty %} <p>No results</p> {% … -
Django SESSION_EXPIRE_AT_BROWSER_CLOSE doesn't work
I would like to log out user if browser is closed. I added SESSION_EXPIRE_AT_BROWSER_CLOSE = True to my settings.py and the following function to my base.html file but it doesn't work. $(document).ready(function(){ $(window).on("beforeunload", function(e) { $.ajax({ url: logout_view, method: 'GET', }) }); }); What am I missing and how to solve it? I am using Django 3.2. -
Input Tag and spaces in Strings
model.py class Cartrecord(models.Model): cartid=models.AutoField(primary_key=True) cart_user=models.ForeignKey(User,on_delete=models.CASCADE) json_data=models.CharField(max_length=500,default="0") def __str__(self): return self.cart_user.username views.py param_cart=Cartrecord.objects.get(cart_user=request.user) params['cart']=param_cart params['cart_length']=len(param_cart.json_data) return params html <input id="cart_data" type="text" value={{cart.json_data}}> <input id="cart_length" type="hidden" value={{cart_length}}> enter code here cart.json_data is supposed to be printed as {"product7":{"0":1,"1":"USB cable","2":"250"},"product9":{"0":1,"1":"Sony Tv","2":"40000"},"product10":{"0":1,"1":"LG Refrigerator","2":"30000"},"product4":{"0":1,"1":"mobie","2":"10000"},"product6":{"0":1,"1":"bag","2":"1000"}} Instead im getting this {"product7":{"0":1,"1":"USB I have tried it with different sets of json data, but each time the string got sliced when it meets the space But later i have tried the same thing using textarea by replacing input tag, <textarea id="cart_data" type="text">{{cart.json_data}}</textarea> And i got my json string properly Can someone explain this behavior? -
How to Preview and Edit, Login the django model form after finishing the user signup in django?
models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) mobile_number = models.IntegerField(blank=False, null=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] customer = models.BooleanField(default=False) vendor = models.BooleanField(default=False) id = models.AutoField(primary_key=True, editable=True) userid= models.CharField(max_length=100, unique=True, null=True) objects = UserManager() def __str__(self): return self.email forms.py class VendorCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ['email','first_name','last_name','mobile_number'] def save(self, commit=True): user = super().save(commit=False) user.vendor = True if commit: user.save() return user views.py def VendorSignup(request): vendorform = VendorCreationForm() if request.method == 'POST': vendorform = VendorCreationForm(request.POST) vendordetailform = VendorAdminDetailsForm(request.POST, request.FILES) if vendorform.is_valid(): new_user = vendorform.save() new_user.is_active = False new_user.save() return redirect('vendor_preview') else: vendorform = VendorCreationForm() return render(request, 'vendor/signup.html', {'vendorform': vendorform}) def VendorPreview(request): details = CustomUser.objects.filter(id=request.user.id) return render(request,'vendor/preview.html', {'details':details}) My template: signup.html <div class="container"> <h1>VENDOR SIGNUP</h1><br> <form method="POST" action="{% url 'vendor_signup' %}" enctype='multipart/form-data'> {% csrf_token %} {{ vendorform.email|as_crispy_field}} {{ vendorform.first_name|as_crispy_field}} {{ vendorform.last_name|as_crispy_field}} {{ vendorform.mobile_number|as_crispy_field}} {{ vendorform.password1|as_crispy_field}} {{ vendorform.password2|as_crispy_field}} <button type="submit" class="btn btn-dark" value="Submit">Submit</button>&ensp; <a href="{% url 'login' %}">Already a Vendor?</a> </form> </div> preview.html <caption>Please, Check your details.</caption> <table class="table table-hover table-bordered mt-3"> <thead> <tr> <th scope="col">Email Address</th> <th scope="col">First Name</th> <th scope="col">Last Name</th> <th scope="col">Mobile Number</th> </tr> </thead> <tbody> {% if details %} {% for data in details %} <tr> <td>{{data.email}}</td> … -
how export filtered data in django
I am using class based view to such for data and I want to export the output from search. The output is from two dates search. I use below code: class expenses_list(ListView): model = EXPENSES template_name = 'cashes/expenses_list.html' paginate_by=10 def get_queryset(self): filter_val1=self.request.GET.get("filter1","") filter_val2=self.request.GET.get("filter2","") order_by=self.request.GET.get("orderby","-date_of_operation") if filter_val1!="" and filter_val2!="": reqo=EXPENSES.objects.filter(Q(created_at__range= [filter_val2,filter_val1])).order_by(order_by) else: reqo=EXPENSES.objects.filter().order_by(order_by) return reqo def get_context_data(self,**kwargs): context=super(expenses_list,self).get_context_data(**kwargs) context["filter1"]=self.request.GET.get("filter1","") context["filter2"]=self.request.GET.get("filter2","") context["orderby"]=self.request.GET.get("orderby","id") context["all_table_fields"]=EXPENSES._meta.get_fields() return context and I have this as interface enter image description here the following export code is not working as the value of date fields are empty value def exporexpensescsv(request,**kwargs): filter_val1=request.GET.get("filter1") filter_val2=request.GET.get("filter2") print(filter_val1) print(filter_val2) response=HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=expenses' + str(datetime.datetime.now())+'.csv' writer = csv.writer(response) writer.writerow(['Categoty','Beneficiary','Description','Operation Date','Amount','Account Number','Paymrnt Date','Status']) expes = EXPENSES.objects.filter(Q(created_at__range=[filter_val1,filter_val2])) # expes = EXPENSES.objects.all() for exp in expes: writer.writerow([exp.category,exp.beneficiary,exp.description, exp.date_of_operation,exp.amount,exp.account_number,exp.payment_date, exp.status]) return response but when I want to export with expes = EXPENSES.objects.all() it works well. Assist to be able to export the filtered data. -
Django - Вывод формы вопрос|вырианты ответов [closed]
помогите пожалуйста, нужно сделать вопросник(вопрос и варианты ответы) Сделал простую связанную модель: class Questions_set(models.Model): title = models.CharField(max_length=500, verbose_name='Вопрос') def __str__(self): return self.title class Meta: verbose_name = 'Вопросы' verbose_name_plural = 'Вопрос' class Answers_set(models.Model): title = models.CharField(max_length=500, verbose_name='Вопрос') correct = models.BooleanField(verbose_name='Правильный ответ') key_questions_set = models.ForeignKey(Questions_set, on_delete=models.CASCADE, related_name='question') Заполнил таблицы.Как вывести в шаблон вопрос и варианты ответов к нему в форме или это не через форму решается?Спасибо -
how to successfully upload BLOB images to django ImageField
I am using django rest framework(version 3.12.2) for my backend, and React/Next js in my front end. my goal is pretty straightforward, I want to upload BLOB images via POST request to django. but unfortunately I receive this error message {"photo_main":["The submitted data was not a file. Check the encoding type on the form."]} has anyone ever encountered this problem and was able to solve it? the model class Recipe(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) author = models.ForeignKey(get_user_model() , on_delete=models.CASCADE, null=True, related_name='author') photo_main = models.ImageField(upload_to='media/', blank=True) title = models.CharField(max_length=150) description = models.TextField(blank=True) the view class RecipeCreate(CreateAPIView): permission_classes = (permissions.IsAuthenticated, ) queryset = Recipe.objects.all() serializer_class = RecipeCreateSerializer def perform_create(self, serializer): '''save the the current logged in user as the author of the recipe''' serializer.save(author=self.request.user) I'll appreciate every help that I can get, thanks in advance -
Django reverse returns the error 'view_name' is not a valid view function or pattern name
Here is my view: class OrganizationViewSet(AbstractEntityViewSet): serializer_class = OrganizationSerializer permission_classes = [IsAuthenticated] model = serializer_class.Meta.model queryset = model.objects.all() I registered it as follows: router.register(r"organizations", OrganizationViewSet, basename="organizations") Now, I am trying to use build_absolute_url as follows: HttpRequest().build_absolute_uri(reverse('organizations', args=(self.parent_organization.slug,))), It returns the following error: File "C:\Samir\Pro\near_shop\venv\lib\site-packages\django\urls\base.py", line 86, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Samir\Pro\near_shop\venv\lib\site-packages\django\urls\resolvers.py", line 694, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'organizations' not found. 'organizations' is not a valid view function or pattern name. The basename on the router is "organizations", then why it can't find it? -
How to save shipping information when proceed with payment in Django Razorpay gateway?
I am trying to submit the data in the database whenever a customer pays with Razorpay Payment gateway, but I am able to click on the Razorpay payment gateway button and the amount is reflected in my Razorpay test account. But shipping data is not stored in my database, Please help me to solve this issue. Here is my views.py file... def place_order(request,total= 0,quantity = 0): cart = Cart.objects.get(cart_id = _cart_id(request)) cart_items = CartItem.objects.filter(cart = cart, status = True) # cart_items = CartItem.objects.filter(user= current_user) cart_count = cart_items.count() if cart_count <= 0: return redirect('login') tax= 0 grant_total = 0 for item in cart_items: total += (item.product.sale_price * item.quantity) quantity += item.quantity tax = (3*total)/100 grant_total = total+tax if request.method == "POST": order_number = request.POST.get('order_number') full_name = request.POST.get('full_name') mobile = request.POST.get('mobile') email = request.POST.get('email') address_line1 = request.POST.get('address_line1') address_line2 = request.POST.get('address_line2') country = request.POST.get('country') state = request.POST.get('state') city = request.POST.get('city') order_note = request.POST.get('order_note') tax = request.POST.get('tax') grant_total = int(request.POST.get('order_total'))*100 status = request.POST.get('status') amount = int(request.POST.get('amount')) * 100 # Create Rezorpay Client client = razorpay.Client(auth=('rzp_test_ertermiaBf1212','ertgghg56Qp27UYlPEsghtedfes')) # Create Order callback_url = 'http://'+ str(get_current_site(request))+"/payment/handlerequest/" response_payment = client.order.create(dict(amount=amount, currency="INR") ) order_id = response_payment['id'] order_status = response_payment['status'] if order_status == 'created': order = Order( order_number = order_number, full_name … -
Why does my Javascript code returns object object?
I am new to jquerry. I tried getting/summing some items from my django views in jquerry. this is whhat I have $(document).ready(function() { var sch = $('#sch-books'); var gov = $('#gov-books'); var total = sch.val() + gov.val(); $('#total').text("Total : " + total); }); My template has these <div id="sch-books" class="h6 mb-1">School copies - <b>{{ s_books.count }}</b></div> <div id="gov-books"class="h6 mb-1">Govt copies - <b>{{ g_books.count }}</b></div> <div id="total"></div> It displays Total : May someone help me get it right.. -
Database queries to 'new-database' are not allowed in this test
I have added a new database in my django project. Now I have run into issues with my test cases. I am keep getting this error message for every single of my test cases: Database queries to 'new-database' are not allowed in this test I have searched for this issue and the common solution comes down to adding databases = '__all__' or databases = {'default', 'new_database'} to the TestCase class But the problem is that now we have a lot of these test cases in my django application and a lot of corresponding TestCase based classes. So it does not fill right (specifically from the scale point of view) to add this databases = '__all__' declaration or whatever to every single class. Do we have any other and more proper solution for this issue? (After all why django needs to make transaction to new_database in all other test cases every single time that does not seem needed at all?) -
django foreign key mismatch - "question_question" referencing "question_subject"
Hi there is this problem I have can anyone solve this ? here is my django model class Question(models.Model): user = models.ForeignKey(User,on_delete=models.SET_NULL,null=True) title = models.CharField(max_length=255,null=True,blank=False) content = models.TextField(null=True,blank=False) subject = models.ForeignKey(Subject,on_delete=models.SET_NULL,null=True,related_name="subject_question") topicTag = models.ManyToManyField(TopicTag, related_name='questionTopic', blank=True) image = models.ImageField(blank=True, null=True) createdAt = models.DateTimeField(auto_now_add=True) votes = models.ManyToManyField(User, related_name='questionUser', blank=True, through='QuestionVote') answer_count = models.IntegerField(default=0,null=True,blank=True) difficulty = models.ForeignKey(Difficulty,on_delete=models.SET_NULL,null=True,related_name="difficulty") id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.title and here is the error code django.db.utils.OperationalError: foreign key mismatch - "question_question" referencing "question_subject" -
What do I need to do if I want to use database data conditionally in Django templates?
I am working on an ecommerce store in Django. I want to know that how do I use the database data passed to templates using render() method, conditionally through JavaScript or AJAX or JSON? For example, let's say I have a following models.py: from django.db import models class Suit(models.Model): title = models.CharField(max_length = 100, verbose_name = "Title") img = models.FileField(upload_to = 'suit-products/', null = True, verbose_name = "Picture") def __str__(self): return f"{self.title}" class Buttoning(models.Model): title = models.CharField(max_length = 100, verbose_name = "Title") img = models.FileField(upload_to = 'buttonings/', null = True, verbose_name = "Picture") def __str__(self): return f"{self.title}" and following views.py from django.shortcuts import render def index(request): suit_prods = Suit.objects.all() buttoning = Buttoning.objects.all() context { "suit_prods": suit_prods, "buttoning": buttoning } return render(request, "index/index.html", context) and following index.html (template): {% for element in suit_prods %} <li> <a href="#"> <div id="menu"> <img src="{{ element.img.url }}" /> <span>{{ element.title }}</span> <span></span> </div> </a> </li> {% endfor %} Now what I want is, if the clicked element in the list items in index.html has the title as "two_piece_suit" then show items of {{ buttoning }} as a list, otherwise pass. If I explain it more using some JS syntax, then I want following kind of … -
Chart.js 3.6.0 is not working on Weebpack 5.62.1?
I have a Django project. And after some security updates, I did some major dependencies upgrade. Everything was fix and working excepting the Chart.js that is not loaded in Webpack. After few days of working hard, I decided to bring the problem here. To clarify from start, these are one critical error and a minor error (can be ignored). charts are not loading - CRITICAL Uncaught ReferenceError: Chart is not defined My solution: To load Chart.js CDN before code <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.min.js"></script> Multiple charts using same canvas - MINOR (temporary ignored) Uncaught Error: Canvas is already in use. Chart with ID '0' must be destroyed before the canvas can be reused. My solution: to use only a js bundle file So let's go over my code! The next files are really big so I will try to bring the important sections. If you need extra info, let me know. These are my dependencies upgrades: # from pip (requirements.txt) Django==3.0.7 >> 3.0.14 django-webpack-loader==0.7.0 >> 1.4.1 # from npm (package.json) "bootstrap": "^4.5.3", >> "^5.1.3", "chart.js": "^2.9.4", >> "^3.6.0", "jquery": "^3.4.1", >> "^3.6.0", "popper.js": "^1.16.0", >> "^1.16.0", "webpack": "^4.44.2", >> "^5.62.1", "webpack-bundle-tracker": "^0.4.3", >> "^1.4.0", "webpack-cli": "^3.3.10" >> "^4.9.1" This is webpack config …