ValueError: The 'Image' attribute has no file associated with it - python

It says 'Image' attribute has no file associated what does that mean? How do I solve this issue?
I tried to search in internet and couldn't understand anything because I've only started learning.
My view:
def bookdata(req):
if req.method == "POST":
b_name = req.POST.get('book name')
a_name = req.POST.get('author name')
p_year = req.POST.get('published year')
price = req.POST.get('price')
image = req.FILE['image']
obj = BookDetails(Name=b_name, A_Name=a_name, P_Year=p_year, Price=price, Image=image)
obj.save()
return redirect(add_books)
My model:
class BookDetails(models.Model):
Name = models.CharField(max_length=30, null=True, blank=True)
A_Name = models.CharField(max_length=30, null=True, blank=True)
P_Year = models.IntegerField(null=True, blank=True)
Price = models.IntegerField(null=True, blank=True)
Image = models.ImageField(upload_to="book images", null=True, blank=True)
Template:
<table class="table table-bordered">
`<thead>`
<tr>
<th>Name</th>
<th>A_Name</th>
<th>P_Year</th>
<th>Price</th>
<th>Image</th>
</tr>
</thead>
{% for i in data %}
<tr>
<td>{{ i.Name }}</td>
<td>{{ i.A_Name }}</td>
<td>{{ i.P_Year }}</td>
<td>{{ i.Price }}</td>
<td>
<img src="{{ i.Image.url}} ">
</td>
</tr>
{% endfor %}
If I do it like this there is no error, but image is not shown.
<img src="{{ i.Image }}">

The error causes because no image is associated with the image field. Use the following code to store image properly:
def bookdata(req):
if req.method == "POST":
b_name = req.POST.get('book name')
a_name = req.POST.get('author name')
p_year = req.POST.get('published year')
price = req.POST.get('price')
image = req.FILES['image'] # Change Done Here
obj = BookDetails(Name=b_name, A_Name=a_name, P_Year=p_year, Price=price, Image=image)
obj.save()
return redirect(add_books)
In the template, you can also make some changes like :
<td>
{% if i.Image %}
<img src="{{ i.Image.url}} ">
{% else %}
<img src="#path_to_default_image">
{% endif %}
</td>

Related

Nested Regroups with django with some attributes from none regroups

