I am having a one to one relationship between 2 models. While creating the second model, I want to pass the instance of the first model to the second one.
These 2 models are new tabs/features in our web application. I tried passing the instance through URL but didn't succeed. Maybe I am not following steps correctly.
Details about:
python version: Python 3.6.4 :: Anaconda, Inc.
django version: 2.0.2-3
Please find below the code:
1) models.py
class StudyConcept(models.Model):
requestor_name = models.CharField(max_length=240, blank=False, null=False)
project = models.CharField(max_length=240, blank=False, null=False)
date_of_request = models.DateField(blank=False, null=False)
brief_summary = models.CharField(max_length=4000, blank=False, null=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
class Logistics(models.Model):
budget = models.CharField(max_length=255, blank=False, null=False)
business_technology = models.CharField(max_length=3, choices=CHOICES, blank=False, null=False)
vendor_or_contracts = models.CharField(max_length=3, choices=CHOICES, blank=False, null=False)
studyConcept = models.OneToOneField(StudyConcept, on_delete = models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
def get_absolute_url(self):
return reverse('update_Logistics', kwargs={'pk': self.pk})
def get_deliverablesLogistics(self):
return ','.join([str(i) for i in self.deliverablesLogistics.all().values_list('id', flat=True)])
def get_paymentScheduleLogistics(self):
return ','.join([str(i) for i in self.paymentScheduleLogistics.all().values_list('id', flat=True)])
def get_commentsLogistics(self):
return ','.join([str(i) for i in self.commentsLogistics.all().values_list('id', flat=True)])
class DeliverablesLogistics(models.Model):
milestone_deliverable = models.CharField('MileStone/Deliverable', max_length=480, blank=False, null=False)
poa = models.CharField('POA', max_length=480, blank=False, null=False)
start_date = models.DateField(blank=False, null=False)
end_date = models.DateField(blank=False, null=False)
logistics = models.ForeignKey(Logistics, related_name='deliverablesLogistics', on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
class PaymentScheduleLogistics(models.Model):
milestone_deliverable = models.CharField('MileStone/Deliverable', max_length=480, blank=False, null=False)
cost = models.DecimalField(max_digits=14, decimal_places=2, blank=False, null=False, default=0)
estimated_payment_date = models.DateField(blank=False, null=False)
logistics = models.ForeignKey(Logistics, related_name='paymentScheduleLogistics', on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
class CommentsLogistics(models.Model):
comments = models.CharField('Comment', max_length=2000, blank=True, null=True)
commented_by = models.CharField(max_length=2000, blank=True, null=True)
logistics = models.ForeignKey(Logistics, related_name='commentsLogistics', on_delete=models.CASCADE)
def __str__(self):
return str(self.id)
views.py
def load_concepts(request):
currentUser = User.objects.get(id=request.user.id)
concepts = StudyConcept.objects.all().filter(user=request.user)
#concepts = get_object_or_404(StudyConcept)
return render(request, 'concept_dropdown_list_options.html',{
'concepts':concepts
})
class LogisticsFormsetCreate(CreateView):
model = Logistics
template_name = 'createLogistics.html'
form_class = LogisticsForm
success_url = reverse_lazy('create_Logistics')
def get_context_data(self, **kwargs):
data = super(LogisticsFormsetCreate, self).get_context_data(**kwargs)
if self.request.POST:
data['deliverable'] = DeliverablesLogisticsFormset(self.request.POST, prefix='deliverables')
data['paymentSchedule'] = PaymentScheduleLogisticsFormset(self.request.POST, prefix='payments')
data['comment'] = CommentsLogisticsFormset(self.request.POST, prefix='comments')
#data['studyRequestConcept'] = self.request.POST.get('studyRequestConcept')
else:
data['deliverable'] = DeliverablesLogisticsFormset(prefix='deliverables')
data['paymentSchedule'] = PaymentScheduleLogisticsFormset(prefix='payments')
data['comment'] = CommentsLogisticsFormset(prefix='comments')
#data['studyRequestConcept'] = self.request.GET.get('studyRequestConcept')
return data
def form_valid(self, form):
context = self.get_context_data()
deliverable = context['deliverable']
paymentSchedule = context['paymentSchedule']
comment = context['comment']
with transaction.atomic():
if deliverable.is_valid() and paymentSchedule.is_valid() and comment.is_valid():
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object = form.save()
deliverable.instance = self.object
deliverable.save()
paymentSchedule.instance = self.object
paymentSchedule.save()
comment.instance = self.object
comment.save()
messages.success(self.request, Logistics.__name__ +' Form ID: '+ str(self.object.id) + ' was submitted successfully')
return super(LogisticsFormsetCreate, self).form_valid(form)
else:
return self.render_to_response(self.get_context_data(form=form))
Template
{% extends "header.html" %}
{% load widget_tweaks %}
{% block content %}
{% csrf_token %}
{% include 'xdsoft_stylesheets.html' %}
{% include 'messages.html' %}
<div class="container" align="center">
<h1 class="display-5">Logistics</h1>
</div>
<br/>
<div class="table-responsive">
<table class="table table-striped table-bordered" id="example" data-toggle="table"
data-filter-control="true" data-show-export="true"
data-click-to-select="true" data-toolbar="#toolbar" data-escape>
<thead>
<tr>
<th></th>
<th class="text-center" data-field="id" data-filter-control="input">ID</th>
<th class="text-center" data-field="project" data-filter-control="input">Project</th>
<th class="text-center" data-field="date_of_request" data-filter-control="input">Date</th>
<th class="text-center" data-field="brief_summary" data-filter-control="input">Summary</th>
<th class="text-center" data-field="scientific_question" data-filter-control="input">Question</th>
</tr>
</thead>
<tbody>
{%for studyRequestConcept in concepts %}
<tr>
<td style="width:200px">
<a class=" btn btn-primary js-create-logistics" data-toggle="modal" data-target="#modal" href="{% url 'create_Logistics' %}">
<span class="glyphicon glyphicon-plus"></span>
New Logistics
</a>
</td>
<td class="text-left">{{studyRequestConcept.id}}</td>
<td class="text-left">{{studyRequestConcept.project}}</td>
<td class="text-left">{{studyRequestConcept.date_of_request}}</td>
<td class="text-left">{{studyRequestConcept.brief_summary}}</td>
<td class="text-left">{{studyRequestConcept.scientific_question}}</td>
</tr>
{% endfor%}
</tbody>
</table>
</div>
{% comment %}The modal container{% endcomment %}
<div class="modal" id="modal" data-backdrop="false"></div>
<script>
$(function () {
$('.js-create-logistics').click( function () {
var btn = $(this)
$.ajax({
url: btn.attr("href"),
context: document.body
}).done(function(response) {
$("#modal").html(response);
});
});
});
</script>
{% endblock %}
I have a view/template where I list all the Study Concepts and every row has a create new Logistics button next to it. After clicking create new logistics button, the modal/view will open that will allow you to create a new Logistics. I want to pass the instance of the object study concept when I click the button.
Also, CreateLogistics is a class-based view designed using "from django.views.generic import CreateView"
I will be more than happy to provide any further code or information needed. Thanks in advance for all the support and help.
Regards,
Amey Kelekar
You haven't shown your URLs, but you need to accept the ID in the URL for the CreateView and use it in form_valid. For example:
path('/create_logistics/<int:id>/', LogisticsFormsetCreate.as_view(), name="create_Logistics"),
So in the template you would do:
<a class="btn btn-primary js-create-logistics" data-toggle="modal" data-target="#modal" href="{% url 'create_Logistics' id=studyRequestConcept.id %}">
and in the view:
def form_valid(self, form):
...
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.studyConcept_id = self.kwargs['id']
self.object.save()
...
Related
My tables in my django don't show up , the titles for the table do but the data itself does not. can someone tell me what is wrong with my code please. Thank you
dashboard.html
{% extends 'accounts/main.html' %}
{% block content %}
{% include 'accounts/status.html' %}
<br>
<div class="col-md-16">
<h5>LAST 5 ORDERS</h5>
<hr>
<div class="card card-body">
<a class="btn btn-primary btn-sm btn-block" href="">Create Order</a>
<table class="table table-sm">
<tr>
<th>Title</th>
<th>Language</th>
<th>Rating</th>
<th>Type of Media</th>
<th>Genre</th>
<th>Review</th>
<th>Notes</th>
<th>Date</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for media in medias %}
<tr>
<td>{{media.title}}</td>
<td>{{media.language}}</td>
<td>{{media.rating}}</td>
<td>{{media.type_of_media}}</td>
<td>{{media.genre}}</td>
<td>{{media.review}}</td>
<td>{{media.notes}}</td>
<td>{{media.date}}</td>
<td>Update</td>
<td>Delete</td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
models.py
from django.db import models
class Media(models.Model):
CATEGORY = (
('Movie', 'Movie'),
('Tv Show', 'Tv Show'),
('Drama', 'Drama'),
('Other', 'Other'),
)
NUMBER = (
('1', '1'),
('2', '2'),
('3', '3'),
('4', '4'),
('5', '5'),
)
GROUP = (
('Action', 'Action'),
('Anime', 'Anime'),
('Comedy', 'Comedy'),
('Crime', 'Crime'),
('Fantasy', 'Fantasy'),
('Horror', 'Horror'),
('Romance', 'Romance'),
('Other', 'Other'),
)
title = models.CharField(max_length=200, null=True)
language = models.CharField(max_length=200, null=True)
rating = models.CharField(max_length=200, null=True, choices=NUMBER)
type_of_media = models.CharField(max_length=200, null=True, choices=CATEGORY)
genre = models.CharField(max_length=200, null=True, choices=GROUP)
review = models.CharField(max_length=1000, null=True)
notes = models.CharField(max_length=1000, null=True, blank=True)
date = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.title
class Status(models.Model):
POSITION = (
('Completed', 'Completed'),
('Continue Watching', 'Continue Watching'),
('Plan to Watch', 'Plan to Watch'),
('Dropped', 'Dropped'),
)
media = models.ForeignKey(Media, null=True,on_delete= models.SET_NULL)
status_of_media = models.CharField(max_length=200, null=True, choices=POSITION)
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import *
# Create your views here.
def home(request):
return render(request, 'accounts/dashboard.html')
medias = Media.objects.all()
context = {'medias': medias}
return render(request, 'accounts/dashboard.html', context)
def products(request):
return render(request, 'accounts/products.html')
def customer(request):
return render(request, 'accounts/customer.html')
Those are all the relevant windows
Thanks
ignore this please i need more words to publish my question
def home(request):
return render(request, 'accounts/dashboard.html')
medias = Media.objects.all()
context = {'medias': medias}
return render(request, 'accounts/dashboard.html', context)
def products(request):
return render(request, 'accounts/products.html')
def customer(request):
return render(request, 'accounts/customer.html')
instead of this line.
{% for media in mediass %}
use the line below
{% for media in medias %}
you passed medias in your context.
I think you just misspelled it
You are returning before you add 'medias' to the context:
def home(request):
**return render(request, 'accounts/dashboard.html')**
medias = Media.objects.all()
context = {'medias': medias}
return render(request, 'accounts/dashboard.html', context)
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 %}
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).
i want to get the images form the image model in the template.
class Products(models.Model):
category = models.ForeignKey(Category)
name= models.CharField(max_length=120, unique=True)
slug = models.SlugField(unique = True)
price = models.IntegerField(default=100)
class Image(models.Model):
property = models.ForeignKey(Products, related_name='images')
image = models.ImageField(upload_to='static/images/home',blank=True,null=True)
views.py
def index(request):
queryset = Products.objects.all()
return render_to_response('site/index.html',
locals(),
context_instance=RequestContext(request))
{% for query in queryset %}
<img src='/ {{ query.????? }} ' alt="" width = 'auto' height='340'/>
{% endfor %}
i want to get the images which is connected to that product
i have readed that link
i have tried:
{% for query in queryset %}
<img src='/ {{ query.images_all.0.image }} ' alt="" width = 'auto' height='340'/>
{% endfor %}
but no success ..
just try to understand the model that how i get the image url from models which related with foreignkey relationship.
my models:
class Product(models.Model):
title = models.CharField(max_length = 400)
slug = models.SlugField(max_length = 400,unique=True,null=True,blank=True)
is_popular = models.BooleanField(default=True)
category = models.ForeignKey(Category,on_delete=models.CASCADE)
subcategory = models.ForeignKey(Subcategory,on_delete=models.CASCADE,null=True,blank=True)
childcategory = models.ForeignKey(Childcategory,on_delete=models.CASCADE,null=True,blank=True)
brand = models.ForeignKey(Brand,on_delete=models.CASCADE,null=True,blank=True)
description = models.TextField()
is_active = models.IntegerField(choices=STATUS_CHOICES)
created_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = unique_slug_generator(self)
super(Product, self).save(*args, **kwargs)
def show_image(self):
return self.productmeaserment_set.first().first_image()
class ProductMeaserment(models.Model):
product = models.ForeignKey(Product,on_delete=models.CASCADE)
measerment = models.ForeignKey(Measerment,on_delete=models.CASCADE,null=True,blank=True)
selling_price = models.DecimalField(max_digits=20,decimal_places=2)
offer_price = models.DecimalField(max_digits=20,decimal_places=2)
available_quantity = models.IntegerField();
is_active = models.IntegerField(choices=STATUS_CHOICES)
created_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.measerment.name
def first_image(self):
return self.productmeasermentimage_set.first()
class ProductMeasermentImage(models.Model):
productmeaserment = models.ForeignKey(ProductMeaserment,on_delete=models.CASCADE)
image = models.FileField(upload_to='uploads/products')
is_active = models.IntegerField(choices=STATUS_CHOICES)
created_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.productmeaserment.product.title
views.py
from products.models import Product
def adminpanel(request):
products=Product.objects.all()
return render(request,'adminpanel/index.html',{'productsall':products})
templates/adminpanel/index.html
{% for item in productsall %}
<tr>
<div class="border1">
<td class="image-cell">
<img src="{{item.show_image.image.url}}"> #this is how i got image url.
</td>
</div>
<td data-label="title">{{item.title}}</td>
<td data-label="category">{{item.category}}</td>
<td data-label="subcategory">{{item.subcategory}}</td>
<td data-label="brand">
{{item.brand}}
</td>
<td data-label="description">
{{item.description}}
</td>
<td class="created">
{{item.created_date}}
</td>
</tr>
<tr>
{% endfor %}
There is so much wrong with your code, I suggest that you do the Django Tutorial first.
https://docs.djangoproject.com/en/1.8/intro/tutorial01/
But if you wan't it working, here is how:
models.py
class Product(models.Model):
category = models.ForeignKey(Category)
name= models.CharField(max_length=120, unique=True)
slug = models.SlugField(unique = True)
price = models.IntegerField(default=100)
def first_image(self):
# code to determine which image to show. The First in this case.
return self.images[0]
class ProductImage(models.Model):
image = models.ImageField(upload_to='static/images/home',blank=True,null=True)
product = models.ForeignKey(Product, related_name='images')
views.py
def index(request):
queryset = Products.objects.all()
return render_to_response('site/index.html', {'products': queryset})
index.html
{% for product in products %}
<img src="{{ product.first_image.src }}" alt="" width="auto" height="340"/>
{% endfor %}
I have a form field that calls a queryset and uses the 'select' widget.
Is there a way to remove an option value from the queryset if it already has been 'added' to the cart?
In the select form, there's three options: Option A, Option B, Option C.
The user selects Option A, and clicks 'Add'. Now once the user clicks 'Add', I want to remove Option A from the select.
Only Option B and Option C will be available to choose from.
Can this be done just using Django+Python? Or will I need to use additional JS/jQuery?
Thanks!
models.py
class Pickup(models.Model):
# id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, null=True)
total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
active = models.BooleanField(default=True)
status = models.CharField(max_length=120, choices=STATUS_CHOICES, default="Open")
def __str__(self):
return "Pickup Order ID: %s" %(str(self.id))
class PickupItem(models.Model):
pickup = models.ForeignKey('Pickup', null=True, blank=True)
dropoffitem = models.ForeignKey(DropoffItem)
notes = models.TextField(null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
forms.py
class AddPickupItemForm(forms.ModelForm):
dropoffitem = forms.ModelChoiceField(queryset=DropoffItem.objects.all(), widget=forms.Select(attrs={'class':'form-control'}))
class Meta:
model = PickupItem
fields = ['dropoffitem']
views.py
def add_item_to_pickup_order(request):
request.session.set_expiry(120000)
try:
user = request.user
the_id = request.session['pickup_id']
pickup = Pickup.objects.get(id=the_id)
except:
user = request.user
new_pickup_order = Pickup(user=user)
new_pickup_order.save()
request.session['pickup_id'] = new_pickup_order.id
the_id = new_pickup_order.id
pickup = Pickup.objects.get(id=the_id)
try:
dropoffitem = DropoffItem.objects.get(id=id)
except DropoffItem.DoesNotExist:
pass
except:
pass
form = AddPickupItemForm(request.POST or None)
if request.method == "POST":
dropoffitem_id = int(request.POST['dropoffitem'])
pickup_item = PickupItem.objects.create(pickup=pickup, dropoffitem_id=dropoffitem_id)
pickup_item.save()
return HttpResponseRedirect('%s'%(reverse('add_item_to_pickup_order')))
context = {
"pickup": pickup,
"form": form,
}
return render(request, 'pickups/create_pickup_order.html', context)
.html
{% extends "base.html" %}
{% block content %}
<div class="row">
<div class="container">
<div class="col-xs-12">
<h1>Create Cart</h1>
<form method="POST" action="{% url 'add_item_to_pickup_order' %}">
{% csrf_token %}
<table class="table">
<thead>
<th>Item</th>
<th></th>
</thead>
<tr>
<td>{{ form.dropoffitem }}</td>
<td><input type="submit" value="Add Item" class="btn btn-default btn-primary" /></td>
</tr>
</table>
</form>
To exclude/remove an item from the queryset, you can use exclude.
YourModel.objects.exclude(id=4)
To exclude multiple items:
YourModel.objects.exclude(id__in=[4, 6, 10])
More info about exclude on Django docs.