Reverse lookup on template page not working - django

I have a contact and an event model where the event model has a foreign key to contact. The first half of my html obviously works, but for some reason when I display the list of other events that the contact has done, I can't get the list to show up. Is it because I'm calling {{event.whatever}} twice on the same page but in two differrent context?
views.py
class EventDetail(DetailView):
template_name = 'crm/eventdetail.html'
model = Event
models.py
class Contact(models.Model):
firstname = models.CharField(max_length=20, null=True, blank=True)
lastname = models.CharField(max_length=20, null=True, blank=True)
email = models.CharField(max_length=40, null=True, blank=True)
phone = models.CharField(max_length=15, null=True, blank=True)
title = models.CharField(max_length=20, null=True, blank=True)
notes = models.CharField(max_length=400, null=True, blank=True)
company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ["lastname"]
def __str__(self):
return self.firstname
class Event(models.Model):
event_type = models.CharField(max_length=20, choices = event_types)
contact = models.ForeignKey(Contact, on_delete=models.CASCADE)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
should_follow_up = models.BooleanField(default=False)
date = models.DateField()
notes = models.CharField(max_length=400)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def get_absolute_url(self):
return reverse('events_detail', kwargs={'pk': self.pk})
eventdetail.html
<div id="container">
<h1> Event: {{event.event_type}} </h1>
<ul>
<li>Event Contact: {{event.contact}}</li>
<li>Created By: {{event.created_by}}</li>
<li>Date: {{event.date}}</li>
<li>Note: {{event.notes}}</li>
</ul>
<h1>Events for {{event.contact}}</h1>
<table class="table">
<tr>
<th scope="col">Event Type</th>
<th scope="col">Date</th>
<th scope="col">3</th>
</tr>
{% for event in contact.event_set.all %}
<tr>
<td> {{event.event_type}}</td>
<td> {{event.date}}</td>
<td> </td>
</tr>
{% endfor %}
</table>
<p>This event was inputted on {{event.created}} and last edited on {{event.updated}}</p>
</div>
The for loop which is supposed to display all the other events the contact has done is not showing up. Any help is appreciated

Changes my view
class EventDetail(DetailView):
def get(self, request, *args, **kwargs):
event = get_object_or_404(Event, pk=kwargs['pk'])
events = event.contact.eventss.all()
context = {'event': event, 'events':events}
return render(request, 'crm/eventdetail.html', context)
Added a related_name to my model
contact = models.ForeignKey(Contact, related_name='eventss', on_delete=models.CASCADE)
Here is the html file that finally worked
{% for events in event.contact.eventss.all %}
<tr>
<td>{{events.event_type}}</td>
<td>{{events.date}}</td>
<td> </td>
</tr>
{% endfor %}

Related

Multiply Django field values to get a total