I have a django template that I have implemented regroups in it. I have a problem with how to display some of the attributes from my model into the template in a table.
I have a couple of issues to address:
How can I display the remaining 4 attributes from the ImplementationMatrix model i.e implementation_status, implementation_summary, challenges, and wayforward to be displayed at the respective columns in the table on the template (index.html) without distorting the layout for each instance of ImplementationMatrix.
The last for loop in the templates displays only one item for subactivity while I have more than subactivity for the respective activity.
Is there any better way of implementing all this?
My Models:
class Strategy(TrackingModel):
"""
Stores all the strategies related to HSSP.
"""
strategy_name = models.CharField(
max_length=255, blank=True, null=True, default="")
class Meta(TrackingModel.Meta):
verbose_name_plural = "Strategies"
def __str__(self):
return self.strategy_name
class Intervention(TrackingModel):
intervention_name = models.CharField(
max_length=255, blank=True, null=True, default=""
)
strategy = models.ForeignKey(Strategy, on_delete=models.PROTECT)
class Meta(TrackingModel.Meta):
verbose_name_plural = "Interventions"
def __str__(self):
return self.intervention_name
class Activity(TrackingModel):
activity_name = models.CharField(
max_length=255, blank=True, null=True, default="")
intervention = models.ForeignKey(Intervention, on_delete=models.PROTECT)
class Meta(TrackingModel.Meta):
verbose_name_plural = "Activities"
def __str__(self):
return self.activity_name
class SubActivity(TrackingModel):
subactivity_name = models.CharField(
max_length=255, blank=True, null=True, default=""
)
activity = models.ForeignKey(Activity, on_delete=models.PROTECT)
class Meta(TrackingModel.Meta):
verbose_name_plural = "Sub Activities"
def __str__(self):
return self.subactivity_name
class ImplementationMatrix(TrackingModel):
"""
The class for keeping track the implementation of each action plan
"""
IMPLEMENTATION_STATUS = (
("ON PROGRESS", "ON PROGRESS"),
("DONE", "DONE"),
("NOT DONE", "NOT DONE"),
)
implementation_summary = models.TextField()
implementation_status = models.CharField(
choices=IMPLEMENTATION_STATUS, max_length=100, default="",
verbose_name="Matrix Implementation Status"
)
challenges = models.TextField()
way_forward = models.TextField()
sub_activity = models.ForeignKey(
SubActivity, on_delete=models.PROTECT, verbose_name='Sub-Actions')
def __str__(self) -> str:
return self.sub_activity.activity.intervention.strategy.strategy_name
My View:
#login_required(login_url="/login")
def matrix_implementation_list(request: HttpRequest) -> HttpResponse:
all_implementations = ImplementationMatrix.objects.filter(
active=True, deleted=False).select_related(
'sub_activity',
'sub_activity__activity',
'sub_activity__activity__intervention',
'sub_activity__activity__intervention__strategy')
context = {'all_implementations': all_implementations}
return render(request, 'index.html', context)
My template (index.html)
<div class="card-body">
{% regroup all_implementations by sub_activity.activity.intervention.strategy.strategy_name as strategy_list %}
<!-- Start Table section -->
<div class="table-responsive table-bordered">
<table class="table">
<thead class="thead-light">
<tr>
<th>Policy Statement</th>
<th>Action</th>
<th>Sub-Actions</th>
<th>Implementation Summary</th>
<th>Implementation Status</th>
<th>Challenges</th>
<th>Way Forward</th>
</tr>
</thead>
{% for strategy in strategy_list %}
<tr>
<td colspan="7" class="text-center"><strong>Priority Area {{ forloop.counter }}: {{ strategy.grouper }}</strong></td>
</tr>
{% regroup strategy.list by sub_activity.activity.intervention.intervention_name as intervention_list %}
{% for intervention in intervention_list %}
{% regroup intervention.list by sub_activity.activity.activity_name as activity_list %}
{% for activity in activity_list %}
{% regroup activity.list by sub_activity.subactivity_name as subactivity_list %}
{% for subactivity in subactivity_list %}
<tr>
{% if forloop.first %}
{% if forloop.parentloop.first %}
<td rowspan="{{ intervention.list|length }}">
{{ intervention.grouper|wordwrap:30|linebreaksbr }}
</td>
{% endif %}
<td rowspan="{{ activity.list|length }}">
{{ activity.grouper|wordwrap:30|linebreaksbr }}
</td>
{% endif %}
<td>
{{ subactivity.grouper|wordwrap:20|linebreaksbr }}
</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
{% endfor %}
{% endfor %}
{% endfor %}
{% endfor %}
</table>
</div>
<!-- end Table Section -->
</div>
I was able to display the contents of the parent model in the last 'for loop' by doing the following:
<td>{{ subactivity.grouper|wordwrap:20|linebreaksbr }}</td>
<td>{{subactivity.list.0.implementation_summary|wordwrap:30|linebreaksbr}}</td>
<td>{{ subactivity.list.0.get_implementation_status_display }}</td>
<td>{{ subactivity.list.0.challenges|wordwrap:30|linebreaksbr }}</td>
<td>{{ subactivity.list.0.way_forward|wordwrap:30|linebreaksbr }}</td>

i have to make a relation between movie and actor without using manytomany field i have to use only foreign key in django i've write this code so far

