Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invalid password or unknown hashing algorithm in Django-rest-framework
I created a custom user model making use of just the email and password field. I created the API serializer for the custom user model using the djangorestframework. It seems to send all the data (email and password) but doesn't hash the password. I tried out different solutions here but none seems to work. models.py from django.db import models from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser) class UserManager(BaseUserManager): def create_user(self, email, password=None): # Creates and saves a User with the given email and password if not email: raise ValueError('User must have an email address') user = self.model(email=self.normalize_email(email),) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): # Creates and saves a staff User with the given email and password user = self.create_user(email, password=password) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, password): # Creates and saves a superuser with the given email and password user = self.create_user(email, password=password) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] # Email and password are required by default def get_full_name(self): # The user is identified by their email address return self.email … -
(django) can't make changes to database other than creating new objects
I created a todo app following Dennis Ivy's tutorial his code works fine but mine does not.. whenever i update task it creates new object. Not even able to delete object by delete button that i added .. I think its not able to make changes to database other than creating new objects..help please def index(request): task = Task.objects.all().order_by('- created_on') form= TaskForm() if request.method=='POST': form= TaskForm(request.POST) if form.is_valid(): form.save() return redirect ('/') return render(request('task/list.html',{'task':task,'form':form}) def update_task(request,pk): task =Task.objects.get(id=pk) form= TaskForm(instance= task) if request.method=='POST': form= TaskForm(request.POST,instance=task) if form.is_valid(): form.save() return redirect('/') return render(request,'task/update_task.html', {'form': form}) -
rendering a template using ajax in django-oscar
I am trying to customize how the default implementation of Oscar's add review functionality works on a product's detail page, so that instead of django reloading the detail template with the form(default implementation),i use ajax to render the template(with the add review form). Any better way of implementing this to achieve that effect will be appreciated. The default implementation is triggered using a link on the detail page/template like so: {% block content %} ...... <a href="{% url 'catalogue:reviews-add' product_slug=product.slug product_pk=product.id %}#addreview"> </a> ...... {% iffeature 'reviews' %} {% block product_review %} {% endblock product_review %} {% endiffeature %} {% endblock content %} In my implementation I just changed the anchor tag implementation in the detail page/template like so: {% block content %} ...... <a class='xx' product_slug="{{product.slug}}" product_pk="{{ product.id }}" href="#addreview"> </a> ...... {% iffeature 'reviews' %} {% block product_review %} {% endblock product_review %} {% endiffeature %} {% endblock content %} In the default implementation, the product_review form template extends the detail template like so: {% extends "oscar/catalogue/detail.html" %} <div id="addreview" class="review_add" > <form id="add_review_form" method="post" action="#addreview"> ................... </form> </div> The default URLs config for reviews(which lives in the catalogue app as a package) is appended to the catalogue's … -
Access foreign key value in Django Rest Framework permissions
I am coding a restaurant reviews app. User can write a review and add pictures to it. I am setting up permissions to StarterPicsViewset so only the author of the review can Update it. So I set up a custom permission but as I run it, I have a 'StarterPic' object has no attribute 'restaurant_review_review_author_id' error. What I need is to get the review_author related to the restaurant_review_id so I can compare it to the request.user Here is my models: class Restaurant(models.Model): adress = models.CharField(max_length=240) name = models.CharField(max_length=140) class RestaurantReview(models.Model): review_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) class StarterPic(models.Model): restaurant_review = models.OneToOneField(RestaurantReview, on_delete=models.CASCADE) name_1 = models.CharField(max_length=40) picture_1 = models.ImageField() My view: class StarterPicsViewset(viewsets.ModelViewSet): queryset = models.InsidePic.objects.all() serializer_class = serializers.InsidePicsSerializer permission_classes = [IsAuthenticatedOrReadOnly, IsOwnReviewOrReadOnly] and my permissions: class IsOwnReviewOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.restaurant_review_review_author_id == request.user -
Django-Rest-Framework: Serializing Many to Many Model with a through in Post Request
I am having really big trouble while trying to implement handling of POST request within DRF and Serializers. The error I have is following; AttributeError: Got AttributeError when attempting to get a value for field equipment_types on serializer FreightCreateSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Freight instance. Original exception text was: 'Freight' object has no attribute 'FreightEquipmentType_set'. My Models are; class EquipmentType(model.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=250) class Freight(model.Model): name = models.CharField(max_length=250) equipment_types = models.ManyToManyField(EquipmentType, through='FreightEquipmentType') class FreightEquipmentType(model.Model): equipment_type = models.ForeignKey( EquipmentType, on_delete=models.CASCADE ) freight = models.ForeignKey( Freight, on_delete=models.CASCADE ) quantity = models.DecimalField(max_digits=18, decimal_places=2, default= 0) My Serializers are, class EquipmentTypeSerializer(serializers.ModelSerializer): class Meta: model = EquipmentType fields = "__all__" class FreightEquipmentTypeSerializer(serializers.ModelSerializer): class Meta: model = FreightEquipmentType fields = ('equipment_type', 'quantity', ) class FreightCreateSerializer(EnumChoiceModelSerializerMixin, serializers.ModelSerializer): equipment_types = FreightEquipmentTypeSerializer(many=True, source='FreightEquipmentType_set', read_only=False) class Meta: model = Freight fields = "__all__" def create(self, validated_data): equipment_types_validated_data = validated_data.pop('FreightEquipmentType_set') freight = Freight.objects.create(**validated_data) equipment_type_serializer = self.fields['equipment_types'] for each in equipment_types_validated_data: each['freight'] = freight equipment_types = equipment_type_serializer.create(equipment_types_validated_data) return freight I would like to handle following post request. { "name": "0", "equipment_types": [{ "equipment_type": "8a9c1f57-c6c9-4bfa-84a8-2082d6c3d112", "quantity": 2 }, { "equipment_type": "7242a8fb-3eba-4988-98fa-806c21562101", "quantity": 3 }] } Any help is … -
apache2 ubuntu django : ModuleNotFoundError: No module named 'encodings'
i tried to upload my django 2.2 project but u get this error while i type : cat /var/log/apache2/error.log the error is: (13)Permission denied: mod_wsgi (pid=7692): Unable to stat Python home /root/project_name/venv/. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' and this is my /etc/apache2/sites-available/django_proj.conf <VirtualHost *:80> Alias /static /root/project_name/static <Directory /root/project_name/static> Require all granted </Directory> Alias /meida /root/project_name/meida <Directory /root/project_name/meida> Require all granted </Directory> <Directory /root/project_name/zettapc> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /root/project_name/project_name/wsgi.py WSGIDaemonProcess django_app python-path=/root/project_name python-home=/root/project_name/venv/ WSGIProcessGroup django_app </VirtualHost> is there something i've missed , or doing something wrong please? ubuntu 18lts , mysql, django =2.2 -
Django: Pass UserID to settings.py
I need to pass the UserID to settings.py because of this line: FROALA_UPLOAD_PATH = os.path.join(BASE_DIR, 'media/froala_editor/', instance.user.id) -
Django CBV detailview get_context_data not passing id to the query
class Project(models.Model): name = models.CharField(max_length=256, unique = True ) location = models.CharField(max_length=256,blank=True, default='') type = models.CharField(max_length=100,blank=True, default='') floors = models.CharField(max_length=100,blank=True, default='') creationdate = models.DateTimeField(auto_now_add=True) class Flat(models.Model): FACING_CHOICES = [ ('east', 'East'), ('west', 'West'), ('north', 'North'), ('south', 'South'), ] STATUS_CHOICES = [ ('sold', 'Sold'), ('available', 'Available'), ('mortgage', 'Mortgage'), ] project = models.ForeignKey('Project', on_delete=models.CASCADE) flatno = models.PositiveSmallIntegerField(null=True) flatarea = models.PositiveSmallIntegerField(null=True) facing = models.CharField(max_length=5, choices=FACING_CHOICES, default='east') status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='available') Views.py class ProjectDetailView(DetailView): model = Project template_name = 'projects/project_detail.html' def get_context_data(self, **kwargs): context = super(ProjectDetailView, self).get_context_data(**kwargs) context['totalavailable_flats'] = Flat.objects.filter (project_id = self.kwargs.get('id')) .count() return context template projects/project_detail.html {% extends '_base.html' %} {% block content %} {% load static %} <p>{{ project.finishdate }}</p> <p>Available flats : {{ total_flats }}</p> {% endblock content %} How to pass the Project_id to the query to get flat details Query - Project id not passing to the query SELECT COUNT(*) AS "__count"enter code here FROM "projects_flat" WHERE "projects_flat"."project_id" IS NULL My view not passing project id to the query. -
How to group and filter objects by list objects
I have to get average grade value by each type of question(many grades at 1 question, 1 question at 1 grade). Below my code to get just all grades which user got but i don't know how to "group by" grades by question and why my filter doesn't work(returning 400 bad request) @action(detail=False, methods=['post']) def results(self, request): user_id = request.data["user_id"] survey_id = request.data["survey_id"] self_rating_objects = Grade.objects.filter(interview__in=Interview.objects.filter( survey_id=survey_id, target_user_id=user_id)) serializer = GradeSerializer(data=self_rating_objects,many=True) if serializer.is_valid(): return Response(serializer.data,status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) Here my grade model class Grade(models.Model): created_at = models.DateField(auto_now_add=True) value = models.IntegerField() question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="questions") interview = models.ForeignKey(Interview, on_delete=models.CASCADE, related_name="grades") And interview model class Interview(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="users") target_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="target_users") comment = models.TextField(default='') created_at = models.DateField(auto_now_add=True) survey = models.ForeignKey(Survey, on_delete=models.CASCADE, related_name="interviews") -
How to store the Json in a Django Db as text
I am sending a POST request from my front-end from which I want to save the JSON into my database as a text field I am using django rest framework and sqlite db. My serializer class is class DataSerializer(serializers.Serializer): json_data = serializers.JSONField() def create(self,validated_data): return TableUser.objects.create(json_data=validated_data) and my model is class TableUser(models.Model): username = models.TextField(default="unlogged") json_data = models.TextField() When i send the POST request it stores 1|unlogged|{'json_data': {'json_data': ['Value must be valid JSON.']}} in my db instead of the actual JSON I am sending. So, How do I just simply store the whole JSON in my textfield in whatever format it comes. -
password reset in django
I am trying to send passwword-reset email in django.But for sending that I need to create the google app password.I have generated the app password in google accounts.But I am cannot find where to paste the app password in gmail.Can you guys please help me find out this. -
Why use Django 3?
So we had celery and redis for background tasks / async for django but how does the same thing gets tackled in django 3.0? do we have new inbuilt features for the same in dj 3.0? Thanks in advance. -
HTML Page rel="icon" is not showing up in Django
This is how I've referenced it. {% load static %} <link href="{% static 'Assets/img/globe.png' %}" rel="icon" /> -
Create PDF of Images in Django
In my Django Application I am creating Barcodes of an Object and up until then it works fine, the PNGs are created perfectly but How can I arrange them in a PDF in a 7x2 Grid such that they can be printed? Is there any Library which takes the images as input and create a pdf with these images? Here's the code: class GrnBarcodes(APIView): permission_classes = (permissions.IsAuthenticated,) def get(self, request, *args, **kwargs): pk = self.kwargs['pk'] grn = Grn.objects.filter(pk=pk)[0] grn_prod = grn.items.all() items = [] for i in grn_prod: for j in range(i.item_quantity): items.append("YNT9299"+str(pk)+str(i.item.short_code)+str(j+1)) zpl_img = [] for i in items: barcode = get_barcode(value=i, width=650) a = barcode.save(formats=['PNG'], fnRoot=str(i)) with open(a, 'rb') as image: img = image.read() grf = GRF.from_image(img, 'YNT') grf.optimise_barcodes() # os.remove(a) zpl_img.append(grf.to_zpl()) return Response(zpl_img) The grid that I have to place these images looks like this: -
get () get() returned more than one SubRegion, DJango cities_light
I am using Django Cities_light My files that I want to include CITIES_LIGHT_TRANSLATION_LANGUAGES = ['fr','en'] CITIES_LIGHT_INCLUDE_COUNTRIES = ['CA','US'] CITIES_LIGHT_INCLUDE_CITY_TYPES = ['PPL', 'PPLA', 'PPLA2', 'PPLA3', 'PPLA4', 'PPLC', 'PPLF', 'PPLG', 'PPLL', 'PPLR', 'PPLS', 'STLMT',] When I run the command python manage.py cities_light I just got the error of cities_light.models.MultipleObjectsReturned: get() returned more than one SubRegion -- it returned 35! Any solutions? I want the all cities of Canada and USA -
why i cant take correct id of button jqery in django loop in template
The problem is this. In my loop in the template, I display the + and - buttons for the amount of each product in the cart, while receiving the data and sending it to the server, where I actually process it, and increasing that amount of the product in the cart. template <td class="info col-md-3"> <div class="input-group"> <span class="input-group-btn"> <button id="minus" class="btn btn-danger minus" data-id="{{obj.id}}" type="button">-</button> </span> <input id="calc-button" type="text" class="form-control calc-button" data-id="{{obj.id}}" value="{{obj.quantity}}"> <span class="input-group-btn"> <button id="plus" class="btn btn-success plus" data-id="{{obj.id}}" type="button">+</button> </span> </div> </td> and my view class MainCartPlusValue(View): def post(self, request): print(request.POST) a = dict() a = { 'id': request.POST['id'], 'counts': request.POST['counts'] } obj = Dishes.objects.get(id=request.POST['id']) product = get_object_or_404(Dishes, id=obj.id) """не работает :(""" # if request.POST['counts'] == 3: # cartremove = MainCartRemove # cartremove.get(self=cartremove.self, request=request, key='remove', pk=obj.id) """посюда(""" cart = Cart(request) cart.add(item=product, quantity=request.POST['counts'], update_quantity=True) return JsonResponse(a) if need it my cart def add(self, item, quantity=1, update_quantity=False): product_id = item.id if product_id not in self.cart: self.cart[product_id] = {'quantity': item.counts, 'price': str(item.price), 'name': str(item.name), 'id': item.id } if update_quantity: self.cart[product_id]['quantity'] = quantity print(self.cart[product_id]['quantity']) self.session['cart'] = self.cart self.session.modified = True $(function () { $('.minus').click(function(){ $(".calc-button").val(parseInt($(".calc-button").val())-1), alert( $(".calc-button").val()); const csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); $.ajaxSetup({ beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }); … -
Unique and custom order_id generated by Django Autofield
I am building an e-commerce solution that stores unique and custom order_id's for every single order. The uniqueness is due to the separation of orders for 1 particular customer. The custom part is for the separation of different suppliers. For example: Supplier name = foo order1: order_id = foo-20202907-001 order2: order_id = foo-20202907-002 ... Supplier name = bar order1: order_id = bar-20202907-001 order2: order_id = bar-20202907-002 ... The first part of the order_is is depending on the name of the supplier. Next it will take in a date stamp and lastly it takes auto incremented field for the order amount that day. My current Order model: class Order(models.Model): order_id = models.AutoField(primary_key=True, editable=False) customer_id = models.ForeignKey(User, on_delete=models.CASCADE) The Autofield starts at 1 and increments it every time a new is placed by 1. When a lot of customers are placing different orders at different suppliers the order_id's get really messy. For the sake of the unique id in my payment system i need something like the above order_id's. I've read some articles about on custom unique field but I don't know whats the right approach. Is there a way to do this? -
Python - retrieving slug value from foreingkey class
I'm a newbie in Python and I need some help with my code. Not even sure if my title makes sense. Basically I have my blog and I'm trying to add a sidebar with popular posts. I have created a PostStatistics class to collect the number of visits in each post which can be seen from Django admin. The PostStatistics class has a ForeignKey to the Post class. OK so my problem is in the PostDetail view. I have a QuerySet there called Popular where I retrieve the 5 most popular posts in the last 7 days. There I retrieve the Post_id and Post__Title. I also need to retrive the Post SLUG but I have no idea how I can do that. The slug would be used in the following bit of code: <a href="{% url 'post_detail' pop_article.post_slug %}">{{ pop_article.post__title }}</a> The following is what in my models: class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) views = models.PositiveIntegerField(default=0, editable=False) class Meta: ordering = ['-created_on'] db_table = "post" def __str__(self): return self.title def get_absolute_url(self): from django.urls import reverse return … -
Incorrect application version found on all instances. Expected version "app_version" (deployment 158)
I'm trying to deploy my Django application to Beanstalk but my app health is Degraded for some reason. The log file is also deleted automatically so I cannot read the error. But when I click on "Cause", I get this message: Command failed on all instances. Incorrect application version found on all instances. Expected version "app-fc04-XXXX" (deployment XXX). Application deployment failed at 2020-07-29T07:24:43Z with exit status 1 and error: Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. It's also worth noting that the failure is happening when trying to install from requirements.txt, here's the error: Application deployment failed at 2020-07-29T07:24:43Z with exit status 1 and error: Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. Collecting alphabet-detector==0.0.7 (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Using cached https://files.pythonhosted.org/packages/f8/89/c9ab40530fb9142890a79bf39b6f2ee47c311729358794719acd15974e68/alphabet-detector-0.0.7.tar.gz Collecting argcomplete==1.10.0 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) Using cached https://files.pythonhosted.org/packages/4d/82/f44c9661e479207348a979b1f6f063625d11dc4ca6256af053719bbb0124/argcomplete-1.10.0-py2.py3-none-any.whl I've tried rebooting the instance, deploying an old working version, and deleting the EC2 instance but none of them work. -
Django activate translations project wide instead of per view?
I have a Django project where I activate the translations based on the Accept-Language header on each and every view as follows, from django.utils import translation translation.activate(request.headers.get('Accept-Language', 'en')) So if I have a ViewSet using Django Rest Framework, I had to do the above for each and every methods as following, class MyViewSet(viewsets.ModelViewSet): def list(self, request, *args, **kwargs): translation.activate(request.headers.get('Accept-Language', 'en')) # .... def retrieve(self, request, *args, **kwargs): translation.activate(request.headers.get('Accept-Language', 'en')) # .... def update(self, request, *args, **kwargs): translation.activate(request.headers.get('Accept-Language', 'en')) # .... def destroy(self, request, *args, **kwargs): translation.activate(request.headers.get('Accept-Language', 'en')) # .... This is just for a viewset, I currently have 10+ viewsets and Translations are needed for every viewset. This make the process even harder to maintain and results in much code duplication. How can I clean up this code to something like activating translations project wide, any options available to do? thank you for any input. -
Many To Many NOT saving in django
my views.py file: form = ClassesForm(request.POST) if form.is_valid(): New_Class = Classes() New_Class.semester = Last_Semester New_Class.year = form.cleaned_data.get('year') if form.cleaned_data.get('year') >= 6 and form.cleaned_data.get('year') <= 8: New_Class.school_mode = 1 else: New_Class.school_mode = 2 New_Class.brunch = form.cleaned_data.get('brunch') New_Class.subject = form.cleaned_data.get('subject') New_Class.teacher.set(Staff.objects.filter(uuid=form.cleaned_data.get('teacher').uuid)) New_Class.save() my models.py file: @reversion.register() class Classes(BaseModel): semester = models.ForeignKey(Semester, on_delete=models.PROTECT,default=get_last_semester, verbose_name=("Semester")) school_mode = models.IntegerField(db_index=True, choices=SCHOOL_MODE, verbose_name=("School Type")) year = models.IntegerField(db_index=True, choices=CLASS_YEARS, verbose_name=("Year")) brunch = models.CharField(max_length=2, verbose_name=("Class Brunch")) subject = models.CharField(max_length=15, choices=CLASS_SUBJECTS, verbose_name=("Subject")) **teacher = models.ManyToManyField(Staff, blank=True, verbose_name=("Class Teachers"))** class Meta: unique_together = ('semester', 'year', 'brunch') ordering = ['semester', 'year', 'brunch', 'subject'] def __unicode__(self): return "%d %s %s %s / %s" % (self.semester, self.year, self.brunch, self.subject) auditlog.register(Classes) @reversion.register() class Staff(BaseModel): photo = models.ImageField(upload_to="Staff/", null=True, blank=True, verbose_name=("Photo")) user = models.OneToOneField(User, on_delete=models.PROTECT, db_index=True, verbose_name=("User")) name = models.CharField(max_length=30, db_index=True, verbose_name=("Name")) surname = models.CharField(max_length=30, db_index=True, verbose_name=("Surname")) id_no = models.CharField(max_length=15, unique=True,verbose_name=("ID Card Number")) birthdate = models.DateField(verbose_name=("Birthdate")) birthplace = models.CharField(max_length=30, verbose_name=("Birthplace")) gender = models.IntegerField(choices=GENDERS, default=None, verbose_name=("Gender")) nationality = models.CharField(choices=NATIONALITIES, max_length=20, verbose_name=("Nationality")) blood_type = models.CharField(choices=BLOOD_TYPES, null=True, blank=True, max_length=10, verbose_name=("Blood Type")) phone_home = models.CharField(max_length=15, null=True, blank=True, verbose_name=("Phone Home")) phone_mobile = models.CharField(max_length=15, null=True, blank=True, verbose_name=("Phone Mobile")) email = models.EmailField(default=None, null=True, blank=True, verbose_name=("Email Address")) address = models.TextField(verbose_name=("Address")) brunch = models.ForeignKey(TeacherBrunch, on_delete=models.PROTECT, verbose_name=("Brunch")) staff_type = models.ManyToManyField(StaffType, verbose_name=("Staff Type")) staff_status = models.IntegerField(choices=STAFF_STATUS, default=1, … -
Does web sockets consume more memory than WSGI app?
I am beginning to explore Django channels (to handle ASGI requests),and created a simple chat app following guide https://channels.readthedocs.io/en/latest/tutorial/part_3.html. If a user started chat with other user and leave chat window as it is, will the server waits / open the websockets until the any of the user closes the window ? If so I suppose that it will need more processor power to support multiple users. -
Save method didn't working for put or patch method in foreign table in djagno rest framework
I'm trying to develop system using django rest frameworks everythings is working fine but i've little but issue. ie save method is not working in foregin table for put and patch method. Suppose I've two table called A and B class A(models.Model): title = models.CharField(..) class B(models.Model): a = models.OneToOneField(A, .....) def save(self, *args, **kwargs): print('test') return super(B, self).save(*args, **kwargs) this is working fine for post method but not for put and patch method. I'm using djago rest frameworks. -
When i delete an object in Django Admin it is still being rendered on the webpage
I've tried to create a simple app that has a list of Categories and each Category has a list of Posts. When I delete a Category object in Django Admin it disappears in Admin but it remains rendered in the template. Here is Admin showing only two Categories However, on the home.html it shows 3.. the base.html serving the Navbar also shows 3 I have cleared cache and hard reload. Here is my code: Views.py from django.shortcuts import render, get_object_or_404 from .models import Post, Category from django.views.generic import ListView, DetailView category_list = Category.objects.all() def privacy(request): return render (request, 'privacy.html', {'category_list':category_list}) def home(request): return render(request,'home.html',{'category_list':category_list}) def categoryDetail(request, slug): category = get_object_or_404(Category, slug=slug) post = Post.objects.filter(category=category) return render(request,'category_detail.html',{'category':category, 'post':post, 'category_list':category_list}) and template, home.html {% if category_list %} <!-- Content Row --> <div class="row"> {% for cat in category_list %} <div class="col-md-4 mb-5"> <div class="card h-100"> <div class="card-body"> <h2 class="card-title"><a href="{% url 'category_detail' cat.slug %}">{{ cat.name }}</a></h2> <p class="card-text">{{ cat.summary|truncatechars:100 }}</p> </div> <div class="card-footer"> <a href="{% url 'category_detail' cat.slug %}" class="btn btn-primary btn-sm">More Info</a> </div> </div> </div> {% endfor %} </div> <!-- /.row --> {% else %} <h3>COMING SOON ...</h3> {% endif %} an similarly in base.html <ul class="navbar-nav ml-auto"> {% for cat … -
Generate same form dynamically pressing a buttom in django
I have modelform called WorkExperienceForm. Currently the form is adding only one information. But work experience can be of multiple times. forms.py: class WorkExperienceForm(forms.ModelForm): """ Creates a form for saving employee work experiences """ class Meta: model = WorkExperience fields = [ 'previous_company_name', 'job_designation', 'from_date', 'to_date', 'job_description', ] widgets = { 'previous_company_name': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'job_designation': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'from_date': forms.DateInput(attrs={'class': 'form-control form-control-sm has-feedback-left single_cal', 'id': 'single_cal3'}, format='%m/%d/%Y'), 'to_date': forms.DateInput(attrs={'class': 'form-control form-control-sm has-feedback-left single_cal', 'id': 'single_cal4'}, format='%m/%d/%Y'), 'job_description': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) I want to add a "Add" button to the frontend. When user presses add button, same form will be generated. This can be done unlimited times. I also want to add a delete button so that user can delete form if he/she creates form mistakenly. How can I do that using javascript??? Any help will be appreciated.