Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with filter in django orm by json field
Could someone help me with django orm filter I am trying to filter data by some key in json filed (Postgres, jsonb field) Field in postgres table contains something like { "pet": "dog", "name": "my_lovely_dog" } I build filter like: cond = {"field_name__pet": some_variable} qs = qs.filter(**cond) But when I watch result sql query I see something like: Select * from "table_name" where ("table"."my_field" -> pet) = '"dog"' How I can do it correctly? Why django use "" inside ''? And why django not put key from json in ""? Thank you -
How to call pytest-django from python manage.py test?
I have made my custom management command called pytest_wrp So when I call python manage.py test This bit of code is called: super(Command, self).handle(*args, **options) # this calls the python manage.py test self.stdout.write("My code starts from here.") management.call_command(pytest_wrp.Command(), '--pact-files="{argument}"'.format(argument=path_to_file), '--pact-provider-name="MyService"', verbosity=0) The pytest_wrp basically has this code in it: class Command(BaseCommand): help = "Runs tests with Pytest" def add_arguments(self, parser): parser.add_argument("args", nargs=argparse.REMAINDER) def handle(self, *args, **options): pytest.main(list(args)) # This gets executed but this calls default pytest not django-pytest But this calls pytest not pytest-django Hence the extra arguments that I am passing don't get recognized and pytest can't start the test suite. I wanna pass the extra arguments for some of the test cases. If there is some way to call pytest-django directly and pass the extra arguments in code that would be optimal. -
fetch a list of related many-to-many values as a field on the related model queryset in django
I have models that look like this: class Schedule(models.Model): field1 = models.CharField(max_length=20) plans = models.ManyToManyField(Plan, through="Schedule_Plan") users = models.ManyToManyField(User, through="Schedule_User") class Plan(models.Model): field2 = models.CharField(max_length=20) users = models.ManyToManyField(User, through="Plan_User") class Plan_User(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) plan = models.ForeignKey(Plan, on_delete=models.CASCADE) is_owner = models.BooleanField(default=True) class Schedule_Plan(models.Model): plan = models.ForeignKey(Plan, on_delete=models.CASCADE) schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE) class Schedule_User(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE) is_owner = models.BooleanField(default=True) I would like to create a queryset that contains the following field outputs: schedule.id, schedule.field1, schedule.users.is_owner, [list of schedule.plans.id] I am able to get the first three fields together using: qs1 = Schedule.objects.filter(users__in=[self.request.user]).order_by('-id') qs2 = Schedule_User.objects.filter(user_id=self.request.user.id).order_by('-schedule_id').values('is_owner') data = zip(qs1, qs2) ...and I unpack them in tags using: {% for schedule, ownership in plans.schedule_data %} ---- do something using schedule.field1 ----- ---- do something using ownership.is_owner ----- {% endfor %} All of that is successful. I need to add the list of plans to the output so I can access the list similarly. I have read about prefetch_related() but have not been able to implement it successfully for this issue. Also I've considered using values_list but haven't been successful there either. I am open to any ideas that will produce the desired result. *Please note, plans … -
How can I avoid circular import in django models?
I need to import address into my UserProfile so I could keep track of all addresses of a person in his profile, also I wanted to import owner into my AddressBook to know which profile I am saving this address to. Below is the code I tried but since it is a circular import I am not able to do that, how do I overcome this situation. Any help would be appreciated. class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="profile") address = models.ManyToManyField(AddressBook, blank=True) class AddressBook(models.Model): name = models.CharField(max_length=50) owner = models.ForeignKey(UserProfile, on_delete=models.SET_NULL, null=True) has_address = models.BooleanField(default=False) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17) # validators should be a list line1 = models.CharField(max_length=100) line2 = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=25) state = models.CharField(max_length=25) postcode = models.CharField(max_length=8) country = models.CharField(max_length=25) -
Django: how to display inlineformset fields 'in line' and not one below another
I try to implement for the first time inlineformset following this tutorial But I would like to change the inlineformset field organization of each subform (in line and not in column) Currently, fields are displayed one below another: User (parent model) Name: ___________________________________ Application (child model) Name: Access: delete Name: Access: delete Name: Access: delete Submit I would like this: User (parent model) Name: ___________________________________ Application (child model) Name: Access: delete Name: Access: delete Name: Access: delete Submit I have tried to render fields manually with a loop on fields but get this: User (parent model) Name: ___________________________________ Application (child model) Name: Name: Name Access: Access: Access delete: delete: delete Submit user_form.html <form id="utilisateureditform" method="POST" class="post-form"> {% csrf_token %} {{ form|crispy }} <br><br><div class="dropdown-divider"></div><br><br> <h2>Applications</h2><br><br> {{ application|crispy }} <!-- <div class="row"> {% for field in application %} <div class="col-4"> <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> </div> {% endfor %} </div> --> <input class="btn btn-primary" type="submit" value="Valider" style="width: 100px;"> <a data-modal data-target="" class="btn btn-danger" href="{% url 'project:index' %}" style="width: 100px;">Annuler</a> </form> I also tried this approch as mentionned in Django doc to be able … -
`django-cron==0.5.0` is not able to run scheduled cron jobs in `python:2.7` and `python:2.7-slim-buster` docker image
I'm sharing my GitHub repository link for your reference. https://github.com/deepenpatel19/test_django_cron Here, I have set up one project to test cron scheduler in Docker. but, the scheduler is not being run on time. I have to run manually. Django dependencies: Django==1.8 django-cron==0.5.0 uwsgi==2.0.18 django-common-helpers==0.9.2 Docker configuration: FROM python:2.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code RUN apt-get update && apt-get purge nodejs && apt-get install -y --no-install-recommends gcc g++ default-libmysqlclient-dev libssl-dev libjpeg62-turbo-dev zlib1g-dev curl wget apt-transport-https gnupg2 nginx supervisor cron vim&& wget https://nodejs.org/dist/v6.4.0/node-v6.4.0-linux-x64.tar.xz && apt-get install -y xz-utils && tar -C /usr/local --strip-components 1 -xJf node-v6.4.0-linux-x64.tar.xz && curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && apt-get update && apt-get install -y yarn && sed '/st_mysql_options options;/a unsigned int reconnect;' /usr/include/mysql/mysql.h -i.bkp && apt-get clean && pip install Django==1.8 django-cron==0.5.0 uwsgi==2.0.18 django-common-helpers==0.9.2&& rm -rf /var/lib/apt/lists/* && rm -rf /root/.cache ADD . /code/ RUN useradd --no-create-home nginx RUN rm /etc/nginx/sites-enabled/default RUN touch /var/log/cron.log COPY nginx.conf /etc/nginx/ COPY django-site-nginx.conf /etc/nginx/conf.d/ COPY uwsgi.ini /etc/uwsgi/ COPY supervisord.conf /etc/supervisor/ WORKDIR /code EXPOSE 8081 CMD ["/usr/bin/supervisord"] -
Django Backend Filter for nested object
I have one API which contains few fields which are from different model. Those fields are like list of objects. I want to apply Django filter which will also work for those fields as well. (List of objects fields ) Sample JSON: { field1: "value" field2: "Value" field3: [ { Nestfield1: "value" Nestfield2: "Value" }, { .. } ] } I want to apply Django backend search,filter,sort on api's fields(field1,field2, etc) as well as objects inside field3 (Nestfield1,Nestfield2,..) -
Heroku Custom Domain Issues
I couldn't access my heroku app with a www prepended to the domain name. I had to change it from a root custom domain to a custom subdomain on Heroku. After deleting the old domain settings and reinstalling, I keep getting this when I run host www.darader.com www.darader.com is an alias for darader.herokuapp.com. darader.herokuapp.com has address 18.235.131.220 darader.herokuapp.com has address 3.208.142.122 darader.herokuapp.com has address 52.0.3.28 darader.herokuapp.com has address 54.164.210.125 darader.herokuapp.com has address 34.226.45.27 darader.herokuapp.com has address 34.232.191.21 darader.herokuapp.com has address 52.21.209.224 darader.herokuapp.com has address 52.203.224.128 Thanks in advance. -
Keyerror/MultiValueDictKeyError while sending file to django
I am sending the form data to a django api and the form data includes file also. When I am sending the data to django through AJAX, the MultiValueDict is {} empty and I am getting the KeyError for the file. I tested without sending file it's working but when I send file it's not working. index.html [Front End] <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" style="background-color:#00d1b2;border-color: transparent;color: #fff;font-size:20px;font-family:sans-serif;">Create Auto-Label Project</button> <div class="modal" id="myModal" > <div class="modal-background"></div> <div class="modal-card" style="width:800px;"> <header class="modal-card-head"> <p class="modal-card-title">Create Auot-Label Project</p> <button type="button" aria-label="close" class="delete" data-dismiss="modal">&times;</button> </header> <section class="modal-card-body"> <form method="POST" id="upload" name="upload" action="http://API_LINK"> <div class="field"> <label class="label">Project Name</label> <div class="control"> <input type="text" name="project_name" id="project_name" required="required" placeholder="Project name" class="input"> </div> <p class="help is-danger"></p> </div> <div class="field"> <label class="label">Description</label> <div class="control"> <textarea name="description" id="description" required="required" placeholder="Project description" class="textarea"></textarea> </div> <p class="help is-danger"></p> </div> <div class="field"> <label class="label">Project Type</label> <div class="control"> <select name="project_type" id="project_type" required="required"> <option value="" selected="selected">---------</option> <option value="DocumentClassification">document classification</option> <option value="SequenceLabeling">sequence labeling</option> <option value="Seq2seq">sequence to sequence</option> </select> </div> <p class="help is-danger"></p> </div> <div class="field"> <label class="label">Model Type</label> <div class="control"> <select name="model_name" id="model_name" required="required"> <option value="" selected="selected">---------</option> <option value="sn">Simple NER</option> <option value="mn">Bio-NER</option> <option value="sa">Sentiment Analysis</option> </select> </div> <p class="help is-danger"></p> </div> <div class="field"> <label class="label">Guideline</label> <div class="control"> … -
Django : How to extract full address previously saved as default in template
I have made a checkout process where users can add a new address and set it as default for next orders The address contains Street_address, Street address2, Province, Country, Postal_Code and Phone. I wanted to show the full default address before proceeding. I have reached to the point where I show the Street_address only but I tried to show the rest but failed. How to extract the rest of the address? This is the view: class CheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, } shipping_address_qs = Address.objects.filter( user=self.request.user, address_type='S', default='True' ) if shipping_address_qs.exists(): context.update( {'default_shipping_address': shipping_address_qs[0]}) def post(self, *args, **kwargs): form = CheckoutForm(self.request.POST or None) try: order = Order.objects.get(user=self.request.user, ordered=False) if form.is_valid(): use_default_shipping = form.cleaned_data.get( 'use_default_shipping') if use_default_shipping: print("Using the defualt shipping address") address_qs = Address.objects.filter( user=self.request.user, address_type='S', default=True ) if address_qs.exists(): shipping_address = address_qs[0] order.shipping_address = shipping_address order.save() else: messages.info( self.request, "No default shipping address available") return redirect('core:checkout') else: print("User is entering a new shipping address") shipping_address1 = form.cleaned_data.get( 'shipping_address') shipping_address2 = form.cleaned_data.get( 'shipping_address2') shipping_province = form.cleaned_data.get( 'shipping_province') shipping_country = form.cleaned_data.get( 'shipping_country') shipping_postal_code = form.cleaned_data.get( 'shipping_postal_code') shipping_phone_number = form.cleaned_data.get( 'shipping_phone_number') if is_valid_form([shipping_address1, shipping_province, shipping_country, … -
Django custom through table for ManyToMany relationship: save method not being called during model form save (or save_m2m)
Here's the setup... class RequestUserBaseClass(Model): # There is middleware that sets "thread.request" with each request - that is functioning fine thread = threading.local() created_by = ForeignKey(User) ... def save(self, *args, **kwargs): self.created_by = RequestUserBaseClass.thread.request.user ... class Meta: abstract = True class CustomThroughTable(RequestUserBaseClass): ... class SimpleModelClass(RequestUserBaseClass): ... manyfield = ManyToManyField(OtherTable, through=CustomThroughTable) ... class SimpleModelForm(ModelForm): class Meta: fields = [... 'manyfield' ... ] in a view... if simple_form.is_valid(): simple_form.save() Bottom line: I have this base class, it sets the created by field by working together with some custom middleware that puts the user in a thread local variable. Works great, use it all over the place. Then I have a model with a many to many that uses a custom through table. When the form gets saved, I get an integrity error about created_id not being set, and from inspecting the output it is when the entry in the through table is being added into the database. This lines up because I only get the error when the many to many field has been edited. Why would this be though? Would "save()" not be getting called when that through table entry is added or something? Feel free to ask for more info … -
Slice an array in two (balanced) halfs in DJango template
I am newbie in DJango and Python both. I have tag model and his manager. Tags must be shown on every page on my site. I want they to be shown in two balanced columns - left and right. For now, I have written this code for responding view: def my_view(request): # ... tags = QuestionTag.manager.all() return render(request, 'page.html', { # ..., 'tags_left': tags[:int((len(tags) + 1) / 2)], # for left column 'tags_right': tags[int((len(tags) + 1) / 2):] # for right column }) and this code for the base template: <div class="card my-4"> <h5 class="card-header">Tags</h5> <div class="card-body"> <div class="row"> <div class="col-lg-6"> <ul class="list-unstyled mb-0"> {% for tag in tags_left %} <li> <a href="{% url 'forum:tag' tag %}">{{ tag }}</a> </li> {% endfor %} </ul> </div> <div class="col-lg-6"> <ul class="list-unstyled mb-0"> {% for tag in tags_right %} <li> <a href="{% url 'forum:tag' tag %}">{{ tag }}</a> </li> {% endfor %} </ul> </div> </div> </div> </div> And currently my block of tags on every page seems like that: Tags are adding/removing so often, so I don't know how much tags do I have for any moment of time. I need to write a unique code for template that will slice an array … -
I'm trying to give user posibility to upload picture from blog-page, but I'm stucked at 'models' file
It says: form_class = PostForm(request.FILES or None) NameError: name 'request' is not defined -
Exclude fields when nesting serializer Django REST Framework
serializers.py class ThreadSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) last_post_user = UserSerializer(read_only=True) class Meta: model = Thread fields = '__all__' read_only_fields = ('locked', 'views', 'post_count', 'last_post_time') class ChannelSerializer(serializers.ModelSerializer): threads = ThreadSerializer(many=True, read_only=True) class Meta: model = Channel fields = ['id', 'name', 'description', 'category', 'threads'] class CategorySerializer(serializers.ModelSerializer): channels = ChannelSerializer(many=True, read_only=True) class Meta: model = Category fields = ['id', 'name', 'channels'] You'll notice I have nested ChannelSerializer in CategorySerializer, when I visit the endpoint that queries data using CategorySerializer I was hoping it would list out only data from ChannelSerializer however it lists data from ThreadSerializer as well, I'd assume this is expect behavior since ThreadSerializer is nested inside ChannelSerializer. Is there some elegant way I can exclude fields when I nest serializers? in this case I'd like to exclude threads from appearing when querying data using the CategorySerializer I tried the answer from a similar question but can't seem to get it working in my case unfortunately, it ends up listing the threads again, also I'd think there's a simpler way to do it. -
Error parsing json content through JSON.parse()
I'm using the json_script template tag from django to take a json from a context view. I receive the json like this {{rules|json_script:"rules"}} <script lang="javascript"> const rules = JSON.parse($('#rules').text()) </script> this is what i receive from {{rules|json_script:"rules"}} <script id="rules" type="application/json">{"id": 10, "string": "demo", "profile": "Alumno Demo", "license": "Licencia no facturable por usuario demo", "field": "codigo_usuario", "include": true, "order": 1, "uppercase_sensitive": false, "dateadded": "2020-05-11T08:06:35Z", "billable": false}</script> But when i try to JSON.parse I receive this error: VM760:5 Uncaught SyntaxError: Unexpected token R in JSON at position 5 What am I doing wrong? If I copy the content of the script it seems like a correct json. Thanks in advance! -
Integrate Raw SQL Query into Django ORM with Aggregations
I'm trying to integrate this RAW query into a django ORM query but I'm facing problems to apply the raw query and the orm query The original query which works fine with postgres querytools: "SELECT SUM(counter),type, manufacturer FROM sells GROUP BY manufacturer, type" Now I tried to integrate this into a django-orm query like this: res_postgres = Sells.objects.all().values('manufacturer','type','counter').aggregate(cnter=Sum('counter')) But what I get is just a the counter cnter ... What I need is the result from the Raw query which looks like this What I also tried is to use values and field names. Like Sells.objects.values('manufacturer'....).aggregate(cnter=Sum(counter)) But then django is building a query which integrates a GROUP BY id. Which is not what I need. I need an aggregation of the entire data not the object level while keeping the information of the other fields. When I use Cars.objects.raw() it asks me about primary keys, which I also don't need. Any hints here? is that possible with Django ORM at all? -
give the same instance of a form to the other in one submit button
i have two tables(models) one for product name and features and the other for prices i normalized to database tables like this class Model(models.Model): name = models.CharField(max_length=23) def __str__(self): return self.name class Feature(models.Model): model = models.ForeignKey(Model,on_delete=models.CASCADE) price = models.IntegerField() company = models.CharField(max_length=33) def __str__(self): return self.model my views.py def create(request): createmodel = ModelForms(prefix='createmodel') createfeature = FeatureForm(prefix='createfeature') if request.method == 'POST': createmodel = ModelForms(request.POST,prefix='createmodel') if createmodel.is_valid(): createmodel.save() name = createmodel.cleaned_data['name'] if createfeature.is_valid(): createfeature = FeatureForm(request.POST,prefix='createfeature',model=name) createfeature.save() return redirect('/lists/') return render(request,'forms/create.html',{'createmodel':createmodel,'createfeature':createfeature}) my forms.py class ModelForms(forms.ModelForm): class Meta: model = Model fields = [ 'name' ] class FeatureForm(forms.ModelForm): read_only = ['model'] class Meta: model = Feature fields = [ 'price','company' ] but the form wont saved how to submit both forms at the same time with providing the exact foreign key (as filled in ModelForm to FeatureForm)in one go i know how to do it in updating two forms , but how to create submit two forms with providing the instance directly much respect -
ReactJS & Django axios.post (403 error code)
I keep getting error code 403 (Forbidden (CSRF cookie not set.): /api/) even after following some responses on this kind of questions. This is my code: JS import axios from 'axios'; axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN'; axios.defaults.xsrfCookieName = 'csrftoken'; class App extends Component { postHandler = (event) => { event.preventDefault(); axios.get('http://localhost:8000/api/') .then((response) => { console.log(response) }) .catch(error => alert(error)); }; } settings.py CORS_ORIGIN_WHITELIST = 'http://localhost:3000', views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello!") Anything else is set as defaults from create-react-app and django-admin startproject. -
How to run batch file in remote server(windows 10) from Django Web server
I am new to Django learning and have fairly understood basic polls app from Django tutorial, Now I ahve below requirement: I have a basic (server1) Django development web server and another server (server2) which has a python script or a batch file that launches a python application . Assume that the server1 has necessary authentication in place to run the script on server2. All I want to do is, click a button on the django website which would run the python script sitting on server2. I am really clueless here on how to achieve it, Will Django REST APIs work in this case ? I am not aware of what Django REST APIs do but willing to learn if it solves the purpose. Any help highly appreciated. -
postgres & docker compose: change service status to ready after additional initialization
In my case, a postgres database works as the main django backend database. Additional postgres initialization is required. The problem is that status of postgres service becomes ready before additional database initialization. As a result, dependent django app starts running prior to database initialization. Is there any way to configure postgres service in a way that becomes ready after additional initialization? docker compose file: version: "3.3" services: postgres: image: library/postgres:11 volumes: - some_folder:/docker-entrypoint-initdb.d django_app: image: custom_django_image:latest volumes: - $PWD:/app ports: - 8000:8000 depends_on: - postgres -
Django Formtools
I have a form in Django that i want to transform to a multi step form. The issue i have is in the view. My code before formtools: class CharacterCreateView(ObjectCreateView): template_name = "character/create.html" def form_valid(self, form): # Get account object creating the character account = self.request.user character = None # Get attributes from the form self.attributes = {k: form.cleaned_data[k] for k in form.cleaned_data.keys()} charname = self.attributes.pop("db_key") background = self.attributes.pop("background") # Create a character character, errors = self.typeclass.create(charname, account, background=background) if errors: # Echo error messages to the user [messages.error(self.request, x) for x in errors] if character: # Assign attributes from form for key, value in self.attributes.items(): setattr(character.db, key, value) # Return the user to the character management page, unless overridden messages.success(self.request, "Your character '%s' was created!" % character.name) return HttpResponseRedirect(self.success_url) else: # Call the Django "form failed" hook messages.error(self.request, "Your character could not be created.") return self.form_invalid(form) My code after formtools: class CharacterCreateView(ObjectCreateView, SessionWizardView): template_name = "character/create.html" form_list = [FormStepOne, FormStepTwo] def done(self, form_list, **kwargs): # Get account object creating the character account = self.request.user character = None # Get attributes from the form self.attributes = {k: form_list.cleaned_data[k] for k in form_list.cleaned_data.keys()} charname = self.attributes.pop("db_key") background = self.attributes.pop("background") # Create … -
Django migration to delete rows from database
How can I delete rows from a database table with some criteria via a migration script? Do I need to manually write it or generate it? How to create the file? -
Database Error:No exception message supplied
I am trying to create an article here.I started to get this error that says Database Error:No exception message supplied Here is my views.py class ArticleCreateView(CreateAPIView): serializer_class = ArticleCreateSerializer permission_classes = (IsAuthenticated,) def create(self, request): serializer_context = { 'request': request } serializer_data = request.data.get('article',{}) serializer = self.serializer_class( data=serializer_data, context=serializer_context, ) serializer.is_valid(raise_exception=True) serializer.save() response = { 'success' : 'True', 'status code' : status.HTTP_200_OK, 'message': 'Article Created Successfully!', } status_code = status.HTTP_200_OK return Response(serializer.data, status=status.HTTP_201_CREATED) serializer.py class ArticleCreateSerializer(serializers.ModelSerializer): caption = serializers.CharField(required=False) details = serializers.CharField(required=False) author = UserSerializer(read_only=True) class Meta: model = Article fields = ('id','author','caption','details') def create(self, validated_data): author=self.context['request'].user.profile article = Article.objects.create(author=author,**validated_data) return article Does anyone know the cause? -
Django : how to group in a template on a foreign key field multiple traverses away , how to loop over a foreign key field in a view
i'm building a system for managing preventive tasks per asset in our factory. Thanks to the nice documentation and tutorials about django i've managed to build to following app : a tree structure using mptt to show a tree stucture of our plant, the thee shows functional locations, at the lowest level the tree node is of type asset, to which we can attach asset templates (max 3 assets per location) tree image an asset list, to which we attach tasks a task list to which we attach work instructions, spare parts, materials, Crafts, Period, can be performed when asset in use... etc a craft list to select from in each task a period list to select from in each task i've managed to create a template listing all descendants of a functional location, the assets per location, and the tasks per asset : enter image description here the goal is now to create a pdf file with a task list for a location and its descendants per each task-period ( and asset in use yes or no ) for a selected location. To accomplish this i'm trying to build a view where i detect the distinct task-periods and "can … -
How do i update comment count using Ajax
i am working on a project in Django where users can comment on a post. How do i update the comment count of each post, when user comment on a post increases the count to 1. I tried adding the id to div's but nothing happened. How do i implement this? Home Template: <!-- Comment button --> <div class="col-4 col-md-4 col-lg-4" id="newfeeds-form"> {% if post.comments.all %} {{ post.comments.count }} {% endif %} </div> <!-- New Feeds Comment Form --> <div id="newfeeds-form"> {% include 'ajax_newfeeds_comments.html' %} </div> Ajax submit comment: $(document).ready(function() { $('.feeds-form').on('submit', onSubmitFeedsForm); $('.feeds-form .textinput').on({ 'keyup': onKeyUpTextInput, 'change': onKeyUpTextInput // if another jquery code changes the value of the input }); function onKeyUpTextInput(event) { var textInput = $(event.target); textInput.parent().find('.submit').attr('disabled', textInput.val() == ''); } function onSubmitFeedsForm(event) { event.preventDefault(); // if you need to use elements more than once try to keep it in variables var form = $(event.target); var textInput = form.find('.textinput'); var hiddenField = form.find('input[name="post_comment"]'); $.ajax({ type: 'POST', url: "{% url 'site:home' %}", // use the variable of the "form" here data: form.serialize(), dataType: 'json', beforeSend: function() { // beforeSend will be executed before the request is sent form.find('.submit').attr('disabled', true); }, success: function(response) { // as a hint: since you …