Implementing #check_honeypot on Django Wagtail Form - wagtail

I am trying to implement Honeypot into a Wagtail email form, but I don't understand how to add the #check_honeypot decorator to a class in models.py, which checks the honeypotfor validity.
To set up Honeypot, it requires that I add the #check_honeypot decorator to the form view in my views.py. Unfortunately, wagtail does not utilize views.py and instead the form is built in the models.py.
How to I implement honeypot decorator onto a Wagtail form?
Honeypot repo: https://github.com/jamesturk/django-honeypot
Snippet from honeypot instructions:
To ensure that the honeypot field is both present and correct you will >need to use check_honeypot decorator from honeypot.decorators:
from honeypot.decorators import check_honeypot
#check_honeypot(field_name='hp_field_name')
def post_comment(request):
...
#check_honeypot
def other_post_view(request):
...
SOLUTION:
#method_decorator(check_honeypot)
def render_landing_page
models.py
class FormField(AbstractFormField):
page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields')
class FormPage(AbstractEmailForm):
header = RichTextField(blank=True)
body = RichTextField(blank=True)
header_two = RichTextField(blank=True)
body_two = RichTextField(blank=True)
header_three = RichTextField(blank=True)
body_three = RichTextField(blank=True)
address = RichTextField(blank=True)
form_header = models.CharField(blank=True, max_length=100)
thank_you_text = RichTextField(blank=True)
content_panels = AbstractEmailForm.content_panels + [
FieldPanel('header', classname="full"),
FieldPanel('body', classname='full'),
FieldPanel('header_two', classname="full"),
FieldPanel('body_two', classname='full'),
FieldPanel('header_three', classname="full"),
FieldPanel('body_three', classname='full'),
FieldPanel('address', classname='full'),
FieldPanel('form_header', classname='full'),
InlinePanel('form_fields', label="Form fields"),
FieldPanel('thank_you_text', classname="full"),
MultiFieldPanel([
FieldRowPanel([
FieldPanel('from_address', classname="col6"),
FieldPanel('to_address', classname="col6"),
]),
FieldPanel('subject'),
], "Email"),
]
thank_you_page = models.ForeignKey(
'wagtailcore.Page',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+',
)
def render_landing_page(self, request, form_submission=None, *args, **kwargs):
if self.thank_you_page:
url = self.thank_you_page.url
# if a form_submission instance is available, append the id to URL
# when previewing landing page, there will not be a form_submission instance
if form_submission:
url += '?id=%s' % form_submission.id
return redirect(url, permanent=False)
# if no thank_you_page is set, render default landing page
return super().render_landing_page(request, form_submission, *args, **kwargs)
content_panels = AbstractEmailForm.content_panels + [
FieldPanel('header', classname="full"),
FieldPanel('body', classname='full'),
FieldPanel('header_two', classname="full"),
FieldPanel('body_two', classname='full'),
FieldPanel('header_three', classname="full"),
FieldPanel('body_three', classname='full'),
FieldPanel('address', classname='full'),
FieldPanel('form_header', classname='full'),
InlinePanel('form_fields'),
FieldPanel('thank_you_text', classname='full'),
PageChooserPanel('thank_you_page'),
MultiFieldPanel([
FieldRowPanel([
FieldPanel('from_address', classname='col6'),
FieldPanel('to_address', classname='col6'),
]),
FieldPanel('subject'),
], 'Email'),
]
form.html
<section class="contact-background-lg" >
<div class="container px-0">
<div class="card p-m-5-0">
<form action="{% pageurl page %}" method="POST">
{% csrf_token %}
{% render_honeypot_field "phonenumber" %}
<div class="row">
<div class="col-md-12 col-sm-12">
{% if form.non_field_errors %}
<div class="alert alert-danger" role="alert">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
{% endif %}
<div class="card-title text-primary">
<h2><strong>{{ page.form_header }}</strong></h2><p class="pb-2 text-muted">Please complete the form below to receive a response within 24 hours.</p>
<hr>
<br>
</div>
</div>
{% for field in form.visible_fields %}
<div class="col-md-6 col-sm-12">
<div class="form-group pt-3">
{{ field.label_tag }}
{% render_field field class+="form-control" %}
</div>
</div>
{% endfor %}
</div>
<div class="pull-center">
<button type="submit" class="btn btn-primary-alt py-3 mt-3" style="width: 8rem;">Submit</button>
</div>
</form>
</div>
</div>
</section>

