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.
Related
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>
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 }}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am very new to the technologies and learning angular js by developing a quiz app using angularJS. I want to mix the questions of Multiple choice questions and fill in the blank questions. I have created multiple choice questions but I am not able to create fill in the blank questions. could someone please give some suggestions, how to create fill in the blank questions.
for example: how ---you?, what --- you doing?. these kinds of questions.
here is my code:
questions.html
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="questionsController" ng-init="StartTimer()">
<div id="test_status" style="text-align:left">
<h3 ng-show='ques'>Question {{pos+1}} of {{questions.length}}</h3>
<h3 ng-hide='ques'>Test Completed </h3>
</div>
<ol style="list-style-type:none">
<li id="test" colspan="3">
<div ng-show="ques">
<h3>{{question}}</h3>
<input type='radio' name='choices' value='A'>{{chA}}
<br>
<input type='radio' name='choices' value='B'>{{chB}}
<br>
<input type='radio' name='choices' value='C'>{{chC}}
<br>
<br>
<button ng-click='checkAnswer()'>Next</button>
</div>
</li>
</ol>
<div ng-hide='ques'>
<div class="col-lg-5">
<div class="panel panel-danger">
<div class="panel-heading">Score Card</div>
<div class="panel-body">
<h3>You have got {{correct}} correct of {{questions.length}} questions</h3>
<h4>Exam Finished in Time :{{minuteleft}} Minutes {{sec}} Seconds</h4>
<div ng-controller="resultController">
<button ng-click='click()' class="btn btn-success">Continue</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-2">
<div class="panel panel-primary">
<div class="panel-heading">Time Limit</div>
<div class="panel-body">
<h2>{{min}}:{{sec}}</h2>
</div>
</div>
</div>
<br>
</div>
</body>
and main.js
var myApp = angular.module('myApp',['ngRoute']);
myApp.controller('questionsController', function($scope,$interval,$filter,$http) {
$scope.pos = 0, $scope.correct = 0, $scope.ques = true;
$scope.questions = [
["Which of the following a is not a keyword in Java ?", "class", "interface", "extends", "C"],
["Which of the following is an interface ?", "Thread", "Date", "Calender", "A"],
["Which company released Java Version 8 ?", "Sun", "Oracle", "Adobe", "A"],
["What is the length of Java datatype int ?", "32 bit", "16 bit", "None", "C"],
["What is the default value of Java datatype boolean?", "true", "false", "0", "A"]
];
$scope.totalsecoriginal = $scope.totalsec = 60;
$scope.totalsec--;
$scope.min = parseInt($scope.totalsec / 60, 10);
$scope.sec = $scope.totalsec - ($scope.min * 60);
$scope.date = new Date();
$scope.hhmmss = $filter('date')(new Date(), 'hh:mm:ss a');
$scope.currentTime = new Date();
$scope.currentTime.setSeconds($scope.currentTime.getSeconds() + 60);
function _(x) {
console.log(angular.element(document.getElementById(x)));
return angular.element(document.getElementById(x))[0];
}
$scope.interval = $interval(function() {
if ($scope.sec === 0) {
$scope.min--;
$scope.sec = 60;
}
$scope.sec--;
}, 1000);
$scope.$watch('sec', function() {
if ($scope.min === 0 && $scope.sec === 0) {
$interval.cancel($scope.interval);
window.alert('Time Up!!!');
$scope.pos = $scope.questions.length;
$scope.temp = true;
$scope.renderQuestion();
}
})
$scope.renderQuestion = function() {
if ($scope.pos >= $scope.questions.length) {
$scope.ques = false;
if (!$scope.temp) { $scope.temp = false;
$interval.cancel($scope.interval);
}
$scope.showscore = Math.round($scope.correct / $scope.questions.length * 100);
$scope.minuteleft = parseInt(($scope.totalsecoriginal - $scope.totalsec) / 60, 10);
$scope.pos = 0;
return false;
}
$scope.question = $scope.questions[$scope.pos][0];
$scope.chA = $scope.questions[$scope.pos][1];
$scope.chB = $scope.questions[$scope.pos][2];
$scope.chC = $scope.questions[$scope.pos][3];
}
$scope.checkAnswer = function() {
$scope.choices = angular.element(document.getElementsByName('choices'));
$scope.choice = -1;
for (var i = 0; i < $scope.choices.length; i++) {
if ($scope.choices[i].checked) {
$scope.choice = $scope.choices[i].value;
$scope.choices[i].checked = false;
}
}
if ($scope.choice == $scope.questions[$scope.pos][4]) {
$scope.correct++;
}
$scope.pos++;
$scope.renderQuestion();
};
$scope.renderQuestion();
});
Thanks in advance.
I'm trying to show the thumbnailPhoto property of an ActiveDirectory user on an MVC View.
I'm parsing the needed properties to a List of a class named Employee:
for (int counter = 0; counter < resultCol.Count; counter++)
{
result = resultCol[counter];
if (result.Properties.Contains("samaccountname") &&
result.Properties.Contains("displayname") &&
result.Properties.Contains("sn") &&
result.Properties.Contains("givenName"))
{
list.Add(new Employee
{
Email = (String)result.Properties["samaccountname"][0],
FirstName = (String)result.Properties["givenName"][0],
LastName = (String)result.Properties["sn"][0],
pictureBLOB = result.Properties.Contains("thumbnailPhoto") ? (byte[])result.Properties["thumbnailPhoto"][0] : null,
});
}
}
I did some research on how to display the picture on the Index View and found this as a possible solution:
<div class="container">
#foreach (var item in Model)
{
String imgSrc = String.Empty;
String base64 = String.Empty;
if (item.pictureBLOB != null)
{
base64 = Convert.ToBase64String(item.pictureBLOB);
imgSrc = String.Format("data:image;base64,{0}", base64);
}
<div id="#Html.DisplayFor(i => item.Number)" class="col col-lg-2 col-md-4 col-sm-6">
<a class="post" mailto="#item.Email" href="#">
<img src="{#imgSrc}" title="#Html.DisplayFor(i => item.LastName), #Html.DisplayFor(i => item.FirstName)" />
#*onerror="this.src = '../../Content/Images/nopicture.gif';" />*#
</a>
</div>
}
</div>
But when I call the index page, the pictures won't be shown. Is there any other possibility to show the profile pictures?
Finally I found the solution. I simply had to remove the braces around #imgSrc in
<img src="{#imgSrc}" title="#Html.DisplayFor(i => item.LastName), #Html.DisplayFor(i => item.FirstName)" />
I am trying to show list of questions and their choices by nested ng-repeat, I have seen plenty of similar questions but still could not fix my issue. My issue here is I could see the list of questions but the choices are not getting displayed and in the developer tools I could only see the commented ng-repeat line in place of choices.
Here is my View
<div ng-repeat ="question in questions track by $index" class="panel panel-default" ng-show="showQuestions">
<div class="panel-heading">
<div class="panel-title">
<a href="div#{{$index}}" class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" >
{{question.QuestionTxt}}
</a>
<div class="row height"></div>
<div class="row" ng-show="question.QuestionTypeTxt == 'RadioButton'">
<div class="col-xs-3" ng-repeat ="answer in questions.QuestionAnswers track by $index">
<input type="radio" ng-model="selectedChoice.choice" ng-value="{{answer.AnswerTxt}}" name="{{question.QuestionTxt}}"/>{{answer.AnswerTxt}}
</div>
</div>
<div class="row" ng-show="question.QuestionTypeTxt == 'Checkbox'">
<div class="col-xs-3" ng-repeat ="answer in questions.QuestionAnswers track by $index">
<input type="checkbox" ng-model="selectedChoice.choice" ng-value="{{answer.AnswerTxt}}" name="{{question.QuestionTxt}}"/>{{answer.AnswerTxt}}
</div>
</div>
</div>
</div>
</div>
Here is my Controller
$scope.questions = [];
$scope.selectedChoice = { choice:"" };
$scope.addQuestions = function () {
$scope.showQuestions = true;
rmat3Service.getQuestionsForSection().then(function (data) {
angular.forEach(data,function(a) {
$scope.questions.push(a);
});
});
}
This is my Json data:
var questions = new List<Question>();
var answers = new List<QuestionAnswer>();
answers.Add(new QuestionAnswer()
{
AnswerTxt = "Yes",
});
answers.Add(new QuestionAnswer()
{
AnswerTxt = "No"
});
answers.Add(new QuestionAnswer()
{
AnswerTxt = "Yes Verified"
});
answers.Add(new QuestionAnswer()
{
AnswerTxt = "Not Applicable"
});
questions.Add(new Question()
{
QuestionId = 1,
QuestionTxt = "Are aisles clear of product on the floor?",
QuestionTypeTxt = "RadioButton",
QuestionAnswers = answers
});
questions.Add(new Question()
{
QuestionId = 2,
QuestionTxt = "Automated Car Wash",
QuestionTypeTxt = "Checkbox",
QuestionAnswers = answers
});
return Json(questions, JsonRequestBehavior.AllowGet);
The issue is that you're attempting to loop questions.QuestionAnswers which doesn't exist. It should be question.QuestionAnswers:
<div class="col-xs-3" ng-repeat ="answer in question.QuestionAnswers track by $index">