I want to upload an excel file containing 4 columns and display each column in different page.
views.py
def upload(request):
if "GET" == request.method:
return render(request, 'myapp/upload.html', {})
else:
excel_file = 'WBSdetails.xlsx'
pd.read_excel(excel_file, sheet_name = 'ItemDetails')
return render(request, 'myapp/structuremaster.html')
def structure(request):
structures=ConVehicleMaster.objects.all()
context={
'structures':structures
}
return render(request, 'myapp/structuremaster.html', context)
models.py
class Excel(models.Model):
structure = models.CharField(("Structure"), max_length=150)
segment = models.CharField(("Segment"), max_length=150)
subsegment = models.CharField(("SubSegment"), max_length=150)
element = models.CharField(("Element"), max_length=150)
structuremaster.html
<tbody>
{% for row in WBSdetails %}
{% for cell in row %}
<tr>
<td>{{ cell.structure }}</td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
I am new to django and have very little idea. Any help will be appreciated.
Related
I have a simple table with some rows:
My goal is to instantiate the current value of the quantity and eventually save the new data for all the lines.
At the moment I have a simple view:
#login_required
def compilaDocMultiRow(request,pk):
member = get_object_or_404(testaDoc, pk=pk)
family = corpoDoc.objects.filter(doc=pk)
if request.method == "POST":
form = multiCorpoDocForm(request.POST or None)
if form.is_valid():
reg = form.save(commit=False)
reg.doc_id = member.pk
reg.save()
return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
else:
print(form.errors)
else:
form = multiCorpoDocForm()
return render(request, "compilaDocMultiRow.html", {'family':family, 'member':member, 'form':form})
Is there a way to do this using only Django?
EDIT 1
I was able to instantiate the value with widget tweaks. I am left with the problem of passing the pk of the line to the form and saving the value.
This is the html code:
{% for item in family %}
<tr>
<td>{{ item.item}}</td>
<td>{{ item.desc }}</td>
{% with field=form.qt %}
<td width="15%">{% render_field field class="form-control" placeholder=item.qt %}
</td>
{% endwith %}
<td></td>
<td></td>
</tr>
{% endfor %}
How to display only some columns of Django model in a HTML template?
And also: how do I perform a function on one of the records? (amount)?
Right now I'm displaying a whole table of model like that:
my models.py
class Tabela(models.Model):
block_id = models.CharField(max_length=64)
timestamp = models.DateTimeField()
type = models.CharField(max_length=32)
link = models.CharField(max_length=64)
link_as_account = models.CharField(max_length=100)
account = models.CharField(max_length=100)
amount = models.CharField(max_length=64)
def __str__(self):
return self.block_id
My views.py
def search_results(request):
model = Tabela
query_addresse = request.GET.get('addressee', None)
query_hash = request.GET.get('hash', None)
if not query_hash and not query_addresse and request.method == 'GET':
return render(request, 'nanosite/index.html', {})
if query_hash and request.method == 'GET':
if query_addresse:
result = Tabela.objects.filter(account=query_addresse, block_id=query_hash)
else:
result = Tabela.objects.filter(block_id=query_hash)
field_names = [f.name for f in model._meta.get_fields()]
data = [[getattr(ins, name) for name in field_names]
for ins in result]
elif query_addresse and request.method == 'GET':
result = Tabela.objects.filter(account=query_addresse)
field_names = [f.name for f in model._meta.get_fields()]
data = [[getattr(ins, name) for name in field_names]
for ins in result]
return render(request, 'nanosite/index.html', {'field_names': field_names, 'data': data})
My index.html
<div id="bottomhalf" class="table-responsive">
<table class="table table-sm table-dark table-hover">
<thead class="thead-light">
{% for head in field_names %}
<th scope="col">{{ head }}</th>
{% endfor %}
</thead>
<tbody>
{% for row in data %}
<tr scope="row">
{% for cell in row %}
<td>{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
What I'd like to do is display only block_id, timestamp, account and amount in html. I've tried different approaches like using only the result part of views without field_names and data, but of course it didn't work.
My other question is, how can I modify the field amount and perform an operation on it to be displayed in template like amound divided by certain digit with a $ sign before it (for example if amount=1488 to be divided by 124 and displayed as '$12')?
Pass the queryset qs selecting the objects to display to the template and iterate over it to generate your table:
{% for obj in qs %}
<tr>
<td> {{obj.block_id}} </td>
<!-- etc ... -->
</tr>
{% endfor %}
Now, if you also want to pass a variable specifying the names of the fields of the object to tabulate, and in what order, you find out that the Django template engine is by design (!) incapable of doing that. You can either do what you are doing, and generate a list-of-rows in Python which you pass to the Template, or you need a Django custom template tag such as
#register.filter
def attr( obj, name):
return getattr( obj, name, '')
and then you can run an inner loop in your template
<tr>
{% for name in selected_field_names %}
<td> {{obj|attr:name}} </td>
{% endfor %}
</tr>
The answer to the second question, is to define a property on your model to return the field suitably transmogrified:
class Tabela(models.Model):
...
#property
def funny_amount(self):
val = self.amount/12.0
return f'$ {val:.2f}'
and refer to {{obj.funny_amount}} in your template
I am new in Django, I'm making an item-category exercise. each item belongs to a category via a foreign key.I'm not able to understand problem in my code during submission of item detail. I'm getting an error "FOREIGN KEY constraint failed".
I wrote the code for models.py which is working fine in the admin dashboard of Django, but if same thing I'm trying to implement by HTML form page, I'm getting error.
models.py
class ColorCat(models.Model):
name = models.CharField(max_length=20, default="other")
def __str__(self):
return self.name
class ListItems(models.Model):
name = models.CharField(max_length=25, default='item')
item_cat = models.ForeignKey(ColorCat, on_delete=models.CASCADE, default=0, null=True,blank=True)
views.py
def index(request):
list = ListItems.objects.all()
cat = ColorCat.objects.all()
return render(request, 'colorlist.html', {'color': cat, 'item':list })
def colorlist(request):
new_list = ListItems
new_cate = ColorCat
if request.method=="POST":
item = str(request.POST["item"])
cat = str(request.POST["category"])
f_key = ColorCat.objects.filter(name="orange").get()
new_list(name="item").save()
new_list(item_cat=f_key.id).save()
item = ListItems.objects.all()
color = ColorCat.objects.all()
return render(request, 'colorlist.html', {"item": item, "color": color})
def addcat(request):
if request.method=="POST":
newcat = str(request.POST["name"])
ColorCat(name = newcat).save()
item = ListItems.objects.all()
color = ColorCat.objects.all()
return render(request, 'colorlist.html', {"item":item, "color":color})
colorlist.html
{% extends 'base.html'%}
{% block content%}
<h2>Welcome in color cards</h2>
<form action="addcat" method="POST">
{% csrf_token %}
<lable>add new cat<input type="text" name="name"></lable><br>
<label>submit<input type="submit"></label>
</form>
<form action="colorlist" method="post">
{% csrf_token %}
<label>new item<input type="text" name="item"></label><br>
<label>cat<input type="text" name="category"></label><br>
<label>add item<input type="submit"></label>
</form>
<!--see saved result-->
<table>
<tr>
<th>categories</th>
</tr>
{% for cat in color %}
<tr>
<td>{{cat.name}}</td>
</tr>
{% endfor %}
</table>
<table>
<tr>
<th>category item </th>
</tr>
{% for clr in color %}
{% for itm in item %}
<tr>
{% if clr.name == itm.category %}
<td>{{itm.name}}</td>
{%endif%}
</tr>
{% endfor %}
{% endfor %}
</table>
{% endblock %}
Error
IntegrityError at /color/colorlist
FOREIGN KEY constraint failed
I haven't gone allof your code - there's lots of irrelevant stuff - but I've noticed a couple of errors:
definition of ListItems model, it doesn't make sense to define a default value for field item_cat, it'll try to link the instance with a ColorCat instance with id 0 which probably doesn't exist
item_cat = models.ForeignKey(ColorCat, on_delete=models.CASCADE, null=True, blank=True)
saving a new_list - use ColorCat instance instead of its id
new_list(item_cat=f_key).save()
I have a django model and csv file separately. What I want to do is that user upload a csv file with a single colomn ('fp_Item').If colomn line exists in the django model as per below
(queryset_list.filter(
Q(fp_Item__contains=query)))
I want to retrieve the necessary fields from the database and show within html if does not exists it shouldn't retrieve anything and leave empty but still should have to print the csv file line.
def check_fp(request):
if not request.user.is_active:
return render(request, 'login.html')
else:
if request.method == 'POST' and request.FILES['csv_file2']:
myfile = request.FILES['csv_file2']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
data = csv.reader(fs.open(filename, mode='r'))
queryset_list = fp.objects.all()
lines=[]
for row in data:
if row[0] != 'fp_Item':
line = row[0]
lines.append(line)
query= line
if query:
queryset_list.filter(
Q(fp_Item__contains=query))
queryset_list= fp.objects.all()
context = {'lines': lines,
'instances': queryset_list,
}
return render(request, 'check_fp.html', context)
context = {'lines': lines,
'instances': queryset_list,
}
return render(request, 'check_fp.html', context)
return render(request, 'check_fp.html', {})
lines.append(line) is working and writing csv column to html file but I couldn't somehow bind the django model and the csv column together. Isn't "if query" method usable for this scenario ?
Here is my html file: I want to match line at retrieve description and detail,timestamp and updated fields from the database. Am I looping false here ?
<tbody>
{% for line in lines %}
{% for instance in instances %}
<tr>
<td width="25%>
{{ line }}
</td></tr>
<td>
{{ instance.description }}
</td>
<td>
{{ instance.detail }}
</td>
<td width="180">
{{ instance.timestamp }}
</td>
<td width="180">
{{ instance.updated }}
</td>
<td width="200">
</td>
</tr>{% endfor %} {% endfor %}
</tbody>
</table>
Instead of this below part,
if query:
queryset_list.filter(
Q(fp_Item__contains=query))
queryset_list= fp.objects.all()
context = {'lines': lines,
'instances': queryset_list,
}
return render(request, 'check_fp.html', context)
you need to modify as per below
queryset_list = FP.objects.filter(FP_Item = query)
context = {'lines': lines,
'instances': queryset_list,
}
I want to get all the details of class Material where user=user_id
Here is the models.py:
class Material(models.Model):
subject = models.CharField(max_length=10)
topic = models.CharField(max_length=50)
user = models.IntegerField()
and my views.py:
def add_material(request):
c = {}
c.update(csrf(request))
if 'user_session' in request.session:
user_id = request.session['user_session']
material_array = Material.objects.filter(user=user_id).values()
materials_len = len(material_array)
c['m_len'] = materials_len
for i in range(0, materials_len):
c['material_id_'+str(i)] = material_array[i]
return render_to_response('add_material.html',c)
else:
return HttpResponseRedirect('/user')
and my add_material.html is:
{% for i in range(m_len) %}
<tr>
{% for j in material_id_+str(i) %}
{{j.subject}}
{{j.topic}}
{% endfor %}
</tr>
{%endfor%}
So I am getting error in template, how to insert variable in for loop?
This how I would do it.
views.py
def add_material(request):
c = {}
c.update(csrf(request))
if 'user_session' in request.session:
user_id = request.session['user_session']
material_array = Material.objects.filter(user=user_id)
c.update({'materials': material_array})
return render_to_response('add_material.html', c)
else:
return HttpResponseRedirect('/user')
template
{% for material in materials %}
<tr>
<td>{{ material.subject }}</td>
<td>{{ material.topic }}</td>
<td>{{ material.user.username }}</td>
</tr>
{% endfor %}
You can include any user field you like.