I have bunch of urls in urls.py , and In template I have defined like below :
<li>Billing</li>
<li>Proforma Invoice</li>
<li>Quotation</li>
But the problem is if I click on one line say viewinvoices, and after that I click on proformainvoice, it redirects to
localhost:8000/vieweinvoices/proformainvoice.html but it should go to localhost:8000/proformainvoice.html how can I do that?
views.py :
def vieweinvoices(request):
alltaxInvoice = taxInvoice.objects.all()
totalInvoices = taxInvoice.objects.all().count()
startdate = datetime.today()
enddate = startdate - timedelta(days=14)
totalthismonthsInvoices = taxInvoice.objects.filter(
invoicedate__range=[startdate, enddate]
).count()
context = {
"alltaxInvoice": alltaxInvoice,
"totalInvoices": totalInvoices,
"totalthismonthsInvoices": totalthismonthsInvoices,
"startdate": startdate,
"enddate": enddate,
}
return render(request, "Invoice/TaxInvoice/viewinvoice.html", context)
all views are like this
and
urls.py
path("vieweinvoices/", views.vieweinvoices, name="vieweinvoices"),
path("viewequotations/", views.viewequotations, name="viewequotations"),
Related
I'm trying to render the Django template after uploading a file (POST method). The issue is: I insert some print() inside the POST request.method and everything is working fine (terminal VSCode) but the template (HTML) is not being displayed inside the render() function.
View.py:
def index(request):
if 'GET' == request.method:
print("It didn't work it!")
print(request.FILES['file'])
return render(request, 'auditoria_app/index.html')
else:
print('It worked it!')
excel_file = request.FILES["file"]
wb = openpyxl.load_workbook(excel_file, data_only=True)
wb.security.workbook_password = 'Rnip*2020'
inputsCombo = wb['Inputs COMBO']
inputsDNCombo = wb['Inputs DN COMBO']
outputCombo = wb['OutPut COMBO']
faixas = wb['Faixas']
wb2 = openpyxl.load_workbook('media/sigma.xlsx', data_only=True)
sigma = wb2['sigma']
sic = wb2['Performance']
# wb4 = openpyxl.load_workbook('media/ultimoContrato.xlsm', data_only=True)
# ultimoContrato = wb4['Base']
numeroIbms = inputsCombo['F5'].value
ibms = []
output = outputResults(numeroIbms, outputCombo)
for i in range(8, 8 + numeroIbms):
ibm = Ibm(i, inputsCombo, inputsDNCombo, outputCombo, faixas, sigma)
ibms.append(ibm)
print(ibm.numeroIbm)
# sigmaReport(sigma, ibm)
return render(request, 'auditoria_app/index.html',
{'ibms': ibms,
'numeroIbms': numeroIbms,
'output': output,
})
Message displayed on VSCode terminal:
It worked it!
Outside: SAE_R360_pagnussat.xlsm
1038108
1049885
[04/Sep/2021 21:18:36] "POST /auditoria/ HTTP/1.1" 200 5132
I am trying to return most voted answer for each question.also i want to send also extra infomation of that answer like vote and id.
Printing one value is easy but for more than one i have to return dictionary.So how can i return dictionary and print all values in template.
from django import template
register = template.Library()
#register.simple_tag
def getmostvotedanswer(answers):
answer = answers.order_by('-vote')[0]
answer_info = {
'answer':answer.answer,
'vote':answer.vote,
'id':answer.id
}
return answer_info
index.html
<p class="small text-muted ">{% getmostvotedanswer question.answer_set.all %}</p>
Output
{'answer': 'THIS IS ANSWER THIS IS ANSWER THIS IS ANSWER THIS IS ANSWER THIS IS ANSWER', 'vote': 7, 'id': 1}
I can call template_tag 3 times for three values.
But I don't want to call templatetag again and again i think it will affect performance.
view.py
def index(request):
questions = Question.objects.all()
context = {
'questions':questions
}
return render(request,'index.html',context=context)
Edit -> Add view.py
The easiest, debugable, best performance and test friendly way to achieve it is to cook data on view instead of write custom template tag. Windows functions are needed to get the first answer of each question:
from django.db.models import F, Window
from django.db.models.functions.window import FirstValue
def index(request):
#q_and_a_ids = [ (id question, id most voted answer), (... ]
q_and_a_ids = (
Question
.objects
.annotate(
most_voted_id=Window(
expression=FirstValue('answer__id'),
partition_by=['id'],
order_by=F('answer__vote').desc()
)
)
.distinct()
.values_list( 'id', 'most_voted_id')
)
answers_ids = set( [ a_id for (_,a_id) in q_and_a_ids] )
questions_dict = Question.objects.in_bulk()
answers_dict = Answers.objects.filter(pk__in=answers_ids).in_bulk()
#q_and_a = [ { 'q':question, 'a':most voted answer}, { ... ]
q_and_a = [ {'q': questions_dict[q_id],
'a': answers_dict.get(a_id) }
for (q_id,a_id) in q_and_a_ids ]
context = {
'questions_and_answers': q_and_a
}
return render(request,'index.html',context=context)
In tastypie, I want set json result name.
I have a class that I use for it but I can set name in.
enter cclass ContentResource(ModelResource):
class Meta:
results = ListField(attribute='results')
queryset = Content.objects.all()
resource_name = 'content'
max_limit = None
#filtering = {"title": "contains"}
def alter_list_data_to_serialize(self, request, data_dict):
if isinstance(data_dict, dict):
if 'meta' in data_dict:
# Get rid of the "meta".
del(data_dict['meta'])
# Rename the objects.
data_dict['Mobile'] = data_dict['objects']
del(data_dict['objects'])
return data_dict
ode here it returns this
{"Mobile":
[
{
"added": "2015-07-23T11:30:20.911835",
"content_cast": "",
"content_company": "HamrahCinema",
"content_description": "so nice",
"content_director": "",
"content_duration": "2:20",
"content_filelanguage": null,
}
]
}
when I use /content/api/content every thing is ok, but when I use /content/api/content/1,"mobile" is removed.
as educated guess, I would suggest using alter_detail_data_to_serialize
I'm trying to inline my stylesheets with the following code:
views.py
def index(request):
latest_course_list = Course.objects.order_by('-start_date')
template = loader.get_template('index.html')
style_sheets = ""
style_sheets = addStyle(style_sheets)
ctx = {
'latest_course_list': latest_course_list,
'style_sheets': style_sheets,
}
return render_to_response('index.html', ctx, context_instance=RequestContext(request))
def addStyle(style):
style_sheets=""
style_sheet_list = [
"bootstrap",
"custom-style",
"responsive",
"animate",
"flexslider",
"theme-style"
]
for sheet in style_sheet_list:
with open (DJANGO_ROOT + "/assets/css/" + sheet + ".css", "r") as myfile:
style_sheets+=myfile.read()
style_sheets+="\n"
return style_sheets
template:
<style type="text/css">{{ style_sheets }}</style>
But it only gets down to half way through the animate.css before cutting off and just adding "..."
What limit am I hitting here? How can I solve it?
I have a model in django admin as follows
ChoiceA= (
("on-false","on-false"),
("on-true","on-true"),
)
ChoiceB = (
("always","always"),
("never","never"),
)
id = models.CharField(verbose_name="Field",max_length=32)
type = models.CharField(verbose_name="Expression",max_length=32)
action = models.CharField(max_length=32, choices=x)
Now based on the type entered by the user ie if user enters type = "a" then action's choices should be set to ChoiceA and if user enters type ="b" then action's choices should be set to ChoiceB. How can I achieve this in Django Admin?
Edit:
action_change.js
jQuery(document).ready(function(){
$("#id_type").change( function(event) {
$.ajax({
"type" : "POST",
"url" : "/action_choices/",
"dataType" : "json",
"cache" : false,
"error" : alert("hello"),
"success" : function(json) {
$('#id_action >option').remove();
for(var j = 0; j < json.length; j++){
$('#id_action').append($('<option></option>').val(json[j][0]).html(json[j][1]));
}
}
});
});
});
You can achieve it using Ajax and jQuery:
models.py:
type = models.CharField(verbose_name="Expression",max_length=32)
action = models.CharField(max_length=32, choices = (('', ''), ))
admin.py:
class MyModelAdmin(admin.ModelAdmin):
list_display = ('type', )
class Media:
js = ['/static/js/action_change.js']
admin.site.register(MyModel, MyModelAdmin)
urls.py:
url(r'^action_choices/', 'myproject.myapp.views.action_choices'),
views.py:
def action_choices(request):
action_list = []
ChoiceA = ("on-false", "on-true")
ChoiceB = ("always", "never")
action_type = request.GET.get('action_type')
if str(action_type).lower() == 'a':
choices = ChoiceA
elif str(action_type).lower() == 'b':
choices = ChoiceB
else:
choices = ()
[action_list.append((each,each)) for each in choices]
json = simplejson.dumps(action_list)
return HttpResponse(json, mimetype='application/javascript')
Create the file action_change.js with following content in your static folder and define correct path in class Media of ModelAdmin.
action_change.js
(function($){
$(function(){
$(document).ready(function() {
$('#id_type').bind('keyup', type_change);
$('#id_action >option').show();
});
});
})(django.jQuery);
// based on the type, action will be loaded
var $ = django.jQuery.noConflict();
function type_change()
{
var action_type = $('#id_type').val();
$.ajax({
"type" : "GET",
"url" : "/action_choices/?action_type="+action_type,
"dataType" : "json",
"cache" : false,
"success" : function(json) {
$('#id_action >option').remove();
for(var j = 0; j < json.length; j++){
$('#id_action').append($('<option></option>').val(json[j][0]).html(json[j][1]));
}
}
})(jQuery);
}
This should work fine for the scenario you asked. And I'm giving my suggestion below:
models.py
type = models.CharField(verbose_name="Expression",max_length=32, choices = (('a', 'a'), ('b', 'b'), ))
action = models.CharField(max_length=32, choices = (('', ''), ))
action_change.js (line 5)
$('#id_type').bind('change', type_change);
You would have to initialize the action field with all possible choices, or Django will complain that a choice that didn't previously exist isn't a valid choice.
My recommendation would be to initialize the field with all of the possible choices, and use JavaScript to toggle the visibility of the choices, depending on the value of type. There are a few plugins around that will handle dynamic fields in Django admin, but most that I've seen deal with ForeignKey or ManyToMany fields that need to do lookups.
You're probably best off just adding some JavaScript to your admin form via the Media meta class and handling it yourself.