models.py
class Movielist(models.Model) :
Title = models.CharField(max_length=1000)
Description = models.TextField(blank=True)
ReleaseDate = models.DateTimeField(verbose_name='Release Date', blank=True)
# NoOfActors = models.IntegerField()
Upvote = models.IntegerField(default=0)
Downvote = models.IntegerField(default=0)
def __str__(self):
return self.Title
class Actorlist(models.Model):
Name = models.CharField(max_length=1000)
DateofBirth = models.DateTimeField(verbose_name='Date of Birth',blank=True)
# NoOfActors = models.IntegerField()
def __str__(self):
return self.Name
class ActorInMovie(models.Model):
Movie = models.ForeignKey(Movielist, default=1, on_delete=models.CASCADE, blank=True)
Actor = models.ForeignKey(Actorlist, default=1, on_delete=models.CASCADE, blank=True)
def __str__(self):
return self.Movie.Title
views.py
def Movie_Detail(request):
MovieName = Movielist.objects.all()
tablelist = ActorInMovie.objects.all()
return render(request, 'Collection/index.html', {'MovieName':MovieName, 'tablelist':tablelist})
index.html
<table border="solid">
<th>Name</th>
<th>Release Date</th>
<th>Actors</th>
{% for data in MovieName %}
<tr>
<td>{{ data.Title }}</td>
<td>{{ data.ReleaseDate }}</td>
<td>
<ul>
{% for name in tablelist %}
<li>{{ name.Actor.Name }}</li>
{% endfor %}
</ul>
</td>
</tr>
{% endfor %}
</table>
**i have getting this out put can any any one tell me how to filter this data only my movie id i would like if someone come and help me in solving this problem
[this is the output what i am getting but i want filter actors name by movielist.id][1]
[1]: https://i.stack.imgur.com/BlAuP.png**
You are selecting all the objects in ActorInMovie into tablelist, and not just the related ones. You don't need the tablelist at all. Instead:
{% for data in MovieName %}
<tr>
<td>{{ data.Title }}</td>
<td>{{ data.ReleaseDate }}</td>
<td>
<ul>
{% for movie_actor in data.ActorInMovie %}
<li>{{ movie_actor.Actor.Name }}</li>
{% endfor %}
</ul>
</td>
</tr>
{% endfor %}
You might also need to use related_name in your ActorInMovie model to tell django how you'll identify the related fields:
Movie = models.ForeignKey(Movielist, default=1, on_delete=models.CASCADE, blank=True, related_name='ActorInMovie)
Since you're going to print all the actors of every movie, it's a good idea to use prefetch_related(Another ref) to achieve better performance, but it's not required if you don't have a lot of data.

How to assign few objects to one user

I want to have template page with object(orders) list (another list, for another user). Like relations one to many. Where do i need to define that objects(order)(for exemple by id: order_id=1 and order_id=3) is assigned to user(driver) with id=1 etc?
I was trying to create Driver class and than set atribute driver in order Class like this.
form.py
class OrderForm(forms.Form):
telephone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'.")
airport = forms.ChoiceField(choices=AIRPORT_CHOICES) ### Jeśli lotnisko jest celem podróży
direction = forms.ChoiceField(choices=DIRECTION_CHOICES) ## to pick_up < plane i odwrotnie!!!
adress = forms.CharField()
client = forms.CharField()
telephone = forms.CharField(validators=[telephone_regex])
flight_number = forms.CharField()
plane = forms.DateTimeField(input_formats=['%Y-%m-%d'])
pick_up = forms.DateTimeField(input_formats=['%Y-%m-%d'])
gate = forms.CharField()
company = forms.ChoiceField(choices=COMPANY_CHOICES)
driver = forms.ChoiceField(choices=DRIVER_CHOICES)
models.py
class Driver(models.Model):
name = models.CharField(max_length=30)
tel = models.CharField(max_length=17)
class Order(models.Model):
telephone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format:
'+999999999'.")
airport = models.CharField(max_length=10, choices=AIRPORT_CHOICES)
direction = models.CharField(max_length=7, choices=DIRECTION_CHOICES)
adress = models.CharField(max_length=100, null=False, blank=False)
client = models.CharField(max_length=50, null=False, blank=False)
telephone = models.CharField(validators=[telephone_regex], max_length=17, blank=False)
flight_number = models.CharField(max_length=7)
plane = models.DateTimeField(null=True)
pick_up = models.DateTimeField(null=True)
gate = models.CharField(max_length=10, null=True, blank=True)
comapny = models.CharField(max_length=50, choices=COMPANY_CHOICES)
driver = models.ForeignKey(Driver, on_delete=models.CASCADE)
order_list.html
{% extends "base.html" %}
{% block content %}
{% if user.is_authenticated %}
<h1>Hi {{ user.username }}! Have a good tips!</h1>
{% else %}
<h1>You have to login to see your orders list</h1>
{% endif %}
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">client</th>
<th scope="col">telephone</th>
<th scope="col">flight number</th>
<th scope="col">airport</th>
<th scope="col">direction</th>
<th scope="col">adress</th>
<th scope="col">gate</th>
<th scope="col">plane</th>
<th scope="col">pick up</th>
</tr>
</thead>
{% for order in orders %}
<tbody>
<tr>
<th scope="row">{{ order.id }}</th>
<td>{{ order.client }}</td>
<td>{{ order.telephone }}</td>
<td>{{ order.flight_number }}</td>
<td>{{ order.airport }}</td>
<td>{{ order.direction }}</td>
<td>{{ order.adress }}</td>
<td>{{ order.gate }}</td>
<td>{{ order.plane }}</td>
<td>{{ order.pick_up }}</td>
<td>{{ order.driver }}</td>
</tr>
</tbody>
{% endfor %}
</table>
{% endblock %}
views.py
class OrderView(View):
def get(self, request, id):
orders = Order.objects.get(id=id)
users = User.object.get(id=id)
ctx = {
'orders': orders,
'users': users
}
return render(request, 'order.html', ctx)
class OrderListView(View):
def get(self, request):
form = OrderForm()
orders = Order.objects.all()
ctx = {'form': form, 'orders': orders}
return render(request, 'orders/order_list.html', ctx)
class AddOrderView(View):
def get(self, request):
form = OrderForm()
return render(request, 'orders/add_order.html', {'form': form})
def post(self, request, *args, **kwargs):
form = OrderForm(request.POST)
if form.is_valid():
order = Order.objects.create(airport=form.cleaned_data['airport'],
direction=form.cleaned_data['direction'],
adress=form.cleaned_data['adress'],
client=form.cleaned_data['client'],
telephone=form.cleaned_data['telephone'],
flight_number=form.cleaned_data['flight_number'],
plane=form.cleaned_data['plane'],
pick_up=form.cleaned_data['pick_up'],
gate=form.cleaned_data['gate'],
driver=form.cleaned_data['driver'])
return render(request, 'orders/add_order.html', {'form': form})
I expect to get form when i can input new order and select driver but I'm geting this:
http://dpaste.com/0PD363H

How to show field from another table using Django ORM?

I have a problem showing fields from another table, where two tables have relationships.
This is my first model:
class DataPribadiSiswa(models.Model):
SiswaID = models.AutoField(primary_key=True)
WaliKelasID = models.CharField(max_length=11, blank=True, null=True)
My second model:
class transaksi_kas(models.Model):
id_kas = models.AutoField(primary_key=True)
siswaID_trans = models.ForeignKey(DataPribadiSiswa, null=True, blank=True)
kelas = models.CharField(max_length=1, null=True, blank=True)
This is my views.py:
def transaksi_index(request):
transaksi = {}
transaksi['transaksikas'] = transaksi_kas.objects.select_related('siswaID_trans')
return render(request, 'kastransaksi/transaksi_index.html', transaksi)
This is the template:
<table id="simple-table" class="table table-striped table-bordered table-hover">
<tr>
<th>No.</th>
<th>Nama</th>
<th>Wali Murid</th>
<th>Kelas</th>
</tr>
{% for kas in transaksikas%}
<tr>
<td>{{ forloop.counter }}</td>
<th>{{ kas.siswaID_trans }}</th>
<td>{{ kas.WaliKelasID }}</td>
<td>{{ kas.kelas }}</td>
</tr>
{% endfor %}
</table>
How do I show {{ kas.WaliKelasID }} from DataPribadiSiswa?
I think you mean to do the following
{{ kas.siswaID_trans.WaliKelasID }}
transaksi['transaksikas'] = transaksi_kas.objects.select_related('siswaID_trans') after this you have to make query get or filter or other.
Example:
transaksi['transaksikas'] = transaksi_kas.objects.select_related('siswaID_trans').get(id=id)
or
transaksi['transaksikas'] = transaksi_kas.objects.select_related('siswaID_trans').filter(your query)
this is link

Data not displaying correctly in my template for django

I need help figuring out how to set up my html table in a way that is giving me issues if anyone can help me figure out how to fix it and make it look like the second picture would be awesome.
*Side note I am using Django
So first off I have three models that I will be using in this view/template. They are called Sheet, Dimension, Inspeciton_vals, my Dimension model has a forgien key called sheet_id which links to sheet, my Inspeciton_vals model has a foreign key that links to Dimension.
Here is my views.py
#login_required
def shipping(request, id):
sheet_data = Sheet.objects.get(pk=id)
work_order = sheet_data.work_order
customer_data = Customer.objects.get(id=sheet_data.customer_id)
customer_name = customer_data.customer_name
title_head = 'Shipping-%s' % sheet_data.work_order
complete_data = Sheet.objects.raw("""select s.id, s.work_order, d.target, i.reading, d.description, i.serial_number from app_sheet s left join app_dimension d on s.id = d.sheet_id
left join app_inspection_vals i on d.id = i.dimension_id""")
for c_d in complete_data:
dim_description = Dimension.objects.filter(sheet_id=c_d.id).values_list('description', flat=True).distinct()
dim_id = Dimension.objects.filter(sheet_id=c_d.id)[:1]
for d_i in dim_id:
dim_data = Inspection_vals.objects.filter(dimension_id=d_i.id)
sample_size = dim_data
return render(request, 'app/shipping.html',
{
'work_order': work_order,
'sample_size': sample_size,
'customer_name': customer_name,
'title': title_head,
'complete_data': complete_data,
'dim_description': dim_description,
})
here are my models
class Sheet(models.Model):
objects = SheetManager()
create_date = models.DateField()
updated_date = models.DateField()
customer_name = models.CharField(max_length=255)
part_number = models.CharField(max_length=255)
part_revision = models.CharField(max_length=255)
work_order = models.CharField(max_length=255)
purchase_order = models.CharField(max_length=255)
sample_size = models.IntegerField()
sample_scheme = models.CharField(max_length=255)
overide_scheme = models.IntegerField()
template = models.IntegerField()
sample_schem_percent = models.IntegerField()
critical_dimensions = models.IntegerField()
closed = models.IntegerField()
serial_index = models.CharField(max_length=255)
drawing_number = models.CharField(max_length=255)
drawing_revision = models.CharField(max_length=255)
heat_number = models.CharField(max_length=255)
note = models.CharField(max_length=255)
valc = models.CharField(max_length=255)
class Dimension(models.Model):
description = models.CharField(max_length=255)
style = models.CharField(max_length=255)
created_at = models.DateField()
updated_at = models.DateField()
target = models.IntegerField()
upper_limit = models.IntegerField()
lower_limit = models.IntegerField()
inspection_tool = models.CharField(max_length=255)
critical = models.IntegerField()
units = models.CharField(max_length=255)
metric = models.CharField(max_length=255)
target_strings = models.CharField(max_length=255)
ref_dim_id = models.IntegerField()
nested_number = models.IntegerField()
met_upper = models.IntegerField()
met_lower = models.IntegerField()
valc = models.CharField(max_length=255)
sheet = models.ForeignKey(Sheet, on_delete=models.CASCADE, default=DEFAULT_FOREIGN_KEY)
class Inspection_vals(models.Model):
created_at = models.DateField()
updated_at = models.DateField()
reading = models.IntegerField(null=True)
reading2 = models.IntegerField(null=True)
reading3 = models.IntegerField(null=True)
reading4 = models.IntegerField(null=True)
state = models.CharField(max_length=255)
state2 = models.CharField(max_length=255)
state3 = models.CharField(max_length=255)
state4 = models.CharField(max_length=255)
approved_by = models.CharField(max_length=255)
approved_at = models.DateField(null=True, blank=True)
dimension = models.ForeignKey(Dimension, on_delete=models.CASCADE, default=DEFAULT_FOREIGN_KEY)
serial_number = models.IntegerField(default=1)
Finally here is my template What I want to do is have my header be the serial numbers. This will be based off sample_size on my sheet model so lets say I have 24 as a sample size show 20 horizontal rows. Next is I will have my dimension description on the right side now with the sample_size being 24 I will have 2 dimensions linked to my sheet model this will change every time as well. Finally I want to put the reading in the rest of the table for each Inspection_val and dimension- so if I have 2 dimensions with a sample_size of 24 I should have 48 Inspeciton_vals with that I want to use the correct reading for the coresponding dimension and serial number. Here is what I have so far--
<div class="container">
<div class="row">
<div>
<table >
<thead>
<tr>
<th>Serial Number</th>
{% for ss in sample_size %}
<th>{{ ss.serial_number }}</th>
{% endfor %}
</tr>
<tr>
{% for r_c in complete_data %}
<th> {{ r_c.reading }} </th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for desc in dim_description.all %}
<tr>
<th> {{ desc }}</th>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
Here is what it looks like now
Here is what I would like it to look like
Bonus here is what my data looks like
Fix after answer suggestions still not displaying it how I would like it to..
<div class="container">
<div class="row">
<div>
<table >
<thead>
<tr>
<th>Serial Number</th>
{% for ss in sample_size %}
<th>{{ ss.serial_number }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for desc in dim_description.all %}
<tr>
<td> {{ desc }}</td>
</tr>
{% for r_c in complete_data %}
<td> {{ r_c.reading }} </td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
Picture of what it looks like now
Updated code with #Michael Platt suggestion
<div class="container">
<div class="row">
<div>
<table >
<thead>
<tr>
<th>Serial Number</th>
{% for ss in sample_size %}
<th>{{ ss.serial_number }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for desc in dim_description.all %}
<tr>
<td> {{ desc }}</td>
{% for r_c in complete_data %}
<td> {{ r_c.reading }} </td>
{% endfor %}
{% endfor %}
</tr>
</tbody>
</table>
</div>
</div>
</div>
#Michael Platt helped fix the html issue now I want to be able to split the reading in half so 24 will go on the inner od row and the next 24 will go on the outter od row.
Ok so knowing that I think this is your problem here:
<tbody>
{% for desc in dim_description.all %}
<tr>
<td> {{ desc }}</td>
{% for r_c in complete_data %}
<td> {{ r_c.reading }} </td>
{% endfor %}
{% endfor %}
</tr>
</tbody>
You had an extra <\tr> just before your second {% endfor %} in the <tbody> tags. I've changed it above so I think it will give the right design you want. If it doesn't let me know but it's a bit hard to test on my end just because I don't have the app up and running :-)
Cheers,

Categories