Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting the selenium scraping script output in web browser using django?
I had wrote a script for scrapping the data of all the matches that are being shown in this url https://web.bet9ja.com/Sport/OddsToday.aspx?IDSport=590 the script which I wrote is scrape.py import selenium.webdriver from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import mysql.connector import pymysql from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # the relevant url url = 'https://web.bet9ja.com/Sport/OddsToday.aspx?IDSport=590' # the driver path driver = webdriver.Chrome(r"c:/Users/SATYA/mysite/chromedriver") driver.get(url) driver.implicitly_wait(10) # seconds buttons = WebDriverWait(driver,15).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.Event.ng-binding"))) for btn in range(len(buttons)): #elements re-assigned again to avoid stale. buttons = WebDriverWait(driver, 15).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.Event.ng-binding"))) buttons[btn].click() headings= [item.text for item in driver.find_elements_by_css_selector("div.SECQ.ng-binding")] keys = [item.text for item in driver.find_elements_by_css_selector("div.SEOdd.g1")] values = [item.text for item in driver.find_elements_by_css_selector("div.SEOddLnk.ng-binding")] driver.execute_script("window.history.go(-1)") print(headings,keys,values) when I run this script in console using python scrape.py then I am getting output i.e scraping all the matches values dynamically now I actually I tried this script in django views.py and want to show the output in web page for that I wrote code like this views.py from django.shortcuts import render from django.http import HttpResponse import selenium.webdriver from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as … -
KeyError at /recommendation/ 'comb'
why I am getting this error at [comb] but when I have already mention it in create.py and in my views too when I have mentioned all the thing to be assign my views.py where I have also mentioned the [comb] def create_sim(): df = pd.read_csv('movies.csv') cv = CountVectorizer() count_matrix = cv.fit_transform(df['comb']) sim = cosine_similarity(count_matrix) return df, sim print("recommendation") def recommendation(request): if request.method == 'POST': movie = request.POST['movie'] movies = recomend(movie) movie = movie.upper() print("here is your movies ", movie) if type(movies) == type('string'): return HttpResponse('recommend.html', movie=movie, movies=movies, t='s') else: return HttpResponse('recommend.html', movie=movie, movies=movies, t='scores') return render(request, 'recommend.html') in this section, I have also mentioned the [comb] but in my ipynb I have mentioned combined_features is that the case or what. Mycreate.py df = pd.read_csv('movie_dataset.csv') df['comb'] = df['cast'] + ' ' + df['keywords'] + \ ' ' + df['genres'] + ' ' + df['director'] cv = CountVectorizer() count_matrix = cv.fit_transform(df['comb']) -
Create Views with DJangocms
I have just started with djnago cms 1 week ago . I have designed a simple html templates and used that template with home page . there is a form which accepts username & password in inside that template. Now my question is how can i connect that form with view.py so that it will check the form data and return response. -
How to change the name/label to delete objects in the change list page in Django admin
I'm working on Django and I want to change the name/label with which the delete action appears in the change list page in Django admin as shown in the pic : my admin.py file looks like this : from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): change_list_template='change_list_form.html' change_form_template = 'change_form.html' add_form_template='add_form.html' list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So is there any way to change it or is it permanent?? Thanks in advance!! -
Stripe InvalidRequestError InvalidRequestError at /payment/stripe/ Request req_5yo1v0CwbYGjTV: Must provide source or customer
Hi I'm trying to charge a user using stripe in Django. The problem I'm facing is that, when I printed my stripeToken value, in the console it is printing "None". That's the reason why I am getting "Invalid Parameters Error". I commented all the errors, just to see the real error, and it was: InvalidRequestError at /payment/stripe/ Request req_5yo1v0CwbYGjTV: Must provide source or customer. Why is my stripeToken value coming None? Can anyone please solve this problem? My Views.py: class PaymentView(View): def get(self, *args, **kwargs): the_id = self.request.session['cart_id'] cart = Cart.objects.get(id=the_id) order = Order.objects.get(cart=cart) token = self.request.POST.get('stripeToken') print(cart) print(order) print(token) return render(self.request, "orders/payment.html") def post(self, *args, **kwargs): the_id = self.request.session['cart_id'] cart = Cart.objects.get(id=the_id) order = Order.objects.get(cart=cart) amount = int(order.final_total * 100) # to convert it into cents token = self.request.POST.get('stripeToken') try: # user_stripe = self.request.user.userstripe.stripe_id # customer = stripe.Customer.retrieve(user_stripe) charge = stripe.Charge.create( amount= amount, currency="usd", # card= card, # customer = customer, source = token, description = "Charge for %s" %(self.request.user.username) ) # card = customer.cards.create(card=token) payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = int(order.final_total()) payment.save() order.payment = payment order.save() messages.success(self.request, "Your order was successful") return redirect("/") except stripe.error.CardError as e: # Since it's a decline, stripe.error.CardError … -
How to change the heading of the filter section in change list page of Django admin
I'm working on Django and I want to change the heading of the filter section which is marked in the pic: And my admin file looks like this : from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): change_form_template = 'change_form.html' add_form_template='add_form.html' list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So can we change the heading of the filter section without changing any thing else?? Thanks in advance!! -
Django serializers vs values method
What is the difference in using Model_Name.Objects.values().get() and serializers to get the data not in the form of model objects? -
How to add help text for many to many field in Django?
I created this simple model, but need your help to add a help_text: class FormModel(models.Model): fullname = models.CharField(max_length=150) slug = models.SlugField(max_length=255) ... interests = models.ManyToManyField(Interests) I tried several ways, there is a similar question in SO. It didn't work either. Thanks -
NoReverseMatch at /accounts/login/ Reverse for '' not found. '' is not a valid view function or pattern name
Environment: Request Method: POST Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 3.0.5 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'articles', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Joga\testenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Joga\testenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Joga\testenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Joga\Desktop\project\djangonautic\accounts\views.py", line 24, in login_view return redirect(request.POST.get('next')) File "C:\Users\Joga\testenv\lib\site-packages\django\shortcuts.py", line 41, in redirect return redirect_class(resolve_url(to, *args, **kwargs)) File "C:\Users\Joga\testenv\lib\site-packages\django\shortcuts.py", line 131, in resolve_url return reverse(to, args=args, kwargs=kwargs) File "C:\Users\Joga\testenv\lib\site-packages\django\urls\base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "C:\Users\Joga\testenv\lib\site-packages\django\urls\resolvers.py", line 677, in _reverse_with_prefix raise NoReverseMatch(msg) Exception Type: NoReverseMatch at /accounts/login/ Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name. after reading the traceback im pretty sure the errors at : return redirect(request.POST.get('next')) but i cant figure out whats wrong -
ERROR: Could not find a version that satisfies the requirement django==1.7b1 (from tictactoe) (from versions: 1.1.3 (...) 3.0.5 )
I'm trying to install the "tictactoe" module from pygame (I've already intall pygame), but when I run: pip3 install tictactoe I get an ERROR message (the one from the Title): ERROR: Could not find a version that satisfies the requirement django==1.7b1 (from tictactoe) (from versions: 1.1.3 (...) 3.0.5 ) And also: ERROR: No matching distribution found for django==1.7b1 (from tictactoe) Any idea on what might be the problem? I'm new in programming so it's probably something silly... -
Django sum total price from table items and table transaction
I have two tables, items and transaction, how do i calculate the total price, and displaying the total price in templates class Items(models.Model): items_name = models.CharField(max_length=50) price = models.PositiveIntegerField() def __str__(self): return self.items_name class Transaction (models.Model): items = models.ForeignKey(Items, on_delete=models.CASCADE) qty = models.PositiveIntegerField() def total_price(self): total = self.qty * self.items.price return total total_price = models.PositiveIntegerField(total_price) Here is the View def transaction(request): transactions=Transaction.objects.all() context={'transactions':transactionss} return render(request,'app/transaction.html',context) here is my template {% for transaction in transactions %} <tr> <td>{{transaction.item}}</td> <td>{{transaction.qty}}</td> <td><a class='btn btn-sm btn-info' href="#"> Update</a></td> <td><a class='btn btn-sm btn-danger' href="# ">Delete</a></td> </tr> {% endfor %} <tr><td> {{total_price}} </td></tr> I want to display the full total_price of all transactions, for example item 1 with price 100 * quantity 2 and item 2 with price 200 * quantity 3 . then the total price would be 200 + 600 = 800. I want to display the 800 in the template. -
Django-select2 HeavySelect2MultipleWidget -> Dynamic Choices
What is the correct way to use HeavySelect2MultipleWidget with Dynamic choices ?? I am using Django-select2 HeavySelect2MultipleWidget to fetch and select data by using ajax search from table... I referred Django-select2 documentation and testapp in their github repo, their documentation is not much helpful but in their testapp, they have very basic example. they are feeding choices from custom static list, which is not from database and also not dynamic. it loads everything to choices. if I use combination of ModelMultipleChoiceField and HeavySelect2MultipleWidget and if I pass queryset of respective model then it loads entire table in choices... which I dont want... my existing code looks like this: class CustReqForm(forms.Form): customer = forms.ModelMultipleChoiceField(widget=HeavySelect2MultipleWidget(data_view='customer_search',), queryset=Customer.objects.filter(channel='34342').all() ) I have a huge data in my table. though I filtered in my query, still it loads 100K unique records... Please advice the right method to implement this... -
Django overriden model save method returning old data
I may be tired and I'm not seeing something, but I've tried too much. class Pizza(models.Model): portion_size = models.ForeignKey('PortionSize', on_delete=models.PROTECT) pizza_type = models.ForeignKey('PizzaType', on_delete=models.PROTECT) toppings = models.ManyToManyField('Topping', blank=True) special = models.BooleanField() price = models.DecimalField( max_digits=4, decimal_places=2, editable=False, default=0 ) def calculate_price(self, topping_amount): print(self.toppings.count()) topping_amount = self.toppings.count() base_pizza = PizzaBase.objects.get( portion_size=self.portion_size, pizza_type=self.pizza_type, special=self.special, topping_amount=topping_amount ) self.price = base_pizza.price def save(self, *args, **kwargs): super().save(*args, **kwargs) self.calculate_price() This is model I've defined for Django and I'm trying to set the the price of the pizza that is being created when the user saves form, but every time the code is run, the toppings.count value is always behind. For instance, if I pick three toppings, and before saving the form in the admin panel there were only two toppings selected, I'd get the calculated price for two toppings. I've tried changing the order of the save method but it didn't change anything. I've also used the shell to check if there was a problem, but while in Django shell everything was fine with the toppings count. I've also check the admin interface, refreshed it multiple times, cleared cache and everything seemed fine there too. I've started Signals to solve this. Creating a receiver for … -
Django how to print out a list in html page
I have a list of data that looks like this [['mvpd', 'asdf, wefef', 'Optimum'], ['app_name', 'd', 'austin.com']] In my template I have a table that I want to put everything in. <table class="table table-hover"> <thead> <tr> <th scope="col">Property</th> <th scope="col">Expected Value</th> <th scope="col">Actual Value</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Mark</td> <td>Otto</td> </tr> <tr> <th scope="row">2</th> <td>Jacob</td> <td>Thornton</td> </tr> <tr> <th scope="row">3</th> <td colspan="2">Larry the Bird</td> </tr> </tbody> </table> However I am not sure how to grab the first list in the list and print them out in each row. Or will I need to send a different data structure to my template? -
cant get image to display Angular, GET 404 (Not Found)
Angular8. I am trying to display images that I previously saved using Angular/Django. I upload the images to the src/assets/images/images_are_here folder. I get the error GET http://127.0.0.1:8000/media/images/photo1_7x0DKZh.png 404 (Not Found). I have tried several different variations: <img [src]="recipe.photo"> and i tried creating a variable path that I then inserted <img [src]="path", tried brackets, no brackets around src. If I directly put in the path however this works <img src="assets/images/ryanphoto1_7x0DKZh.png"> When I save the image it uploads it to the correct place in the asset folder which is src/assets/images/ but when it displays the image filepath (in the browser) it shows http://127.0.0.1:8000/media/images/ which is correct because thats how my Django is set up: settings.py MEDIA_ROOT = '/Users///frontend2/src/assets' MEDIA_URL = '/media/' I think it has something to do with angular running on http://localhost:4200/ and django running on http://127.0.0.1:8000?? -
How can a post have an author on django?
I have been trying to make a post have the username of the creator on it but when I run the code, whenever I change profile, the username that is on the post changes. It seems That something on the models.py file is not correct. Views.py def home(request): created_posts = Create.objects.all().order_by("-added_date") return render(request, 'base.html', {"created_posts": created_posts}) def create(request): if request.method == 'POST': created_date = timezone.now() header1 = request.POST['header'] content1 = request.POST['content'] created_obj = Create.objects.create(added_date=created_date, title=header1, content=content1) created_obj.save() print('create created') return redirect('home') else: print('create not created') return render(request, 'create.html') Models.py class Create(models.Model): added_date = models.DateTimeField() title = models.CharField(max_length=200) content = models.CharField(max_length=200) create.html (creates the post) {% extends 'home.html' %} {% block body %} <div style="margin-top: 200px; margin-left:200px;"> <form action="create" method="POST"> {% csrf_token %} <input type="text" name="header" placeholder="Add here..."> <input type="text" name="content" placeholder="Add here..."> <button type="submit"name="action" class="btn btn-primary mb-2">submit</button> </form> </div> {% endblock %} base.html (shows the created posts in lists) {% extends 'home.html' %} {% block body %} <ul action="{% url 'create' %}" class="container-sm list-group" style="margin-top: 200px;"> {% for created_post in created_posts %} <li class="list-group-item">{{ created_post.title }} <p>{{ user.username }}</p> <p>{{ created_post.content }}</p> <div class="float-right"> <form action="delete_create/{{ created_post.id }}/" action="post"> <button type="submit" class="btn btn-outline-danger btn-sm">Delete</button> </form> </div> <div class="float-right"> <a href="{% … -
Assign Change Function To Django Formset Fields
I have the following function: <script> $("#id_form-0-ProductCode").change(function() { var pId = $("#id_form-0-ProductCode").val(); console.log(pId) $.ajax({ url: "/ajax/product", data : {'product': pId}, success: function(data) { $("#id_form-0-DescriptionOfGoods").val(data.DescriptionOfGoods) $("#id_form-0-Type").val(data.UnitType) $("#id_form-0-Price").val(data.Price) } }); }); </script> This is working perfectly fine - but the problem is that I'm offering the user the ability to add additional forms to the formset dynamically. So when they click the 'Add' button they get a new form. In that case, I would need the same function to apply to that form as well, but all of the ids would change so that the function would effectively look like: <script> $("#id_form-1-ProductCode").change(function() { var pId = $("#id_form-1-ProductCode").val(); console.log(pId) $.ajax({ url: "/ajax/product", data : {'product': pId}, success: function(data) { $("#id_form-1-DescriptionOfGoods").val(data.DescriptionOfGoods) $("#id_form-1-Type").val(data.UnitType) $("#id_form-1-Price").val(data.Price) } }); }); </script> Could anyone recommend the smartest way to implement this kind of thing? I don't want to write the function out many times A) because that's cumbersome and B) because that would create an upper limit to how many forms within the formset this would work for. -
Django Queryset Occurences Counts
I have the following django model... class Entry(models.Model): entry_UUID = models.UUIDField() entry_description = models.TextField() numeric_value = models.FloatField(null=True, blank=True) entry_category = models.CharField() I am trying to query the database - I expect groups of entry_UUIDs and for each group some statistics for numeric_value (Min/Max/Avg) and counts for entry_category. I won't know the specific values for entry_category ahead, but I expect them to form a set (ex. {low, med, high}). I have tried the following query: Entry.objects.filter( entry_UUID__in = entry_UUIDs).values( 'entry_UUID').annotate( Avg('numeric_value'), Min('numeric_value'), Max('numeric_value'), Count('entry_category')) Which returns... <QuerySet [{'entry_UUID': UUID('9fcfea6d-9480-595f-1e1f-81130ddc0c99'), 'numeric_value__avg': 51.5089, 'numeric_value__min': 23.174, 'numeric_value__max': 76.421, 'entry_category__count': 4}, {'entry_UUID': UUID('9fcfea6d-9490-595f-1e1f-81130ddc0c99'), 'numeric_value__avg': 5.2882, 'numeric_value__min': 1.282, 'numeric_value__max': 9.7553, 'entry_category__count': 6}]> For entry_category I am looking to get counts of occurences for each value rather that a total count. Not sure how to got about this. Thanks. -
How do I configure my Apache VirtualHost to only pass certain paths to my Django application?
I'm using Apache 2 on Linux 18.04 with Python 3.6. I have the following virtual host set up ... <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. ServerName lab.chicommons.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html/web # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. LogLevel info ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined #Alias /static /srv/rdmo/rdmo-app/static_root/ #<Directory /srv/rdmo/rdmo-app/static_root/> # Require all granted #</Directory> # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following line enables the CGI … -
Having trouble using js_link to add dropdown selector in Bokeh
I'm trying to implement widgets into my Bokeh diagrams. The first I would like is a drop down menu allowing the selection of other option strategies. I can't seem to figure out the js_link function in order to have the selection make a change on the graph. I fear I may have set up the diagram wrong. Any help is greatly appreciated. from bokeh.plotting import figure, output_file, show from bokeh.models import ColumnDataSource, Div, Select, Slider, TextInput,CustomJSTransform from bokeh.io import curdoc from bokeh.transform import transform from bokeh.layouts import gridplot, column import matplotlib import matplotlib.pyplot as plt import numpy as np strike1 = 20 #Long Call strike2 = 33 #Short Call strike3 = 30 #Long Put strike4 = 60 #Short Put premium1 = 0.5 premium2 = 1.6 premium3 = 2.1 premium4 = 1.5 price = np.arange(15,25,0.01) contracts = 1 symbol = 'TSLA' option = ['Long Call', 'Long Put', 'Short Call', 'Short Put', 'Bull Call Spread', 'Bear Put Spread', 'Straddle', 'Butterfly Spread', 'Box Spread', 'Iron Condor'] def long_call(price, strike1, premium1, contracts): P = [] for i in price: P.append((max(i - strike1, 0) - premium1) * (contracts * 100)) return np.array(P) def long_put(price, strike1, premium1, contracts): P = [] for i in price: P.append((max(strike1 … -
Django's FILE_UPLOAD_PERMISSIONS not working for directories
I'm trying to use Django's FILE_UPLOAD_PERMISSIONS to set permissions when a user uploads a file. The file itself is created with the correct permissions (775), but any directories created seem to be stuck with the default (755). Example: If a file (foo.jpg) is uploaded for a user (id = 123), it should save to media/123/foo.jpg, creating the 123 directory if it does not already exist. foo.jpg has 775 but 123 has 755. How can I get directories saving with the correct permissions? I am using Apache with mod_wsgi in a httpd Docker container if it is relevant. -
API gives 200 Success but object does not change Python
I'm calling this api to cancel an order in my app. After I call the api, I get a success message, but, nothing changes. Here is the code I'm using: API @csrf_exempt def customer_reset_order(request): customer = get_user(request) if not customer: return JsonResponse({'invalid token'}) order = Order.objects.filter( id=request.POST["order_id"], status=Order.READY ) order.status = Order.CANCELED order.save() return JsonResponse({"status": "reset"}) Why can I call the api but, see no change? -
Getting the id of a model from a button in Django
I currently have a template set up so that it loops through all of my menu items with a button that correspond to a post request in my views.py <td> {% for menu_items in menu %} {{ menu_items.Menu_name }} {% endfor %} </td> <td> {% for menu_desc in menu %} {{ menu_desc.Menu_Desc }} {% endfor %} </td> <form method="post"> {% csrf_token %} <th><input class="btn btn-success" type="submit" value="Add To Cart" name="add">. </th> </form> In my views file I have a if statement that tries to get the id of the model that was clicked. However, i'm only able to get the Query Set and not the specific ID of the model. def ordering(request): latest_order = Order.objects.all() menu = Menu.objects.all() if 'add' in request.POST: user_order = Order.objects.get(name='') print(menu.id) return render(request, 'users/ordering.html', {'title':'Ordering', 'latest_order': latest_order, 'menu':menu}) -
Django: CSRF verification fail despite token being provided
I get 403 error due to csrf_token verification failure in spite of token explicit declaration in an ajax call. I for my data dictionary in the same manner in other functions and it works just great. Here is JS: $(document).on("click", ".update-cleaning", function(event){ event.preventDefault(); var input_field_name = $(this).attr('name') var obj_id = $(this).attr('value') var model_name = $(this).attr('data-model') var field_name = $(this).attr('data-field') var value = $("#" + input_field_name + obj_id).val(); if (!value) { alert('Fill the field!') } else { $.ajax({ url: "{% url 'ajax_update_cleaning' %}", type: "POST", data: {'object_id': obj_id, 'model_name': model_name, 'field_name': field_name, 'value': value, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: 'json', }) .done(function(response){ console.log(response); }) } }); My html form is in a popover which is toggled by a click on <td> and looks like this: <td class="text-md-center with-popover" name="frequency" value="{{cleaning.id}}"> {{ cleaning.frequency }} <div id="frequency{{cleaning.id}}" style="display: none"> <form method="POST"> <label for="cleaning_frequency">Frequency: </label> <input id="cleaning_frequency{{cleaning.id}}" type="number" name="cleaning" value="{{cleaning.frequency}}"> <button type="submit" class="btn btn-success btn-sm update-cleaning" name="cleaning_frequency" data-model="Cleaning" data-field="frequency" value="{{cleaning.id}}"> Change </button> </form> </div> </td> Could you give me some ideas? Thank you. -
Filtering Blogs Posts in Django based on Admin Approved Posts
I have made a blog as a project and I have set users to submit posts for the blog directly but I want to direct this post to the admin first for approval before showing on the website. I have added a field to Post model, 'admin_approved = models.BooleanField(default=False)'. I also filtered by Post.objects.filter(admin_approved=True), but still nothing happens and posts are published class PostListView(ListView): model = Post template_name = "score.html" ordering = ['-date_posted'] context_object_name = 'posts' def score(request): context = { 'posts': Post.objects.filter(admin_approved=True) } return render(request, "score.html", context) class PostDetailView(DetailView): model = Post template_name = "post_detail.html" class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['caption', 'design'] template_name = "post_form.html" success_url = '/score' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) Here is the model: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to='new designs') caption = models.TextField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) admin_approved = models.BooleanField(default=False) def __str__(self): return self.caption def get_absolute_url(self): return reverse("core:post-detail", kwargs={"pk": self.pk}) Am I missing a step or is there something I should do?