Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework viewset not returning correct data from queryset
I am pretty new to Django Rest Framework and am trying to build an API that has various viewsets, and almost all are working properly except one. In my viewset I have 3 ModelViewSet's: one to list all Inspections, one to show all completed (done) inspections and the last one to show all the undone inspections. The problem is that it is returning the list of all inspections correctly, but the other 2 return "detail: not found" even though I have instances of Inspections in my database. Here is my Inspection Viewset: from rest_framework.viewsets import ModelViewSet from inspections.models import Inspection from .serializers import InspectionSerializer from rest_framework import generics class InspectionViewSet(ModelViewSet): queryset = Inspection.objects.all() serializer_class = InspectionSerializer class DoneInspectionsViewSet(ModelViewSet): serializer_class = InspectionSerializer def get_queryset(self): queryset = Inspection.objects.all() return queryset class UndoneInspectionsViewSet(ModelViewSet): serializer_class = InspectionSerializer def get_queryset(self): queryset = Inspection.objects.filter(done=False) return queryset Here's my Inspection Serializer: from rest_framework.serializers import ModelSerializer from inspections.models import Inspection from properties.api.serializers import PropertySerializer class InspectionSerializer(ModelSerializer): property = PropertySerializer(many=False) class Meta: model = Inspection fields = ('id', 'connected_check', 'category', 'property', 'date', 'done_date', 'done_by', 'staff', 'notes', 'done') Here's the Inspection model: from django.db import models from check.models import Check from properties.models import Property from django.contrib.auth.models import User from django.urls … -
Python / Django - How to map a list of values in a dictionary to a HTML table?
My Django View: def hub(request): context = {} hub_id = [value['id'] for value in hub_data['data']] hub_name = [value['attributes']['name'] for value in hub_data['data']] hub_url = [value['links']['self']['href'] for value in hub_data['data']] nested_dict = dict(zip(hub_name, map(list, zip(hub_id, hub_url)))) context ['rows'] = nested_dict return render(request, 'connector/hub.html', context) The context['rows'] results in: {'rows': {hub_name1 : ['hub_id1', 'hub_url1'],{hub_name2 : ['hub_id2', 'hub_url2'], etc.. } I am trying to pass it a HTML table that looks like this: <th scope="col">Hub Name</th> <th scope="col">Hub ID</th> <th scope="col">Hub URL</th> My tablebody looks like this: <tbody> {% for key, value in rows.items %} <tr> <td> {{ key }}</td> <td> {{ value }}</td> **//how do i just get hub_id here** <td> Don't know what to do here to get: hub_url </td> </tr> {% endfor %} </tbody> But I want to add another -tag to fill with hub_url. How do I extract the hub_id data and add it to the column: Hub ID and extract the hub_url and add it to the column Hub URL. Any help would be much appreciated! -
Bad Request: server could not understand
I am facing error message "Bad Request, Your browser sent a request that this server could not understand". This messag I am getting when I perform following steps in my website Step1: Login into my website Step2: Click on a "Home page" and then 3MB of JSON data downloaded from server and client machine to display data on UI. Step3: While 3MB data not fully downloaded from server to client, then I click on logout, then I see error message as shown in Please let me know how this can be resolved -
'str' object has no attribute 'get'?
I try to update some data using Django form and ajax, the issue is the form does not accept 'POST['dat'], and I don't know why ?? any solution jquery : $.ajax({ headers: { "X-CSRFToken": csrftoken }, data: {'dat' : $('#form-one').serialize(),'id':id}, type: 'POST', url: '/commande/update2post/', success: function(response) { $.ajax({ headers: { "X-CSRFToken": csrftoken }, }); views.py : def update2post(request): if request.method == 'POST' and request.is_ajax: print(request.POST['id']) print(request.POST.get('id')) commande = get_object_or_404(Commande, id=request.POST['id']) das = request.POST['dat'] form = Commande_Form2(data=request.POST['dat'],instance=commande)// the issue ... if form.is_valid(): form.save() -
how to update m2m depend on a parent field django
i want to update m2m field depend on the its parent model for example : class ModelA(models.Model): status = models.BooleanField(default=True) status_of_product = models.ManyToManyField(Product,verbose_name='product') class Product(models.Model): active = models.BooleanField(default=False) products = models.CharField(max_length=30,unique=True) i want to update active field in Product only when if status field in ModelA equal to True def update_product_m2m(sender,instance,**kwargs): if instance.status == True: #this is wrong and doesnt work Product.objects.filter(pk__in=kwargs.get('pk_set')).update(active=True) m2m_changed.connect(update_product_m2m,sender=ModelA.status_of_product.through) is it possible please ? thanks for helping -
Send notification to users in database when some website is updated django
I am very new to django I would like to build an django project which can send to mail to several user when my college website is updated or given some notices in notification in college website... My intention is to write program which runs in baground and scraps the college website data and if it found any new things it need to send mail to 1000 or more people .. -
How to open virtualenv in python3?
I have both python 2.7 and 3.8 installed in my computer but whenever I would install virtualenv using pip install virtualenvwrapper-win and then open a new virtualenv using mkvirtualenv test it says Running virtualenv with interpreter /usr/bin/python2. Now I downloaded django in the virtualenv and got the outdated version 1.11. So now I am unable to import path from django.urls among other things. Is there any way to install vitrualenwrapper with python3 interpreter? Please help. I am trying to learn django and this is creating a huge hassle. -
Celery RabbitMQ - CloudAMQP does not revoke tasks - Django Heroku
When I use CloudAMQP it does not revoke tasks when I run the following code in my Django application: task_id = campaign.celery_task_id app.control.revoke(task_id) Instead app just stalls. However, I am able to create celery tasks from within my Django app when using CloudAMQP, just can't cancel them. Also for the above code revoking a task, it worked with Redis as broker url. I have also tried changing it to app.control.revoke(task_id, terminate=True) but still stalling. I am trying to revoke tasks that were set for a scheduled time in future using the following code email_campaign.apply_async((audience_id, campaign_id), eta=scheduled_time_utc) -
Python Cannot Import Name Django
I get the following error File "/mnt/d/Protostar/server/src/api/ideas/serializers.py", line 2, in <module> from .models import Idea ImportError: cannot import name 'Idea' models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Idea(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) title = models.CharField(max_length=50) serializers.py: from rest_framework import serializers from .models import Idea class IdeaSerializer(serializers.ModelSerializer): class Meta: model = Idea fields = '__all__' I have no idea why this isn't working, I've imported the same way in many projects before. -
what hapenned to the data going from admin site in website. it is showing title object 1 instead of the data in it
This is the website [ this is how i am connecting to database ... -
How to add different values of the same field
Raw has the process field (1/0) when adding the process=1, it does well but when adding the process=0; it brings me the same value of process=1. Out category | totalProcess | totalNoProcess A | 100 | 100 Desired result category | totalProcess | totalNoProcess A | 100 | 0 query in mysql: SELECT download, SUM(CASE WHEN process = 1 THEN 1 ELSE 0 END) AS Processed, SUM(CASE WHEN process = 0 THEN 1 ELSE 0 END) AS NoPreoces FROM oer_raw where download=1; use annote, count, case is: metaData = Raw.objects.values('download__category_name').annotate( totalProcess = Count(Case(When(process=1, then=Value(1)), default=Value(0), output_field=IntegerField())), totalNoProcess = Count(Case(When(process=0, then=Value(1)), default=Value(0), output_field=IntegerField())) ).get(download = disciplina.id) the relationship between Download and Raw is 1 - * so that the FK is in Raw with the name of download, that's why I use get to obtain the sum of what the FK I am looking for has -
Django Rest Framework: get not get my forms in url after looping through it in my Model and Serializers
I want to show All Subcategory base on the Category Selected in Database. I try to select category with id = 1. I ma getting this. Though on print subcategory in view. I got the list but not showing on my form. I got only quality. Please, kindly assist in solving this. view.py class PalceOrder(APIView): serializer_class = PlaceOrderSerializer def get(self, request, category_pk, format=None): category = get_object_or_404(Category, pk=category_pk) subcategory = category.subcategory.all() print(subcategory) data = {'subcategory': subcategory, 'category_pk': category_pk,} serializer = PlaceOrderSerializer(data, many=True) return Response(serializer.data) def post(self, request, category_pk): category_pk = request.data.get("category") data = {'category_pk': category_pk} serializer = PlaceOrderSerializer(data=data) if serializer.is_valid(): category = serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class CategoryDetailsSerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('name',) class SubCategorySerializer(serializers.ModelSerializer): class Meta: model = SubCategory fields = ('name',) class PlaceOrderSerializer(serializers.ModelSerializer): subcategory = SubCategorySerializer(many=True, read_only=True, source='subcategory.name') class Meta: model = ProcessOrder fields = ('subcategory', 'quantity') models.py class Category(models.Model): name = models.CharField("Carteen Name", max_length=50) address = models.TextField("Carteen Address") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.name}' class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' class SubCategory(models.Model): category = models.ForeignKey(Category, related_name='subcategory', on_delete=models.CASCADE) name = models.CharField("Food Name", max_length=50, help_text="Name of The Food") price = models.DecimalField("Food Price", max_digits=5, decimal_places=2) quantity = … -
how to access html name in modelforms instead of model name in django
forms.py class ProductForm(forms.ModelForm): class Meta: model = Products fields = ['product_name', 'product_image', 'product_brand', 'product_description', 'product_category', 'product_orginal_price', 'product_retail_price', 'product_added_date', 'product_stock', 'product_status', 'product_added_use', 'product_deleted_user'] page.html {% csrf_token %} <div class="form-group"> <label for="productName">Product Name</label> <input name='product_name' class="form-control" type="text" id="productName" required="" placeholder="Michael Zenaty"> </div> <div class="form-group"> <label for="productimage">Product Image</label> <input name="product_image" class="form-control" type="file" id="productimage" placeholder=""> </div> <div class="form-group"> <label for="productbrand">Product Brand</label> <input name="product_brand" class="form-control" type="text" id="productbrand" placeholder=""> </div> <div class="form-group"> <label for="productcategory">Product Category</label> <input name="product_category" class="form-control" type="text" id="productcategory" placeholder=""> </div> <div class="form-group"> <label for="productdescription">Product Description</label> <input name="product_description" class="form-control" type="text" id="productdescription" placeholder=""> </div> <div class="form-group"> <label for="productorginalprice">Product Orginal Price</label> <input name="product_orginal_price" class="form-control" type="text" id="productorginalprice" placeholder=""> </div> <div class="form-group"> <label for="productretailprice">Product Retail Price</label> <input name="product_retail_price" class="form-control" type="text" id="productretailprice" placeholder=""> </div> <div class="form-group"> <label for="productStock">Product Stock</label> <input name="product_stock" class="form-control" type="text" id="productStock" placeholder=""> </div> <div class="form-group"> <label for="product_status">Product Status</label> <input name="product_status" class="form-control" type="text" id="product_status" placeholder=""> </div> </div> how to assign custom name to modelform in django like.. instead of name='product_stock' access tag with ProductStock in model form and how to assign in view.py -
How to upload multiple images with django rest framework CreateAPI in view and create method in serializers
I have a post serializer and a postimage serializer to upload multiple images to a post. I have this serializer, but I am not sure how to make it in a way, so that I can upload multiple images, for example 5 images with a single post, like how we use with formsets coz now I can upload only 1 image in 'images' field. These are my serializers. Please do have a look and let me know what changes I have to make. Thanks class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = ['id', 'images',] class PostSerializer(TaggitSerializer, serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.username') post_date = serializers.ReadOnlyField() postimage_set = PostImageSerializer(many=True) likes = UserSerializer(many=True) class Meta: model = Post fields = ['id','title', 'post_date', 'updated', 'user', 'image', 'postimage_set'] def create(self,validated_data): user = self.context['request'].user title = validated_data['title'] image = self.context['request'].FILES.get('image') images = self.context['request'].FILES.get('images') m1 = Post(user=user,title=title,image=image,) m1.save() m2 = PostImage(post=m1, images= images) m2.save() validated_data['images']=m2.images validated_data['image']=m1.image return validated_data views class CreatePostAPIView(generics.CreateAPIView): serializer_class = PostCreateSerializer permission_classes = [IsAuthenticated] def create(self, request, *args, **kwargs): serializer = PostCreateSerializer(data=request.data, context={'request':request,}) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How to have separate pages for username and password with django user login?
I have an extended django user model, and I want the user to first enter their username then be redirected to another page that asks for their password. Somewhat similar to how amazon handles user login. Do I just use 2 separate views and pass the username as an input to the password view? Second question, can this cause a security problem? def usernameView(request): # get username and redirect to password def passwordView(request, username): # get password if correct login -
Field 'id' expected a number but got '_javiertris'
I created a new .html file for a certain option in my header. Unfotunately, whenever I click it I get this error I don't know what's wrong with my code. Here is my models.py class BillingMethod(models.Model): BILL = ( ('NN', '---'), ('PP', 'PayPal'), ('GCC', 'GCash')) billing_method2 = models.CharField(max_length=100, blank=True, null=True, default='NN', choices=BILL) account_information2 = models.CharField(max_length=100, blank=True, null=True, default='---', help_text='Input email (if PayPal) or contact number (if GCash).') Here's my views.py class BillingMethodView(UpdateView): model = BillingMethod fields = ['billing_method2','account_information2'] template_name = 'users/billing_method.html' def form_valid(self, form): """ Checks valid form and add/save many to many tags field in user object. """ user = form.save(commit=False) user.save() form.save_m2m() return redirect('users:billing_user', self.object.username) Here's my urls.py path('<str:pk>/billing_method', BillingMethodView.as_view(), name='billing_user'), Here's my button to launch the .html file <a class="dropdown-item" href="{% url 'users:billing_user' user.username %}">Billing method</a> Whenever I change my views.py to TemplateView, the template works. But, I need it to be on UpdateView because I need the information. What should I do? Thank you. -
Display dropdown menu materialize
Hi I don't know anything about javascript. I'm currently using materialize with django and i have the problem, that my django select-form is not displayed. I looked up the solution online. There it states,i have to initialize the select form with: document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('.dropdown-trigger'); var instances = M.Dropdown.init(elems, options); }); // Or with jQuery $('.dropdown-trigger').dropdown(); Now the question: Where do i have to put this stuff? Currently it's still not being dsiplayed. My setup is the fowllowing: results.html: {% extends 'maschinen/base.html' %} {% load static %} <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script> <link rel="stylesheet" href="{% static "app/css/style.css" %}"> <link rel="stylesheet" href="{% static "app/js/index.js" %}"> {% block title %} app {% endblock title%} {% block body_data %} <form action="" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Filtern"/> </form {% endblock body_data%} and static/app/js/index.js: <script> window.onload = document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('select'); var instanes = M.FormSelect.init(elems, options); }); </script> Would be really nice if somebody could enlighten me. -
How to create a limit list of users on Django social login
As the title suggests, how can I create a limit list of users in django social login, so that only authorized users are able to login with their social account? For example, a user with certain gmail account can login, but others cannot login using unauthorized gmail accounts. Right now, if I use allauth, all users who have gmail account can login to my django site, but that's not what I expect. Thanks! -
Django - Stripe. You did not set a valid publishable key. Error that comes up when trying to incorprate stripe payments on a django website
I'm working on a django bookstore website and there seems to be an error with stripe integration. I have an orders page that asks for payment information (I'm using the test API for now). I get the same error "You did not set a valid publishable key. Call Stripe.setPublishableKey() with your publishable key." orders/views.py from django.conf import settings from django.views.generic.base import TemplateView class OrdersPageView(TemplateView): template_name = 'orders/purchase.html' def get_context_data(self, **kwargs): ##Stripe.setPublishableKey('PUBLISHABLE_KEY') context = super().get_context_data(**kwargs) context['stripe_key'] = settings.STRIPE_TEST_PUBLISHABLE_KEY return context templates/orders/purchase.html {% extends '_base.html' %} {% block title %}Orders{% endblock title %} {% block content %} <h1>Orders page</h1> <p>Buy for $39.00</p> <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="{{ stripe_key }}" data-description="All Books" data-amount="3900" data-locale="auto"> </script> {% endblock content %} -
Pass array with formdata in ajax
I want ajax to post form data as well as an array but when I pass array it displays none or empty. jQuery("#myform").submit(function (e) { e.preventDefault(); var formData = new FormData(this); jQuery.ajax({ type:'POST', url:'{% url 'urlAjax' %}', data: formData, cache:false, contentType: false, processData: false, success: function (data) { alert("Success"); } }); }); I am able to fetch formdata in django views but I also want to fetch an array. I tried using: jQuery("#myform").submit(function (e) { e.preventDefault(); arr = ['My', 'Array']; var formData = new FormData(this); formData.append('arr[]': arr); jQuery.ajax({ type:'POST', url:'{% url 'urlAjax' %}', data: formData, cache:false, contentType: false, processData: false, success: function (data) { alert("Success"); } }); }); Django views.py: temp = request.POST.getlist('arr[]') But it returns none. -
Django: Adding products to cart not working properly
I am trying to fix an error related to the quantity in the project not reflecting correctly in the Order Summary. So I tried to changing my views from Adding or Removing items and combining them to one function called update quantity and taking order item as a primary key: Now that I am updating i keep getting This page isn’t working If the problem continues, contact the site owner. HTTP ERROR 405 and when I try to changing the template I receive another error Reverse for 'update-qty' with keyword arguments '{'slug': 't-shirt-no1fdgfg'}' not found. 1 pattern(s) tried: ['update\\-qty$'] I need help to fix this issue: Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) keywords = models.CharField(max_length=100) def get_update_qty_url(self): return reverse("core:update-qty", kwargs={ 'slug': self.slug }) class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) category = models.CharField( max_length=120, choices=VAR_CATEGORIES, default='size') objects = VariationManager() class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) variation = models.ManyToManyField(Variation) class Order(models.Model): items = models.ManyToManyField(OrderItem) Here are the views.py @login_required def update_qty(request): if request.method == 'POST': item_slug = request.POST.get('item_slug', None) # Check for an order_item order_item_pk = request.POST.get('order_item', None) order_item = OrderItem.objects.filter(pk=order_item_pk).first() if not order_item: messages.info(request, "Product was not in your cart") return redirect("product", slug=item_slug) # Check … -
Unable to install django Mac terminal
I'm new to programming. Stating with python and django framework. When i try to install django via terminal following happens. Also, pls explain what is sudo and --user. Last login: Sun Aug 2 20:43:02 on ttys000 The default interactive shell is now zsh. To update your account to use zsh, please run `chsh -s /bin/zsh`. For more details, please visit https://support.apple.com/kb/HT208050. Aruns-MacBook-Pro:~ arununnikrishnan$ mkdir vidly mkdir: vidly: File exists Aruns-MacBook-Pro:~ arununnikrishnan$ cd vidly Aruns-MacBook-Pro:vidly arununnikrishnan$ pipenv install django==3.0.8 -bash: pipenv: command not found Aruns-MacBook-Pro:vidly arununnikrishnan$ sudo pipenv install django==3.0.8 Password: sudo: pipenv: command not found Aruns-MacBook-Pro:vidly arununnikrishnan$ --user pipenv install django==3.0.8 -bash: --user: command not found Aruns-MacBook-Pro:vidly arununnikrishnan$ sudo pip install pipenv sudo: pip: command not found Aruns-MacBook-Pro:vidly arununnikrishnan$ sudo easy_install pip Searching for pip Reading https://pypi.org/simple/pip/ Downloading https://files.pythonhosted.org/packages/36/74/38c2410d688ac7b48afa07d413674afc1f903c1c1f854de51dc8eb2367a5/pip-20.2-py2.py3-none-any.whl#sha256=d75f1fc98262dabf74656245c509213a5d0f52137e40e8f8ed5cc256ddd02923 Best match: pip 20.2 Processing pip-20.2-py2.py3-none-any.whl Installing pip-20.2-py2.py3-none-any.whl to /Library/Python/2.7/site-packages Adding pip 20.2 to easy-install.pth file Installing pip script to /usr/local/bin Installing pip3.8 script to /usr/local/bin Installing pip3 script to /usr/local/bin Installed /Library/Python/2.7/site-packages/pip-20.2-py2.7.egg Processing dependencies for pip Finished processing dependencies for pip Aruns-MacBook-Pro:vidly arununnikrishnan$ sudo pipenv install django==3.0.8 sudo: pipenv: command not found Aruns-MacBook-Pro:vidly arununnikrishnan$ pip -V pip 20.2 from /Library/Python/2.7/site-packages/pip-20.2-py2.7.egg/pip (python 2.7) Aruns-MacBook-Pro:vidly arununnikrishnan$ pipenv install django==3.0.8 -bash: pipenv: command … -
How do you run Javascript in Django?
This is my first time doing anything like this and google has not helped me much. I can get Javascript to work as part of the html but not as its own file. I've set up my static files and they work for my CSS but I cannot run any Javascript from the static folder. The path is below: This is in my "base.html" <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="/static/css/base.css"> <!-- Works --> <!-- Custom CSS --> <link rel="stylesheet" href="/static/css/darkmode.css"> <!-- Works --> <!-- Utilities CSS--> <link rel="stylesheet" href="/static/css/star_rate.css"> <!-- Works --> </head> <!-- Scrips --> <script src="/static/js/all_pages.js" type="text/javascript"></script> <!-- Doesn't Work--> <script src="/static/js/jquery-3.5.1.min.js" type="text/javascript"></script> <!-- Doesn't Work--> This is "all_pages.js" alert("Test 2"); and this is an extension of base called "test.html" {% extends 'base.html' %} {% block content %} {% load static %} <script src="/static/js/all_pages.js" type="text/javascript"></script> <!-- I added this in hopes it'd fix the issue --> <!-- VVV I added this to see if js was not working at all --> <script type="text/javascript"> alert('Test 01'); </script> <!-- ^^^ I added this to see if js was not working at all --> {% endblock %} … -
Django. How to make loop for bootstrap collapse
Can you help with better way to process many similar bootstrap collapse for page ? I have 12 similar collapse, where collapse title it is a verbose name of model field, and collapse text it is a model field value. <div class="col-md-12 col-lg-10 mx-auto mb-3"> <div class="accordion md-accordion" id="accordionEx" role="tablist" aria-multiselectable="true"> <div class="card border-top border-bottom-0 border-left border-right border-light"> <div class="card-header border-bottom border-light" role="tab" id="heading" style="background-color:#DDDFDF;"> <a data-toggle="collapse" data-parent="#accordionEx" href="#collapse" aria-expanded="true" aria-controls="collapse"> <h5 class="black-text font-weight-normal mb-0"> Title of collapse where i want get verbose_name of model </h5> </a> </div> <div id="collapse" class="collapse" role="tabpanel" aria-labelledby="heading" data-parent="#accordionEx"> <div class="card-body"> Some text where i want get value of model field </div> </div> </div> </div> </div> How can i make loop for this model and substitute name and value from model field instead creat 12 similar block of code ? -
How Can I Active Virtual Environment Using .bat File?
I have finished working on Django project, but I don't want to Deploy it to the server right now I want to use this system on my local host. I tried to create a file with bat extension, and this one is to open the project on the Chrome browser This file will work when opened The question is how with this file can I run the project virtual environment The code that works is 'manager.bat': start cmd /k start chrome http://127.0.0.1:8000/admin/ cd manager/venv/Manager python manage.py runserver But when adding this statement: activate Then, when executing the file again, it exits the cmd without executing anything Code not working: start cmd /k start chrome http://127.0.0.1:8000/admin/ cd manager/venv cd Scripts activate cd .. cd Manager python manage.py runserver 'activate' instruction is to activate the virtual environment , when I type it on cmd it works successfully ,, look : [enter image description here][1] The idea is that I don't want every time to open the cmd, run the virtual environment, and run the server manually [This is on cmd and it works][1] [1]: https://i.stack.imgur.com/k5XIe.png