Related

Decrement model value in django

It's my first time using django to clear my schoolwork, I want to lower Stock in my Book class by Quantity value,
ex.
Stock = 10 and Quantity = 1
Stock = 9 because 10 - 1 for Stock - Quantity
this is my code
main.html
{% load static %}
<html>
<head>
<title>
Bookstore Management System
</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
{% include 'book/navbar.html' %}
{% block content %}
{% endblock %}
<br>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
</html>
home.html
{% extends 'book/main.html' %}
{% block content %}
<br>
<div class="container jumbotron">
<div class="container row">
<div class="col-lg-10">
<table class="table table-sm">
<tr>
<th>title</th>
<th>Author</th>
<th>Edition</th>
<th>Stock</th>
<th>Price</th>
</tr>
{% for book in books %}
<tr>
<td>{{book.title}}</td>
<td>{{book.Author}}</td>
<td>{{book.Edition}}</td>
<td>{{book.Stock}}</td>
<td>{{book.Price}}</td>
<td><a class="btn btn-sm btn-info" href="{% url 'addtocart' book.id %}">Add to cart</a></td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
viewcart.html
{% extends 'book/main.html' %}
{% load static %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-lg-10"></div>
<br>
<h5>BOOKS:</h5>
<div class="card card-body">
<table>
<tr>
<th>title</th>
<th>Author</th>
<th>Edition</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
{% for book in cart.books.all %}
<tr>
<td>{{book.title}}</td>
<td>{{book.Author}}</td>
<td>{{book.Edition}}</td>
<td>{{book.Quantity}}</td>
<td>{{book.Price}}</td>
<td>{{book.Total}}</td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
Model.py
from django.db import models
from django.db.models import F
from django.contrib.auth.models import User
class Book(models.Model):
title=models.CharField(max_length=300, null=True)
Author=models.CharField(max_length=300, null=True)
Edition=models.IntegerField()
Price=models.IntegerField()
Stock=models.IntegerField()
Quantity=models.IntegerField()
Total=models.IntegerField()
def decrementStock(self):
self.Quantity += 1
self.update(Stock=F('Stock') - F('Quantity'))
self.save()
def Tprice(self):
self.update(Total=F('Price') * F('Quantity'))
self.save()
def _str_(self):
return str(self.title)
class Customer(models.Model):
user=models.OneToOneField(User, null=True, on_delete=models.CASCADE)
name=models.CharField(max_length=200, null=True)
phone=models.CharField(max_length=200, null=True)
email=models.CharField(max_length=200, null=True)
date_created=models.DateTimeField(auto_now_add=True, null=True)
def _str_ (self):
return str(self.name)
class Cart(models.Model):
customer=models.OneToOneField(Customer, null=True, on_delete=models.CASCADE)
books=models.ManyToManyField(Book)
def _str_ (self):
return str(self.customer)
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from django.contrib.auth import login,logout,authenticate
from .forms import *
def home(request):
books=Book.objects.all()
context={'books':books}
if request.user.is_staff:
return render(request, 'book/adminhome.html', context)
else:
return render(request, 'book/home.html', context)
def logoutPage(request):
logout(request)
return redirect('/')
def loginPage(request):
if request.user.is_authenticated:
return redirect('home')
else:
if request.method=="POST":
username=request.POST.get('username')
password=request.POST.get('password')
user=authenticate(request,username=username, password=password)
if user is not None:
print("working")
login(request,user)
return redirect('/')
context ={}
return render(request,'book/login.html',context)
def registerPage(request):
if request.user.is_authenticated:
return redirect('home')
else:
form=createuserform()
cust_form=createcustomerform()
if request.method=='POST':
form=createuserform(request.POST)
cust_form=createcustomerform(request.POST)
if form.is_valid() and cust_form.is_valid:
user=form.save()
customer=cust_form.save(commit=False)
customer.user=user
customer.save()
return redirect('login')
context={
'form':form,
'cust_form':cust_form
}
return render(request,'book/register.html', context)
def addbook(request):
form=createbookform()
if request.method=='POST':
form=createbookform(request.POST)
if form.is_valid():
form.save()
return redirect('/')
context={'form':form}
return render(request,'book.addbook.html', context)
def viewcart(request):
cust=Customer.objects.filter(user=request.user)
for c in cust:
carts=Cart.objects.all()
for cart in carts:
if(cart.customer==c):
context={
'cart':cart
}
return render(request, 'book/viewcart.html', context)
else:
return render(request,'book/emptycart.html')
def addtocart(request,pk):
book=Book.objects.get(id=pk)
Book.objects.get(Quantity=pk).decrementStock()
cust=Customer.objects.filter(user=request.user)
for c in cust:
carts=Cart.objects.all()
reqcart=''
for cart in carts:
if(cart.customer==c):
reqcart=cart
break
if(reqcart==''):
reqcart=Cart.objects.create(
customer=c,
)
reqcart.books.add(book)
return redirect('/')
in model.py and views.py are wrong but i dont know to fix it
sorry for my bad english writing and i thank you for poeple to helped me.
I try by editing model.py by using this but its failed and get these error
`
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/addtocart/1
Django Version: 3.2
Python Version: 3.10.7
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'book']
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:\coding python\MHB\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\coding python\MHB\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\coding python\MHB\Scripts\bookstore\book\views.py", line 80, in addtocart
Book.objects.get(Quantity=pk).decrementStock()
File "C:\coding python\MHB\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\coding python\MHB\lib\site-packages\django\db\models\query.py", line 435, in get
raise self.model.DoesNotExist(
Exception Type: DoesNotExist at /addtocart/1
Exception Value: Book matching query does not exist.
`

In Synfony how do I divide a list according to the statut of his creator ? Error : Key for array with keys "0" does not exist

I'd like to display two lists of events : one list with events created by organizers with organizer status and a list with events created by organizers with member status. My conditions are like this : "if some event exist" and "if the organizer who created the event is an organizer (or a regular member)". For information, "organizer" and "member" depend on the status of the organizer. Because of the second condition, I had this error :
Key "organizer" for array with keys "0" does not exist.
I don't understand why... What needs to be corrected ?
Thank you very much for your help.
My twig file :
{% extends 'base.html.twig' %}
{% block title %}Liste des activités{% endblock %}
{% block main %}
<div class="events">
<div class="vr fixed-top start-50"></div>
<div class="row">
<div class="col-12 col-md-6">
<h2 class="text-center my-4">
<img src="{{ asset('img/titres/zpeak-sorties.svg') }}" alt="Les Zpeak Sorties !">
</h2>
<ul class="list-group">
{% if events and events.organizer.status == 'organizer' %}
{% for event in events %}
<a class="list-group-item list-group-item-action">
<img src="{{ asset('img/flag_images/' ~ event.spokenlanguage.image) }}" alt="Drapeau {{ event.spokenlanguage.name }}" class="me-2"> {{ event.title }}
</a>
{% endfor %}
{% else %}
<p>Il n'y a pas de zpeak sortie organisée.</p>
{% endif %}
</ul>
</div>
<div class="col-12 col-md-6">
<h2 class="text-center my-4">
<img src="{{ asset('img/titres/zpeak-idees.svg') }}" alt="Les Zpeak Idées !">
</h2>
<ul class="list-group">
{% if events and events.organizer.status == 'member' %}
{% for event in events %}
<a class="list-group-item list-group-item-action">
<img src="{{ asset('img/flag_images/' ~ event.spokenlanguage.image) }}" alt="Drapeau {{ event.spokenlanguage.name }}" class="me-2"> {{ event.title }}
</a>
{% endfor %}
{% else %}
<p>Il n'y a pas de zpeak idée proposée.</p>
{% endif %}
</ul>
</div>
</div>
</div>
{% endblock %}
My EventsController.php file :
<?php
namespace App\Controller\Front;
use App\Form\SearchType;
use App\Repository\EventsRepository;
use App\Repository\CategoriesRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class EventsController extends AbstractController
{
#[Route('/search', name: 'search')]
public function search(Request $request, SessionInterface $sessionInterface)
{
$data = $request->request->all();
$sessionSearchFormData = $sessionInterface->get('searchFormData');
$form = $this->createForm(SearchType::class, ['data' => $sessionSearchFormData]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$sessionInterface->set('searchFormData', $data);
return $this->redirectToRoute('events', [$data]);
}
return $this->renderForm('front/search.html.twig', [
'form' => $form
]);
}
#[Route('/events', name: 'events')]
public function events(
EventsRepository $eventsRepository,
CategoriesRepository $categoriesRepository
){
$events = $eventsRepository->findAll();
dd($events);
$categories = $categoriesRepository->findAll();
return $this->render("front/events.html.twig", ['events' => $events, 'categories' => $categories]);
}
}
dd($events) in EventsController.php :
EventsController.php on line 45:
array:1 [▼
0 => App\Entity\Events {#1026 ▼
-id: 1
-title: "Soirée à Belleville"
-description: "Viens boire un verre, rencontrer des natifs et pratiquer l'espagnol !"
-category: Proxies\__CG__\App\Entity\Categories {#933 ▶}
-spokenlanguage: Proxies\__CG__\App\Entity\Language {#981 ▶}
-address: Proxies\__CG__\App\Entity\Location {#744 ▶}
-date: DateTime #1665446400 {#1022 ▶}
-starttime: DateTime #72000 {#1023 ▶}
-endtime: DateTime #86340 {#1024 ▶}
-organizer: Proxies\__CG__\App\Entity\User {#996 ▼
-id: 1
-email: null
-roles: []
-password: null
-gender: null
-lastname: null
-firstname: null
-birthdate: null
-occupation: null
-photo: null
-status: null
-nationality: null
-nativelanguage: null
+__isInitialized__: false
…2
}
-participations: Doctrine\ORM\PersistentCollection {#1002 ▶}
}
]
In your case, you can have many Events, so in your twig, you need to use a for loop.
Place your for loop before the if.
Something like this :
<ul class="list-group">
{% for event in events %}
{% if event and event.organizer.status == 'organizer' %}
<a class="list-group-item list-group-item-action">
<img src="{{ asset('img/flag_images/' ~ event.spokenlanguage.image) }}" alt="Drapeau {{ event.spokenlanguage.name }}" class="me-2"> {{ event.title }}
</a>
{% else %}
<p>Il n'y a pas de zpeak sortie organisée.</p>
{% endif %}
{% endfor %}
</ul>
In case you are sure to have only one item, you can use events[0].organizer.status == 'organizer'
Regards,

CKAN - adding custom fields with ckenxt-scheming

i'm working with ckanext-scheming and trying to add a custom field similar to repeating subfields with few modifications (below are few files that define the field and it's behavior), for the most part it works correct but it doesn't get submitted to the database (although once i intercept the package create action, i can see the field data is there), any ideas are welcomed:
the scheming yaml part:
- field_name: tag_string
label: Tags
form_snippet: custom_tags.html
display_snippet: modified_repeating_subfields.html
help_text: >-
Additional keywords useful for ...
the form snippet:
{% import 'macros/form.html' as form %}
{% asset 'ckanext-dalrrdemcdcpr/facets-active-js' %}
{%
set options=[
{'value': '001', 'text': _('Discipline')}
, {'value': '002', 'text': _('Place')}
, {'value': '003', 'text': _('Stratum')}
, {'value': "004", "text":_("Temporal")}
, {'value': "005", "text":_("Theme")}
]
%}
{%- set extra_html = caller() if caller -%}
{% set classes = (classes|list) %}
{% call form.input_block(field.field_name, field.label, "", classes, extra_html=extra_html, is_required=false) %}
<div class="repeating_custom_tag_row-index-0" id="repeating_custom_tag_row-index-0" data-module="repeating_tags_handler">
<div class="metadata_tags_holder">
<div class="metadata_tags_styler">
<div class="metadata_tags_input">
<label for="custom_delete" class="input-group-text">{{ _('Input tag') }}</label>
<input class="form-control" id="repeating_custom_tag_row-index0-tag-input-index-0" type="text" name="repeating_custom_tag_row-index0-tag-input-index-0" value="" placeholder=""/>
</div>
<div class="metadata_tags_type_select">
<div><label for="tag_select" class="input-group-text">{{_('Input tag type')}}</label></div>
<select id="tag_select" name="repeating_custom_tag_row-index0-select-input-index-0" required>
{% for option in options %}
<option value="{{ option.value }}"{% if option.value == selected %} selected{% endif %}>{{ option.text or option.value }}</option>
{% endfor %}
</select>
</div>
<div class="tags_buttons_wrapper">
<div class="tags_handling_buttons">
<button class="btn btn-success add_metadata_tags_btn">Add</button>
<button class="btn btn-danger remove_metadata_tags_btn"><i class="fa fa-trash"></i>Remove</button>
</div>
</div>
</div>
</div>
</div>
{% endcall %}
the display snippet (don't think it's useful):
{% set fields = data[field.field_name] %}
{% block subfield_display %}
{% for field_data in fields %}
<div class="panel panel-default">
<div class="panel-body">
<dl class="scheming-subfield-list">
{% for subfield in field.repeating_subfields %}
<dt class="dataset-label">
{{ h.scheming_language_text(subfield.label) }}
</dt>
<dd>
{%- snippet 'scheming/snippets/display_field.html',
field=subfield,
data=field_data,
entity_type=entity_type,
object_type=object_type
-%}
</dd>
{% endfor %}
</dl>
</div>
</div>
{% endfor %}
{% endblock %}
this is how the relevant part of the form looks (the tags):
the js module controlling tags fields behavior:
ckan.module("repeating_tags_handler", function ($){
/*
control muliple interaction regarding the tags
section, handles both css and buttons behavior.
*/
return {
initialize: function(){
$.proxyAll(this,/_on/);
// set the styles before copying the section
let add_btns = $(".add_metadata_tags_btn")
add_btns.each((idx,add_btn) => {add_btn.style.marginRight="2px"})
$(document).on('click','.add_metadata_tags_btn',this._on_add_tags)
$(document).on('click','.remove_metadata_tags_btn',this._on_remove_tags)
let repeating_fields_wrapper = $(".repeating_custom_tag_row-index-0")
repeating_fields_wrapper.css({"margin-bottom":"30px"})
let tags_holder = $(".metadata_tags_holder")
tags_holder.css("width:100%")
$(".metadata_tags_styler").css({"width":"100%", "display": 'flex', 'flex-direction': 'row'})
$(".metadata_tags_input").css({"width":"40%"})
$(".metadata_tags_type_select").css({"width":"30%"})//tag_select
$("#tag_select").css({"width":"100%", "height":"34px", "margin-left":"4px"})
$(".tags_buttons_wrapper").css({"margin-left": "4px", "padding-top": "2px"})
$(".tags_handling_buttons").css({"width":"100%","padding-top":"22px", "display": "flex", "flex-direction": "row", "margin-left":"4px"})
this.section_html = tags_holder.html()
const config = { attributes: true, childList: true, subtree: true };
//const added_items_observer = new MutationObserver(this.added_items_mutation_observer);
//added_items_observer.observe(repeating_fields_wrapper.get(0), config)
},
_on_add_tags:function(e){
e.preventDefault()
//let search_parent = e.target.parentElement.parentElement.parentElement.parentElement
let search_parent = e.target.closest(".metadata_tags_styler")
let new_index = Array.from(search_parent.parentNode.children).indexOf(search_parent) +1
let new_index_text = `index-${new_index}`
this.section_html = this.section_html.replace(/index-[0-9]/g, new_index_text)
this.el.append(this.section_html)
},
_on_remove_tags:function(e){
e.preventDefault()
let removed_tag_row = e.target.closest(".metadata_tags_styler")
//let removed_tag_row = e.target.parentElement.parentElement.parentElement.parentElement
removed_tag_row.remove()
},
}
})
and finally this is a Runtime error screenshot i raised for you - dear - to see the tags data is there:
thank you!

model attribute in a template

I want to add attribute I add to my model from a model linked to another
this is my models:
class valuation(models.Model):
stock = models.ForeignKey("stock",on_delete=models.CASCADE,related_name='valuation',)
date = models.DateField(auto_now_add=True)
val_type = models.CharField(choices=TYPE, max_length=1,default='R')
user = models.ForeignKey("users.User", on_delete=models.CASCADE)
decision = models.BooleanField(verbose_name="clicked if u invest?", default=False)
def __str__(self):
return f"{self.stock} - {self.date} - {self.val_type}"
evolQuote = (
(1, 'High'),
(0, 'Undetermine'),
(-1, 'Low'))
class val_detail_Swing(models.Model):
valuation = models.OneToOneField(valuation, on_delete=models.CASCADE)
cycleMarket = models.IntegerField(choices=evolQuote, null=False, blank=False,default=0)
news = models.IntegerField(choices=evolQuote,null=False, blank=False,default=0)
managementPostion = models.IntegerField(choices=evolQuote,null=False, blank=False,default=0)
short =models.IntegerField(choices=evolQuote,null=False, blank=False,default=0)
BARCHART_analysts = models.IntegerField(choices=evolQuote, blank=True, verbose_name= "What BARCHAT says? ",default=0)
TRADINGVIEW_analysts = models.IntegerField(choices=evolQuote, blank=True, verbose_name= "What TRADINGVIEW says? ",default=0)
INVESTING_analysts = models.IntegerField(choices=evolQuote, blank=True,verbose_name= "What INVESTING says? ",default=0)
parabolics = models.IntegerField(choices=evolQuote,null=False, blank=False,default=0)
trix = models.IntegerField(choices=evolQuote,null=False, blank=False,default=0)
arron = models.IntegerField(choices=evolQuote,null=False, blank=False,default=0)
macd = models.IntegerField(choices=evolQuote,null=False, blank=False,default=0)
def rates(self):
marketRate = self.cycleMarket + self.news + self.managementPostion + self.short
analystRate = self.BARCHART_analysts + self. TRADINGVIEW_analysts + self.INVESTING_analysts
indicatorRate = self.parabolics + self.arron + self.macd
return marketRate, indicatorRate,analystRate
on my val_detail_swing model I add rates:
My view is :
class valuationDetailview(DetailView):
template_name = "evaluation/evaluation_detail.html"
queryset = valuation.objects.all()
context_object_name = "valuation"
and my template begins with that :
div id="accordion">
<div class="card">
<div class="card-header" id="headingOne">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne">
<div class="row">
<div class="col">Market trend</div>
<div class="center"><input class="speech-bubble" value="{{ valuation.val_detail_swing.rates.marketRate }}" id="marklRate" name="markRate"></div>
</div>
</button>
</h5>
</div>
the {{ valuation.val_detail_swing.rates.marketRate }} stays empty. I want in my detail view that It shows a value which is the sum of modelchoice values of my val_detail_Swing instance
Your return from rates doesn't specify the marketRate as a named thing. Use a named tuple or {{ valuation.val_detail_swing.rates.0 }} (zero being the first position).
If you show just {{ valuation.val_detail_swing.rates }} I think you'll see it as a tuple without names, just positions.

Model data not showing on template when iterating over queryset

So when building a simple Django website I found that for some reason I can't iterate over a queryset of a model I made and display the data in the template that I'm trying to create.
I have changed the keys of the dictionary being passed into the views and I have saved data on the model's database and changed around the template's format.
The database has values I checked using the Python Shell.
This is the template code:
<div class="container-fluid mt-3" >
<h2 class="display-4"><center>Upcoming Events:</center></h2>
{ % for post in Posts % }
<div class="row mt-3 ">
<div class="col-sm-1">
</div>
<div class="col-md">
<h4> { { post.title } } </h4>
<p class="lead">
{ { post.text } }
</p>
</div>
<div class="col-md">
<img class="img-fluid mx-auto" src="static_files/pictures/logo_main.png">
</div>
<div class="col-sm-1">
</div>
</div>
{ % endfor % }
This is the views code that is interacting with the template:
def home_view(request, *args, **kwargs):
Posts_ = Posts.objects.all()
context = {
'Posts':Posts_
}
return render(request, "home.html", context)
This is the model of interest:
class Posts(models.Model):
title = models.CharField(max_length=140)
text = models.TextField(blank=True, null=True)
date_posted = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
You have put extra space between the curly braces, that is wrong syntax. You need to change:
{ { post.title } } to {{ post.title }}
{ { post.text } } to {{ post.text }}

Resources