I have the following models:
class Supplier(models.Model):
name = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
class Meta:
ordering = ('name',)
def __str__(self):
return self.name
class Order(models.Model):
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.supplier.name
#property
def total(self):
orderitems = self.product_set.all()
total = sum([item.get_total for item in products])
return total
class Product(models.Model):
description = models.CharField(max_length=30)
costprice = models.FloatField(null=True, max_length=99, blank=True)
retailprice = models.FloatField(null=True, max_length=99, blank=True)
barcode = models.CharField(
null=True, max_length=99, unique=True, blank=True)
supplier = models.ForeignKey(
Supplier, on_delete=models.CASCADE, default=5)
on_order = models.ForeignKey(
Order, on_delete=models.CASCADE, null=True, blank=True)
on_order_quantity = models.FloatField(null=True, blank=True)
class Meta:
ordering = ('description',)
def __str__(self):
return self.description
i've created an order object for a given supplier with two products, with different quantities and cost prices.
How do I multiply cost x qty and add up those values in order to reach a total order value?
this is my view
def PurchaseOrder(request, pk_order):
orders = Order.objects.get(id=pk_order)
products = Product.objects.filter(
on_order_id=pk_order).prefetch_related('on_order')
total_products = products.count()
supplier = Product.objects.filter(
on_order_id=pk_order).prefetch_related('on_order')
total_value = Product.objects.filter(
on_order_id=pk_order).aggregate(Sum('costprice'))
context = {
'supplier': supplier,
'products': products,
'orders': orders,
'total_products': total_products,
'total_value': total_value, }
return render(request, 'crmapp/purchase_order.html', context)
at the moment it returns this:
This is my html template
It looks like your post is mostly code; please add some more details.'
Well, I need to show my code
{% extends 'crmapp/base.html' %}
{% load static %}
{% block content %}
<div class='main-site>'>
<h4> Supplier: {{orders.supplier}}</h4>
<h5>Order Number: {{orders.id}}</h5>
<h5>Created on: {{orders.date_created | date:"d/m/Y"}}</h5>
<h6>Total Lines In Order: {{total_products}}</h6>
<button style='margin-bottom:10px' class='btn btn-primary' id="open-popup-1">Edit</button>
<button style='margin-bottom:10px' class='btn btn-success' href="" id="open-popup-1">Print/Export</button>
<input type="search" placeholder="Search any field..." class="form-control search-input" data-table="customers-list"/>
<table class="table table js-sort-table mt32 customers-list" id='myTable'>
<thead class="table" >
<tr>
<th class='header' onclick="sortTable(0)" scope="col">ID</th>
<th class='header' onclick="sortTable(1)" scope="col">Description</th>
<th class='header' onclick="sortTable(3)" scope="col">Order Quantity</th>
<th class='header' onclick="sortTable(2)" scope="col">Cost</th>
</tr>
</thead>
<tbody>
<tr>
{% for product in products %}
<td> {{product.id}}</td>
<td><h6><strong>{{product.description}}</strong></h6></td>
<td>{{product.on_order_quantity |floatformat:0}}</td>
<td>£{{product.costprice |floatformat:2}}</td>
</tr>
</tbody>
{% endfor %}
</table>
<div class='ordertotal'>
<h5>Order Value:</h5>
<h6><strong>{{total_value}}</strong></h6>
</div>
</div>
{% endblock %}
Use the property decorator for the costprice field in the Product Model?
class Product(models.Model):
# define other fields here
#property
def costprice(self):
"Returns retailprice * qty for each product."
return self.on_order_quantity * self.retailprice
Update:
There's clearly some misunderstanding. Therefore I'll try to provide more information.
First Question: "How do I multiply cost x qty"
The property decorator allows you to create fields, which behave like calculated read_only fields. (You don't need to initialize them)
#property
def cost_x_qty(self):
"Returns costprice multiplied by qty for each product."
return self.on_order_quantity * self.costprice
Second Question: "How do I add up those values in order to reach a total order value?"
You can use Aggregation to do this.
You can do the following in your view function:
def PurchaseOrder(request, pk_order):
# some code
grand_total = Product.objects.filter(
on_order_id=pk_order).aggregate(Sum('cost_x_qty'))
# add to context
context['grand_total'] = grand_total
return render(request, 'some_template.html', context)
you can use the grand_total in your template file like this:
{{grant_total}}
Hope that helps

Django model two step filter one is user and the other is custo

I am creating a project management app
Each user has multiple projects and each project has a set of data
When first logged in the user sees a list of all the projects only he created.i am able to do this.
Then when clicked on the project the data related only to that project is to be shown.
How do i do that in django?
My projects model
class projectsmodel(models.Model):
added_by = models.ForeignKey(settings.AUTH_USER_MODEL,null=True,blank=True,on_delete=models.SET_NULL)
projects=models.CharField(max_length=300)
def save_model(self,request,obj,form,change):
obj.added_by=request.User
super().save_model(request,obj,form,change)
def __str__(self):
return self.projects
My BOQ Model,it is the model that needs to be filtered based on project it is redirected from
class boqmodel(models.Model):
project_name = models.ForeignKey(projectsmodel, null=True, blank=True, on_delete=models.SET_NULL)
code = models.IntegerField()
building = models.ForeignKey(building, on_delete=models.SET_NULL, null=True)
level = models.ForeignKey(level, on_delete=models.SET_NULL, null=True)
activity = models.ForeignKey(activity, on_delete=models.SET_NULL, null=True)
subactivity = models.ForeignKey(sub_activity, on_delete=models.SET_NULL, null=True)
duration = models.IntegerField()
linkactivity = models.CharField(max_length=300, null=True, blank=True)
linktype = models.CharField(choices=choicestype, max_length=300, null=True, blank=True)
linkduration = models.IntegerField(default=0)
plannedstart = models.DateField(null=True, blank=True)
plannedfinish = models.DateField(null=True, blank=True)
actualstart = models.DateField(null=True, blank=True)
actualfinish = models.DateField(null=True, blank=True)
html page of projects
<tbody>
<tr>
<td style="vertical-align: top;">Projects<br>
</td>
<td>Open</td>
<td>Edit</td>
<td>Delete</td>
</tr>
{% for projectsmodel in projects1 %}
<tr>
<td>{{projectsmodel.projects}}</td>
<td><a href="{% url 'projecthome' %}"<button class="btn btn-warning">Open</button></td><a></button>
<td>Edit</button></button>
<td>Delete</button></button>
</td>
</tr>
{% endfor %}
<a class="btn btn-primary" href="createprojects/">Create Projects</a>
{% endblock %}
my views for project
#login_required
def projects(request):
projects1 = projectsmodel.objects.filter(added_by =request.user)
context = {'projects1': projects1}
return render(request, 'projectslist.html',context )
Ok what i have understood. You need a structure like this.
models.py
class Project(models.Model):
added_by = models.ForeignKey(settings.AUTH_USER_MODEL,null=True,blank=True,on_delete=models.CASCADE)
project_name = models.CharField(max_length=255)
code = models.IntegerField()
building = models.ForeignKey(building, on_delete=models.SET_NULL, null=True)
level = models.ForeignKey(level, on_delete=models.SET_NULL, null=True)
activity = models.ForeignKey(activity, on_delete=models.SET_NULL, null=True)
subactivity = models.ForeignKey(sub_activity, on_delete=models.SET_NULL, null=True)
duration = models.IntegerField()
linkactivity = models.CharField(max_length=300, null=True, blank=True)
linktype = models.CharField(choices=choicestype, max_length=300, null=True, blank=True)
linkduration = models.IntegerField(default=0)
plannedstart = models.DateField(null=True, blank=True)
plannedfinish = models.DateField(null=True, blank=True)
actualstart = models.DateField(null=True, blank=True)
actualfinish = models.DateField(null=True, blank=True)
urls.py
from yourapp.views import project_details
#Add this url to your url patterns
url(r'^project-details/(?P<projectId><pk>[0-9]+)/$',project_details,name='project_details')
views.py
from yourapp.models import Project
#login_required
def project_list(request):
user_projects = Project.objects.filter(added_by=request.user)
context = {'projects': user_projects}
return render(request, 'projectslist.html',context )
#login_required
def project_details(request,projectId):
context = {}
project_required = Project.objects.get(id=int(projectId))
context['project']= project_required
return render(request,"yourapp/projectDetails.html",context)
This is projectlist.html .You can add button to open project details. For the sake of simplicity i have not added any extra html element.
{% for project in projects %}
<tr>
<td> {{project.project_name}}</td>
</tr>
{% endfor %}
projectDetails.html
<p>Project Name : {{ project.project_name }} </p>
<p>Project Link Activity: {{ project.linkactivity }} </p>
<!-- and so on -->
P.S: where "yourapp" is the django app you have in your django project

Not getting the value in django template

models.py
class Stock(models.Model):
name = models.CharField(verbose_name='Name of Stock', max_length=300)
purchase_price = models.DecimalField(verbose_name='Purchase Price', blank=True, null=True, max_digits=30, decimal_places=2)
pre_price = models.DecimalField(verbose_name='Last Day Price', blank=True, null=True, max_digits=30, decimal_places=2)
current_price = models.DecimalField(verbose_name='Current Price', blank=True, null=True, max_digits=30, decimal_places=2)
def __str__(self):
return self.name
class StockList(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
stock = models.ForeignKey(Stock)
quantity = models.IntegerField(verbose_name='No.of Shares',default=0)
timestamp = models.DateTimeField(auto_now=True, auto_now_add=False)
def __str__(self):
return str(self.stock)
def market_value_reciever(sender, instance, *args, **kwargs):
purchase_price = instance.stock.purchase_price
quantity = instance.quantity
market_value = purchase_price * quantity
instance.market_value = market_value
print(purchase_price)
print(market_value)
pre_save.connect(market_value_reciever, sender=StockList)
html template
{% for item in queryset %}
<tr>
<td>
{{ item.stock.name }}
</td>
<td>
{{ item.purchase_price }}
</td>
<td>
{{ item.quantity }}
</td>
<td>
{{ item.market_value }}
</td>
</tr>
{% endfor %}
Here I am getting only the value of quantity on html template, purchase price and market value fields are not getting on templates but its values are getting on terminal. Anybody can help, Thank you so much.
You could use the #property decorator in StockList model, so the template can render it:
class StockList(models.Model):
#property
def purchase_price(self):
return self.stock.purchase_price
#property
def market_value(self):
return self.purchase_price * self.quantity

Cannot retrieve foreign key ID

I am building an application that allows a user to create a scenario, then create associated emails, t, calls and trades to the scenario.
There is a 1:many relationship with the scenario and the communications. The issue I am having is I want the user to be able to click the scenario, it then shows the filtered list of communications, each communication source is a tab. The way I am filtering the communication is based on the id of the foreign key on the object. However if there is no entry for the datasource I receive a "no reverse match" because I am using the scenario id from the first object and that doesnt exist if there is no communication for that scenario.
I am stumped on what the best way to do this, besides removing tabs which I like.
Please let me know if I am missing anything, I am relatively new to programming and very new to Django.
models.py
from __future__ import unicode_literals
from django.db import models
from django.core.urlresolvers import reverse
class Scenario(models.Model):
name = models.CharField(max_length=256, blank=False, null=False, unique=True)
description = models.TextField(max_length=1000)
def get_absolute_url(self):
return reverse('scenarios:detail', kwargs={'pk': self.pk})
def __unicode__(self):
return self.name
class Email(models.Model):
scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE )
recipient_email = models.EmailField()
sender_email = models.EmailField()
subject = models.CharField(blank=True, null=False, max_length=256)
body = models.TextField(blank=True, null=False, max_length=2048)
# timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
# updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def get_absolute_url(self):
return reverse('scenarios:email-index')
def __unicode__(self):
return self.sender_email + ' ' + self.recipient_email + ' ' + self.subject
class InstantMessage(models.Model):
NETWORKS = (
('Yahoo', 'Yahoo'),
('MSN', 'MSN'),
('Skype', 'Skype')
)
scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
description = models.CharField(max_length=256, null=False, blank=False)
network = models.CharField(max_length=50, null=False, blank=False, choices=NETWORKS)
room = models.CharField(max_length=100, null=False, blank=False)
starttime = models.TimeField(blank=False, null=False)
endtime = models.TimeField(blank=False, null=False)
participant1 = models.CharField(max_length=256, null=False, blank=False)
participant2 = models.CharField(max_length=256, null=False, blank=False)
chatcsv = models.FileField(upload_to='chatfiles')
def get_absolute_url(self):
return reverse('scenarios:im-index')
def __unicode__(self):
return "Network=" + self.network + " Description:" + self.description
class VoiceCall(models.Model):
DIRECTION = (
('outbound', 'Outbound'),
('inbound', 'Inbound')
)
scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
description = models.CharField(max_length=256, null=False, blank=False)
direction = models.CharField(choices=DIRECTION, null=False, blank=False, default="Outbound", max_length=15)
starttime = models.TimeField(blank=False, null=False)
endtime = models.TimeField(blank=False, null=False)
traderid = models.CharField(max_length=50,blank=False, null=False)
diallednumber = models.BigIntegerField(blank=True, null=True)
cli = models.BigIntegerField(blank=True, null=True)
nameofcaller = models.CharField(max_length=100, blank=True, null=True)
nameofline = models.CharField(max_length=100, blank=True, null=True)
wavfile = models.FileField(upload_to='voice')
transcript = models.FileField(blank=True, null=True, upload_to='voice')
bagofwords = models.FileField(blank=True, null=True, upload_to='voice')
def get_absolute_url(self):
return reverse('scenarios:call-index')
def __unicode__(self):
return self.description
class Trade(models.Model):
scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
tradeprefix = models.CharField(max_length=6, null=False, blank=False)
trader = models.CharField(max_length=256, null=False, blank=False)
sales = models.CharField(max_length=256, null=False, blank=False)
counterpartyid = models.CharField(max_length=256, null=False, blank=False)
counterpartyname = models.CharField(max_length=256, null=False, blank=False)
brokerid = models.CharField(max_length=256, null=False, blank=False)
brokername = models.CharField(max_length=256, null=False, blank=False)
isevent = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse('scenarios:trade-index')
# def __unicode__(self):
# return self.description
class Mobile(models.Model):
scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
displayname = models.CharField(max_length=100, null=False, blank=False)
email = models.EmailField()
tonumber = models.BigIntegerField(blank=True, null=True)
fromnumber = models.BigIntegerField(blank=True, null=True)
message = models.CharField(blank=True, null=False, max_length=1024)
def get_absolute_url(self):
return reverse('scenarios:mobile-index')
views.py
class IMScenarioList(generic.ListView):
model = InstantMessage
template_name = 'scenarios/im_filtered.html'
context_object_name = 'scenario_ims'
def get_queryset(self):
return InstantMessage.objects.filter(scenario=self.kwargs['pk'])
class CallScenario(generic.ListView):
model = VoiceCall
template_name = 'scenarios/call_filtered.html'
context_object_name = 'scenario_calls'
def get_queryset(self):
return VoiceCall.objects.filter(scenario=self.kwargs['pk'])
class MobileScenario(generic.ListView):
model = Mobile
template_name = 'scenarios/mobile_filtered.html'
context_object_name = 'scenario_mobiles'
def get_queryset(self):
return Mobile.objects.filter(scenario=self.kwargs['pk'])
class TradeScenario(generic.ListView):
model = Trade
template_name = 'scenarios/trades_filtered.html'
context_object_name = 'trades'
def get_queryset(self):
return Trade.objects.filter(scenario=self.kwargs['pk'])
urls.py
url(r'^(?P<pk>[0-9]+)/email/$', views.EmailScenarioList.as_view(), name='email-scenario'),
# Instant Messages
url(r'^im/$', views.IMList.as_view(), name='im-index'),
url(r'^im/add/$', views.IMCreate.as_view(), name='im-create'),
url(r'^im/(?P<pk>[0-9]+)/update/$', views.IMUpdate.as_view(), name='im-update'),
url(r'^im/(?P<pk>[0-9]+)/delete/$', views.IMDelete.as_view(), name='im-delete'),
url(r'^(?P<pk>[0-9]+)/im/$', views.IMScenarioList.as_view(), name='im-scenario'),
# Voice Calls
url(r'^calls/$', views.CallList.as_view(), name='call-index'),
url(r'calls/add/$', views.CallCreate.as_view(), name='call-create'),
url(r'^calls/(?P<pk>[0-9]+)/update/$', views.CallUpdate.as_view(), name='call-update'),
url(r'^calls/(?P<pk>[0-9]+)/delete/$', views.CallDelete.as_view(), name='call-delete'),
url(r'^(?P<pk>[0-9]+)/voice/$', views.CallScenario.as_view(), name='call-scenario'),
# trades
url(r'^trades/$', views.TradeList.as_view(), name='trade-index'),
url(r'^trades/add/$', views.TradeCreate.as_view(), name='trade-create'),
url(r'^trades/(?P<pk>[0-9]+)/update/$', views.TradeUpdate.as_view(), name='trade-update'),
url(r'^trades/(?P<pk>[0-9]+)/delete/$', views.TradeDelete.as_view(), name='trade-delete'),
url(r'^(?P<pk>[0-9]+)/trade/$', views.TradeScenario.as_view(), name='trade-scenario'),
# mobile
url(r'^mobile/$', views.MobileList.as_view(), name='mobile-index'),
url(r'^mobile/add/$', views.MobileCreate.as_view(), name='mobile-create'),
url(r'^mobile/(?P<pk>[0-9]+)/update/$', views.MobileUpdate.as_view(), name='mobile-update'),
url(r'^mobile/(?P<pk>[0-9]+)/delete/$', views.MobileDelete.as_view(), name='mobile-delete'),
url(r'^(?P<pk>[0-9]+)/mobile/$', views.MobileScenario.as_view(), name='mobile-scenario'),
Templates
trade_index.html
{% extends 'base.html' %}
{% block content %}
<div class="container">
<table id="myTable" class="tablesorter tablesorter-bootstrap">
<thead>
<tr>
<th class="first-name filter-select" data-placeholder="Select a Scenario">Scenario</th>
<th></th>
<th>Trade Prefix</th>
<th>Trader</th>
<th>Sales</th>
<th>Counterparty ID</th>
<th class="first-name filter-select" data-placeholder="Select Counterparty">Counterparty Name</th>
<th>Broker ID</th>
<th></th>
<th class="first-name filter-select" data-placeholder="Select Broker">Broker Name</th>
<th class="first-name filter-select" data-placeholder="IsEvent">IsEvent</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{% for trade in trades %}
<tr>
<td data-toggle="tooltip" title="Description: {{trade.scenario.description}}">{{trade.scenario}}</td>
<td></td>
<td>{{trade.tradeprefix}}</td>
<td>{{trade.trader}}</td>
<td>{{trade.sales}}</td>
<td>{{trade.counterpartyid}}</td>
<td>{{trade.counterpartyname}}</td>
<td>{{trade.brokerid}}</td>
<td></td>
<td>{{trade.brokername}}</td>
<td>{{trade.isevent}}</td>
<td>
<a href="{% url 'scenarios:trade-update' trade.id %}">
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-pencil" />
</button>
</a>
</td>
<td><form action="{% url 'scenarios:trade-delete' pk=trade.id %}" method="post">
{% csrf_token %}
<input type="hidden" name="call_id" value="{{ trade.id}}"/>
<button type="submit" class="btn btn-default btn-sm" onclick="return confirm('Are you sure you want to delete {{trade.description}}?')">
<span class="glyphicon glyphicon-trash" />
</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<a href="{% url 'scenarios:trade-create' %}">
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-plus" />
</button>
</a> Add Trade
<br>
<button type="button" class="btn btn-default btn-sm" value="Back" onClick="javascript:history.go(-1);">
<span class="glyphicon glyphicon-backward" />
</button>
</div>
{% endblock %}
trades_filtered.html
{% extends 'scenarios/trade_index.html' %}
{% block content %}
{% with trades|first as first_trade %}
<ul class="nav nav-pills">
<li class="active">trades</li>
<li>emails</li>
<li>instant messages</li>
<li>voice</li>
<li>mobile</li>
</ul>
{% endwith %}
{{ block.super }}
{% endblock %}
Right now in trades_filtered.html you take the ID of a given scenario and use that ID to manually construct your five URLs. If it were me, I'd use a custom model method to determine whether or not we need to generate a URL first.
class Scenario(models.Model):
name = models.CharField(max_length=256, blank=False, null=False, unique=True)
description = models.TextField(max_length=1000)
def generate_trade_url(self):
if self.trade_set.exists():
return reverse('scenarios:trade-scenario', kwargs={'pk':self.pk})
return None
def generate_email_url(self):
...
You would need one method like this for each URL you want to generate. You can this use this logic either in the view (preferable) or in your template (simpler but slower) to dynamically generate your URLs only when they are valid.
EDIT: I just looked at this answer a second time. I included null=False in the name field definition because it was in the original, but be aware that it doesn't actually do anything useful on a CharField. Django doesn't use null values for those fields, instead storing them as '' (empty string).

How do I get Image from parent model to the child model related with foreign key

I have design a parent model which works fine. Parent model:
class Person(models.Model):
name = models.CharField(max_length=128)
present_position=models.CharField(max_length=100)
organization= models.CharField(max_length=150,blank=True)
address = models.CharField(max_length=150, blank=True)
email = models.EmailField(max_length=70, blank=True, null=True, unique=True)
photo= ResizedImageField(size=[100, 100],crop=['middle', 'center'],upload_to='persons/%Y/%m/%d/',null=True,
blank=True,
editable=True,
help_text="Person Picture")
I have child model which produce executive committee members:
class ExecMember(models.Model):
name = models.ForeignKey(Person, on_delete=models.CASCADE )
committee_position = models.CharField(max_length=100)
rank = models.IntegerField(blank=True)
member_start_date = models.DateField(blank=True)
member_end_date = models.DateField(null=True, blank=True)
is_active = models.BooleanField(default=True)
From child model I want to produce Executive Committee members list containing their related photo from Person model.
So far I tried:
In template:
{% for execomember in object_list %}
<tr>
<td>{{forloop.counter}}.</td>
<td>{{execomember.name}}<br>
{{execomember.committee_position}}</td>
<td><a href="{% url 'member:person-list' %}">
<img src="{{ person.photo_url|default_if_none:'#'}}" class="img-responsive">
</a></td>
<td>
{{execomember.member_start_date }}<br>
{{execomember.member_end_date}}
</td>
<td>
{{execomember.is_active}}<br>
</td>
</tr>
{% endfor %}
In views:
class ExeCommListView(generic.ListView):
model = ExecMember
context_object_name = 'execomembers'
In urls:
url(r'^execomember/$', views.ExeCommListView.as_view(), name='execomember-list'),
But this gives all the fields values of child model correctly. Only photo not shown.
How do I get photo from parent model to ExecMember model?
Thanks.