I am trying to record the creation time, date of input data into a SQLite in Django in the format Jan 1, 2021, 8:21 a.m.. So far I can get the time to work doing the following in models.py:
class Listing(models.Model):
time = models.TimeField(auto_now_add=True)
date = models.DateField()
def __str__(self):
return f"({ ({self.time}))"
with my html:
{% block body %}
<div>
<p> Started: {{listing.date}},{{listing.time}}</p>
</div>
{% endblock %}
My views.py [note I've removed some additional that does not have to do with this question]:
def listing(request, name):
listing = Listina.objects.get(listingTitle=name)
return render(request, "auctions/listing.html", {
"listing": listing,
})
I get the following error:
Exception Type: OperationalError at /
Exception Value: no such column: auctions_listing.date
So I'm assuming it's because date in Listing is null. How can I fix this?
I just made the field to null = true:
class Listing(models.Model):
time = models.TimeField(auto_now_add=True)
date = models.DateField(null = true)
def __str__(self):
return f"({ ({self.time}))"
Then ran makemigrations and migrate
Related
I have a model with 2 fields for numbers. I am trying to query those numbers and append them to each others. How do I do that? How do I work with queried objects?
This is Model
class Post(models.Model):
title = models.CharField(max_length=100)
num1 = models.IntegerField(blank=True,default=0)
num2 = models.IntegerField(blank=True,default=0)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('diary:post-detail', kwargs={'pk': self.pk})
This is view (here I am trying to query and work with queried objects)
def home(request):
a = Post.objects.values('num1')
b = Post.objects.values('num2')
result = a + b
context = {
'result': result,
}
return render(request, 'diary/home.html', context)
This is a working part of my template
{% for x in result %}
<p> {{ x }} </p>
{% endfor %}
This is the error I get
TypeError at /
unsupported operand type(s) for +: 'QuerySet' and 'QuerySet'
C:\Users\detal\Coding\Trading Diary3\TradingDiary\diary\views.py, line 11, in home
result = a + b
The return of your query will be dictionary. To add both query's you can try
result = q.union(b)
for a much more cleaner look
records = query1 | query2
If you don't want duplicates, then add .distinct()
records = (query1 | query2).distinct()
if you want specific field only you can try
Post.objects.all().values_list(
"num2").union(Post1.objects.all().values_list("num1"))
or if it is from same table
Post1.objects.all().values_list("num1","num2"))
I solved it. Here's my view code:
def home(request):
x = Post.objects.all().values_list("num1","num2")
array = []
for i in x:
y = i[0] + i[1]
array.append(y)
context = {
'posts': Post.objects.all(),
'array':array,
}
return render(request, 'diary/home.html', context)
and template code:
{% for i in array %}
<p> {{ i }} </p>
{% endfor %}
The output is the list of appended numbers of num1 and num2. There was also problem for me while solving - you don't need to "return" the for loop result in views. It works only without it
I have a Django model with a FloatField, which I later base a form on. For some reason I get "'float' object has no attribute 'as_tuple'", and unfortunately I have no idea why do I get this error or how to fix it.
models.py:
class Course(models.Model):
title = models.CharField(max_length = 200)
author = models.ForeignKey(User,default=None, on_delete=models.SET_DEFAULT)
description = models.TextField(max_length=1000, blank=True)
tags = models.TextField(blank = True)
duration = models.FloatField(validators=(MinValueValidator(0.1),MaxValueValidator(12), DecimalValidator(max_digits=3,decimal_places=2)))
def __str__(self):
return self.title
forms.py:
class CourseForm(ModelForm):
class Meta:
model = Course
fields = ('title', 'description', 'price', 'duration', 'tags')
views.py:
#login_required
def create_course(request):
if request.method == "POST":
form = CourseForm(request.POST)
if form.is_valid():
form.save()
messages.info(request, f"Course created succesfully!")
else:
messages.error(request, "Something went wrong, please resubmit!")
form = CourseForm()
return render(request, "main/createcourse.html", {"form": form})
html:
{% extends 'main/header.html' %}
<body>
{% block content%}
<div class="container">
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<br>
<button class="btn" type="submit">Create</button>
</form>
If you to modify an existing course, click <strong>here</strong> instead.
</div>
<br><br>
{% endblock %}
</body>
If you really need to use a FloatField, then you need to write your own validator:
def validate_decimals(value):
s = str(value)
d = decimal.Decimal(s)
if abs(d.as_tuple().exponent) > 2:
raise ValidationError(
_('%(value)s has more than 2 decimals. Please enter 2 decimals only.'),
params={'value': value},
)
Then, you add validators='validate_decimals' when you declare the FloatField.
Note that a float value cannot directly be converted to decimal. It should first be converted to string and then to decimal. See also:
Python float to Decimal conversion
There is a difference between a float and a Decimal. A Decimal encodes the data by storing the digits of a decimal number. You can however not perform DecimalValidation on a float, since due to rounding errors, it will add extra digits.
You thus can use a DecimalField [Django-doc] instead. Note that you thus need to pass Decimal objects in that case, not floats.
class Course(models.Model):
title = models.CharField(max_length = 200)
author = models.ForeignKey(User,default=None, on_delete=models.SET_DEFAULT)
description = models.TextField(max_length=1000, blank=True)
tags = models.TextField(blank = True)
duration = models.DecimalField(max_digits=3,decimal_places=2, validators=(MinValueValidator(0.1),MaxValueValidator(12), DecimalValidator(max_digits=3,decimal_places=2)))
def __str__(self):
return self.title
You might want to take a look at the DurationField [Django-doc] to store duration however, this will automatically use a timedelta, and store it as an integer for databases that do not support such types.
I'm having some trouble displaying data from my database on the template in django
model:
class CityInfo (models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=200)
landmark_type = models.CharField(blank=True, max_length=30)
business = 'Business'
student = 'Student'
tourist = 'Tourist'
def __str__(self):
return self.name
relevant view:
def itemget(request):
data=CityInfo.objects.all()
return render(request,'CityApp/infopage.html', {'data': data})
relevant url:
url(r'itemget/$',views.itemget,{'template_name': 'CityApp/info_page.html'},name='itemget'),
infopage.html:
<ul>
{% for item in data %}
<li>
<h1>{{ item.name }}</h1>
</li>
{% endfor %}
<ul>
The above html results in a blank list and I have no idea why.
Try changing views.py to the following:
def itemget(request):
data = CityInfo.objects.all()
context={
'data': data
}
return render(request, "CityApp/infopage.html", context)
Try this :
def __str__(self):
return "%s" % self.name
I'm not sure because I'm on my old smartphone.
Otherwise, your def __str__ is well indented in your class ?
Are you using Python 2 or Python 3 ? str if for Python 3. Else you have to use __unicode__
EDIT :
From you urls.py file, you have :
url(r'itemget/$',views.itemget,{'template_name': 'CityApp/info_page.html'},name='itemget'),
Remove your template_name part which is already in your view and don't forget to add ^ before itemget
url(r'^itemget/$',views.itemget ,name='itemget'),
I have created a model 'VehicleDetails' in which a user can fill the details of a vehicle and another model 'TripStatus' in which he can update the vehicle location. I wanted to get the latest location for which I did as in my below code. But when i running the server, it returns all the values not the latest value. I would appreciate helping me solve this or suggesting a new approach.
models.py:
class VehicleDetails(models.Model):
Vehicle_No = models.CharField(max_length=20)
class TripStatus(models.Model):
vehicledetails = models.ForeignKey(VehicleDetails, related_name='tripstatuss')
CHOICES = (('Yet to start', 'Yet to start'),('Trip starts', 'Trip starts'), ('Chennai','Chennai'), ('Vizag', 'Vizag'), ('Kolkata', 'Kolkata'))
Vehicle_Status = models.CharField(choices=CHOICES, default="Yet to start", max_length=20)
statustime = models.DateTimeField(auto_now=False, auto_now_add=True)
views:
def status(request):
tripstatus = TripStatus.objects.all().latest('statustime')
context = {
"tripstatus": tripstatus,
}
return render(request, 'loggedin_load/active_deals.html', context)
template:
{% for status in vehicledetails.tripstatuss.all %}
{{status.Vehicle_Status}}
{% endfor %}
Should just have to remove the .all():
tripstatus = TripStatus.objects.latest('statustime')
Or maybe:
tripstatus = TripStatus.order_by('-statustime').first()
Consider these Django models:
class MonitorSession(models.Model):
agent = models.ForeignKey(Agent, on_delete=models.CASCADE)
date = models.DateTimeField()
contact_motive = models.ForeignKey(ContactMotive)
customer_number = models.CharField(max_length=65)
protocole_number = models.CharField(max_length=65)
strong_points = models.TextField(blank=True)
points_to_improve = models.TextField(blank=True)
action_plan = models.TextField(blank=True)
def __unicode__(self):
return u"%s, %s" % (self.customer_number, self.protocole_number)
class EvaluationCategory(models.Model):
cel = models.ForeignKey(Cel, on_delete=models.CASCADE)
category = models.CharField(max_length=65)
description = models.TextField(blank=True)
max_points = models.IntegerField()
def __unicode__(self):
return u"%s: %s" % (self.cel, self.category)
class EvaluationItem(models.Model):
category = models.ForeignKey(EvaluationCategory, on_delete=models.CASCADE)
item = models.CharField(max_length=65)
def __unicode__(self):
return u"%s: %s" % (self.category, self.item)
class EvaluationScore(models.Model):
monitor_session = models.ForeignKey(MonitorSession, on_delete=models.CASCADE)
item = models.ForeignKey(EvaluationItem, )
score = models.ForeignKey(PossibleScore, on_delete=models.CASCADE)
def __unicode__(self):
return u"%s: %s" % (self.item, self.score)
Now I need to create a form to with these all the fields from the MonitorSession class.
After those fields I would need to create additional form fields which are dynamic, and would be returning from this query:
fields = EvaluationItem.objects.all().order_by(EvaluationCategory__category)
As you can Imagine the number of fields is not known and is dynamic.
Is there an automated way in Django to get this done? Ar will I have to create the form manually and for the Item fields a loop? I have been trying to get this done with Formsets but I do not see how formsets could help me in this.
The above suggestion is giving me part of the solution: This would be the code of my Form:
class MonitorSessionForm(forms.Form):
agent = forms.ModelChoiceField(queryset=Agent.objects.all())
date = forms.DateField()
contact_motive =forms.ModelChoiceField(queryset=ContactMotive.objects.all())
customer_number = forms.CharField(max_length=65)
protocole_number = forms.CharField(max_length=65)
strong_points = forms.CharField(widget=forms.Textarea)
points_to_improve = forms.CharField(widget=forms.Textarea)
action_plan = forms.CharField(widget=forms.Textarea)
def __init__(self, *args, **kwargs):
extra = kwargs.pop('extra')
super(MonitorSessionForm, self).__init__(*args, **kwargs)
for i, item in enumerate(extra):
self.fields['custum_%s' % i] = forms.CharField(label=item)
My template code:
{% load bootstrap3 %}
<h2>Fazer Monitoria</h2>
<div class="col-md-6">
<form method="post" action="">
{% csrf_token %}
{% bootstrap_form form %}
<br><br>
<input type="submit" name="submit" value="Salvar Monitoria" class="btn btn-primary">
</form>
<br><br>
</div>
And my View code:
#login_required()
def add_monitorsession(request):
items = EvaluationItem.objects.all()
if request.method == 'POST':
form = MonitorSessionForm(request.POST, extra=items)
if form.is_valid():
print u'Tudo ok!'
else:
form = MonitorSessionForm
return render_to_response('add_monitorsession.html', {'form': form})
Trying to render this is giving me a key error:
KeyError at /addmonitorsession/
'extra'
Request Method: GET
Request URL: http://127.0.0.1:8000/addmonitorsession/
Django Version: 1.9.6
Exception Type: KeyError
Exception Value:
'extra'
Exception Location: ..../monitoria_altocontato/main/forms/monitor_session.py in __init__, line 19
pointing out to the next line of the form
extra = kwargs.pop('extra')
Any one an idea?