New line in html table - html

My model:
class Affiliation(models.Model):
name = models.CharField(max_length=32)
slug = models.SlugField(unique=True)
descrizione = models.CharField(max_length=500, blank=True, null=True)
class Reg_Affiliation(models.Model):
reg = ...
affiliazione = models.ForeignKey(Affiliation, null=True,
on_delete=models.CASCADE, related_name='affiliation_conoscenza')
My descrizione field (for example):
descrizione = 'line1 <br> line2'
edit: added something about this field, see below /edit
I tried too:
descrizione = "line1 '<br>' line2"
descrizione = 'line1 "<br>" line2'
descrizione = 'line1 \n line2'
descrizione = 'line1 \r\n line2'
My template:
<div class="panel panel-default">
<table class="table table-striped table table-bordered table table-hover table table-condensed">
<thead>
<tr>
<th>Nome</th>
<th>Descrizione</th>
</tr>
</thead>
<tbody>
{% for aff in lista %}
<tr>
<td>
<b>{{ aff.affiliazione }}</b>
</td>
<td>
{{ aff.affiliazione.descrizione }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
I expect:
line1
line2
in the same field of my table, instead I obtain:
line1 <br> line2
My views:
#login_required
def affiliation_list(request):
lista_a=[]
for a in Affiliation.objects.all():
ra=Reg_Affiliation(affiliazione=a,
conoscenza=c,
rapporto=r)
lista_a.append(ra)
context_dict['lista'] = lista_a
return render(request, 'core/affiliation_list.html', context_dict)
I'm using bootstrap, firefox, windows7
Thank you for your help
edit:
maybe it make difference how I add the descrizione field, so:
My populate script:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sitoposs.settings')
import django
django.setup()
def populate():
affiliation1 = add_affiliation('name affiliation1', '''long line1 <br> long line2''')
affiliation2 =
...
def add_affiliation(name, descrizione):
a = Affiliation.objects.get_or_create(name=name)[0]
a.descrizione=descrizione
a.save()
return a
if __name__ == '__main__':
populate()
In my database I read
long line1 <br> long line2
In source page (on the browser right click on the page, view source page or something like that, I don't use english version) I read:
long line1 <br> long line2
In my populate script I tried also:
affiliation1 = add_affiliation('name affiliation1', 'long line1 and <br> long line2 in the same line, so unreadable')

use descrizione = models.TextField(max_length=500, blank=True, null=True) instead of descrizione = models.CharField(max_length=500, blank=True, null=True)
and
use {% autoescape off %}{{ aff.affiliazione.descrizione }}{% endautoescape %} instead of {{ aff.affiliazione.descrizione }}
Generally django escape all html tag and render as raw text, to render actual html you can also use {{ aff.affiliazione.descrizione|safe }}

Related

Django database data not showing in Templete

I have a class HardBook that inherits from Book:
class Book(models.Model):
title = models.CharField('Book Title', max_length=200)
image = models.ImageField('Book Cover', upload_to='covers')
description = models.CharField('Description', max_length= 350)
class HardBook(Book):
quantity = models.IntegerField('Quantity')
views.py
class BookCreateView(CreateView):
def get_context_data(self,**kwargs):
context = super(BookCreateView, self).get_context_data(**kwargs)
context['softbooks'] = SoftBook.objects.all()
context['hardbooks'] = SoftBook.objects.all()
return context
I want to display the field data in a table, I want to show title, image and quantity. Everthing is displayed except quantity.
{% for hardbook in hardbooks %}
<tr>
<td>
<div class="cover-image" style="background-image:url({{hardbook.image.url}});"></div>
</td>
<td>{{hardbook.title}}</td>
<td>{{hardbook.quantity}}</td>
</tr>
{% endfor %}

Django error stating model field not defined

So I am trying to create a django view where retrieval is done on the basis of past number of months for the current logged in user, as selected by him/her in the radio choices. But I am facing an error stating that one of my model fields 'timestamp' is not defined. Also, I am a bit confused as to how to print the retrieved model in the html. Given below are my files:
html:
{% if model %}
<table>
<thead>
<tr>
<th style = "padding: 20px;">Vendor ID</th>
<th style = "padding: 20px;">Employee ID</th>
<th style = "padding: 20px;">Debit</th>
<th style = "padding: 20px;">Credit</th>
<th style = "padding: 20px;">Time of transaction</th>
</tr>
</thead>
<tbody>
{% for i in model %}
<tr>
<td style="text-align: center;">{{ i.vendor_id }}</td>
<td style="text-align: center;">{{ i.emp_id }}</td>
<td style="text-align: center;">{{ i.debit }}</td>
<td style="text-align: center;">{{ i.credit }}</td>
<td style="text-align: center;">{{ i.timestamp }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>There are no active transactions!</p>
{% endif %}
Views.py
if 'form2' in request.POST:
d = {}
date_id = request.POST["groupOfDefaultRadios1"]
x = employee.objects.get(name = request.user)
if date_id == 1:
d = transaction.objects.filter(emp_id = x, timestamp = datetime.date.today-timestamp(days=30))
elif date_id == 2:
d = transaction.objects.filter(emp_id = x, timestamp = datetime.date.today-timestamp(days=60))
else:
d = transaction.objects.filter(emp_id = x, timestamp = datetime.date.today-timestamp(days=180))
print(d)
return render(request, 'profiles/userLogin.html', {'model':d})
models.py:
class vendor(models.Model):
id = models.CharField(max_length=20, primary_key=True)
name = models.CharField(max_length=30)
class employee(models.Model):
name = models.OneToOneField(User, on_delete=models.CASCADE)
id = models.CharField(max_length=20, primary_key=True)
balance = models.IntegerField(default=0)
class transaction(models.Model):
vendor_id = models.ForeignKey(vendor, on_delete=models.CASCADE)
emp_id = models.ForeignKey(employee, on_delete=models.CASCADE)
debit = models.IntegerField()
credit = models.IntegerField()
timestamp = models.DateField(("Date"), default=datetime.date.today)
Any help is appreciated.
If i understand you right, you want filter transaction if their timestamp date less than 30, 60, 180 days from today
Then your filter should look like this
d = transaction.objects.filter(emp_id = x, timestamp__gte = datetime.date.today() - datetime.timedelta(days=30))
e.t.c
p.s.: Avoid naming models field with names that used in libs that you use, like timestamp
First things first, when Django raised an undefined error, are you sure that you applied migrations to this application?
python manage.py makemigrations APP_NAME
python manage.py sqlmigrate APP_NAME 0001
python manage.py migrate
Next, in your models file:
timestamp = models.DateField(("Date"), default=datetime.date.today)
When I looked up Django's model field reference, I found this:
class DateField(auto_now=False, auto_now_add=False, **options)
After reviewing your needs, will it help when you switch auto_now_add to True? I'm doubtful that default= will work in every circumstance. https://docs.djangoproject.com/en/3.0/ref/models/fields/#datefield
As a side note, when you create an object in the admin dashboard, sometimes Django will mischeck field requirements (like creating superusers), so please do watch out those objects in the management site.

Linking button to new page in Django not working

I have created an update view and am trying to link it to my form
but the button linking doesn't seem to be working at all
urls.py
path('uploadupdate/<int:upload_id>', UploadUpdate.as_view(), name='uploadupdate'),
template:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Manage uploads</title>
<link rel="stylesheet" href="{% static 'studyadmin/manageuploads_css.css' %}">
</head>
<body>
<table >
<tr class="main_row">
<th> Upload Name </th>
<th> Author Name </th>
<th> Type </th>
<th> Date </th>
<th> Edit </th>
<th>Edit Tags</th>
</tr>
<form >
{% csrf_token %}
{% for uploads in uploads %} <!-- shows all contents -->
<tr>
<th> {{ uploads.title}} </th>
<th> {{ uploads.author }} </th>
<th> {{ uploads.upload_type }} </th>
<th> {{ uploads.date_posted|date:"d M, Y" }} </th>
<th> <button href="{% url 'uploadupdate' uploads.upload_id %}" type="submit" class="edit" formmethod="POST">Edit</button> </th>
<th> <button href="#" type="submit" class="edittags" formmethod="POST" >Edit tags</button> </th>
{% endfor %}
</form>
</table>
</body>
</html>
views.py
class UploadUpdate(UpdateView):
form_class = UploadEditForm
template_name = 'studyadmin/upload_update_form.html'
queryset = Uploads.objects.all()
def get_object(self, queryset=None):
obj = Uploads.objects.get(upload_id=self.kwargs['upload_id'])
print(obj)
return obj
def form_valid(self, form):
upload = form.save(commit=False)
upload.save()
return redirect('/manageupload/')
I added the relevant code, I feel like its a small error but I can't seem to identify it since I'm very new to Django, any help would be appreciated!
You should refer to your app to use that URL because Django doesn't know to which app your URL name belongs to by default. So it'd be something like <button href="{% url 'appname:uploadupdate' uploads.upload_id %}" type="submit" class="edit" formmethod="POST">Edit</button>. Of course make sure that your project's URL Configuration includes your app's URLs. Hope it helps.
UPDATE
From the Django Documentation:
...
class ContactView(FormView):
template_name = 'contact.html'
form_class = ContactForm
success_url = '/thanks/'
def form_valid(self, form):
form.send_email()
return super().form_valid(form)
Notes:
FormView inherits TemplateResponseMixin so template_name can be used here.
The default implementation for form_valid() simply redirects to the success_url.
So you should edit your View.
dont do this in your forms , Use it for getting the Fields from the models and the view allows you to connect your forms directly with your page you can directly print our data in a page so there is an example :
My models i have Question and ansewer attribute :
------ models.py ------
class Question_cours(models.Model):
quest = models.CharField(max_length= 200 ) ---> question
rep = models.CharField(max_length = 20) ----> answer
--------- forms.py --------
class Form_question(forms.Form): /// important to make the same name fields
quest = forms.CharField()
rep = forms.CharField()
-------- view.py ----------
#-----------------------------------------------------------------------------
def add_question_cours(request):
form = Form_question()
if request.method == "POST":
form = Form_question(request.POST)
if form.is_valid() :
Question_cours.objects.create(**form.cleaned_data)
else :
print(form.errors)
return render(request , 'bootstrap/add_question.html',context)
#------------------------------------------------------------------------------
-----------urls.py------------
path('dfsdf',views.add_question_cours,name='add_question')
-----------------add_question.html----------
<form method="POST">{% csrf_token %}
<div class ="form-group">
{{ form.as_p}}
</div>
<button type =" submit" class="btn btn-danger ">
<i class ="fa fa-plus"></i>
</button>
for more information
https://youtu.be/uz5gyXemak0

Django: can "double" 'render_to_response' be unified into only one view?

I have defined two functions in views.py to obtain first prova.html with certain elementimenu and then, after clicking over one of them, I obtain again the page with elementimenu and elementi associated to elementimenu with the same id i.e.:
another_app.model.py
...
class ElementiTab(models.Model):
author = models.ForeignKey('auth.User', null=True, blank=False)
des = models.CharField(max_length=30)
x = models.FloatField()
y = models.FloatField()
res = models.FloatField(default=0)
created_date = models.DateTimeField(default=timezone.now)
...
And here the code that I like to get better:
views.py
from another_app.model import ElementiTab
def show_elementi(request):
elementimenu = ElementiTab.objects.all()
return render_to_response('homepage/prova.html',{'elementimenu': elementimenu, 'user.username': request}, context_instance = RequestContext(request))
def show_detail(request,id):
elementimenu = ElementiTab.objects.all()
detail = get_object_or_404(ElementiTab, pk=id)
return render_to_response('homepage/prova.html',{'elementimenu': elementimenu, 'detail': detail, 'user.username': request}, context_instance = RequestContext(request))
urls.py
...
url(r'^homepage/prova/$', views.show_elementi),
url(r'^show_detail/(?P<id>\d+)/$', views.show_detail),
...
prova.html
...
<div class="elementi">
{% for elementi in elementimenu %}
{{elementi.des}}
{% endfor %}
</div>
<div class="table-responsive">
<table class="table table-bordered">
<tr class="info">
<td width="35%" align="center"> NOME</td>
<td width="35%" align="center"> DATA CREAZIONE </td>
<td width="30%" align="center"> AUTORE </td>
</tr>
{% if detail %}
<div class="dettagli">
<tr>
<td>{{detail.des}}</td>
<td>{{detail.created_date}}</td>
<td>{{detail.author}}</td>
</tr>
{% endif %}
</div>
</table>
</div>
...
I had used this "trick" in show_detail view so that I can see elementimenu even after calling this function.
Is there a more elegant way to do this?
Yes, you can use the single view. Add the default None value for the id (or pk) argument:
def show_elementi(request, pk=None):
elementimenu = ElementiTab.objects.all()
detail = get_object_or_404(ElementiTab, pk=pk) if pk else None
return render(request, 'homepage/prova.html',
{'elementimenu': elementimenu, 'detail': detail})
And then map both urls to this view:
url(r'^homepage/prova/$', views.show_elementi),
url(r'^show_detail/(?P<pk>\d+)/$', views.show_elementi),

How can I take input from a text field in a Django page then update a SQL table with the response?

I am working on a site that will be used to clean up inactive Tableau workbooks. Logging into this site will allow my users to see their old workbooks and decide which ones to keep.
This is going to be accomplished by taking some simple text input from an HTML page, K for keep | D for delete.
The response from the user will then be stored as a Python variable that will go into an if then statement. The if then statement will basically update each row in SQL, adding either K or D to a column called "Marked_for_Deletion".
From there, a stored procedure will run, check that column, and delete all things marked with a D.
Is this feasible? If so, how would I go about pulling that input and making sure it gets added to the right column/row? If not, can you offer any suggestions on a substitute method I can use?
Thanks!
Edit: Here is the code for my table.
<table class="blueTable">
<thead>
<tr>
<th>Workbook Name</th>
<th>Deletion Deadline</th>
<th>Keep or Delete?</th>
</tr>
</thead>
<tbody>
{% for book in Workbooks %}
<tr>
<td>{{ book.name }}</td>
<td>{{ book.owner_name }}</td>
<td>
<label class="container" style="margin-bottom: 25px">
<input type="text" placeholder="(Enter K for Keep, D for Delete)">
</label>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<form method="post">
{% csrf_token %}
<button type="submit" name="run_script">Submit</button>
</form>
</body>
</html>
I want to be able to pull the input from the last td tag and store it with the submit button below there.
I'm kind of late, but I hope it helps you out.
urls.py
from django.urls import path
from workbook_app import views
app_name = 'workbook_app'
urlpatterns = [
path('books/', views.BookListView.as_view(), name='books'),
path('keep_or_delete/<int:pk>/', views.KeepOrDeleteView.as_view(), name='keep_or_delete'),
]
models.py
from django.db import models
class Book(models.Model):
name = models.CharField(max_length=250)
owner_name = models.CharField(max_length=250)
marked_for_deletion = models.BooleanField(default=False)
views.py
from django.views.generic import ListView
from workbook_app.models import Book
from django.http import HttpResponse, HttpResponseRedirect
from django.views import View
from django.urls import reverse
class BookListView(ListView):
template_name = 'workbook_app/books.html'
def get_queryset(self):
return Book.objects.all()
class KeepOrDeleteView(View):
def post(self, request, pk):
book = Book.objects.get(pk=pk)
print(book, book.marked_for_deletion, not book.marked_for_deletion)
book.marked_for_deletion = not book.marked_for_deletion
book.save()
url = reverse('workbook_app:books')
return HttpResponseRedirect(url)
books.html
<div class="container">
<h2>Books</h2>
<table class="table">
<tr>
<th>Workbook Name</th>
<th>Deletion Deadline</th>
<th>Keep or Delete?</th>
</tr>
{% for book in object_list %}
<tr>
<td>{{book.name}}</td>
<td>{{book.owner_name}}</td>
<td>
<form action="{% url 'workbook_app:keep_or_delete' pk=book.pk %}" method="POST">
{% csrf_token %}
<button type="submit" class="btn btn-{%if book.marked_for_deletion %}primary{% else%}danger{% endif %}">{%if book.marked_for_deletion %}Keep{% else%}Delete{% endif %}</button>
</form>
</td>
</tr>
{%endfor%}
</table>
P.S. I'm not handling exceptions, messages, etc. You're just gonna have to figure it out yourself or open a new question.