I am new to Django. I have a model with a field that records the time a new entry is made and I want to display the times new entries are posted in the user's timezone. The time is recorded in UTC.
So far I haven't been able to get this to work. I suspect I need to pass something additional info via the view but I haven't been able to figure this out.
settings.py:
TIME_ZONE = 'UTC'
USE_TZ = True
model:
from django.db import models
from accounts.models import CustomUser
from tinymce import models as tinymce_models
class CompanyAnnouncement(models.Model):
title = models.CharField(max_length= 200)
author = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
body = tinymce_models.HTMLField()
date = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.title
view:
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, FormMixin
from django.urls.base import reverse
from .models import CompanyAnnouncement
from django.utils import timezone
class CompanyAnnouncementList(ListView):
model = CompanyAnnouncement
template_name = 'company_accounts/announcements.html'
ordering = ['-date']
template:
{% extends 'base.html' %}
{% load tz %}
{% block content %}
<div class="section-container container">
{% for post in object_list %}
<div class ="announcements-entry">
<h2>{{ post.title }}</h2>
<h3>made on {{ post.date }}</h3>
{% localtime on %}
{{ post.date }}
{% endlocaltime %}
<p>{{ post.body | safe }}</p>
</div>
{% endfor %}
</div>
{% endblock content %}
Here is an example of what is being stored in the database: 2022-03-12 19:54:28
Related
I was trying to display a list of items on the front end of a project using Django. I successfully did it and could see the objects in a list upon spinning up the server. But as soon as I used context_object_name in the views.py file, and then check the page, the objects are not appearing. Also, there is no error shown in the terminal and the docker logs too.
Here's my Views.py file
from django.shortcuts import render
from django.views.generic import ListView
from .models import Book
# Create your views here.
class BookListView(ListView):
model = Book
context_object_name = 'book_list'
template_name = 'books/book_list.html'
Here's the models.py file
from django.db import models
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
return self.title
Here's the book_list.html file
<!--templates/books/book_list.html-->
{% extends '_base.html' %}
{% block title %}Books{% endblock title %}
{% block content %}
{% for book in book_list %}
<div>
<h2>{{ object.title }}</h2>
</div>
{% endfor %}
{% endblock content %}
small mistake in book_list.html. object.title to replace book.title
<h2>{{ book.title }}</h2>
I am attempting to display .pdfs that have been uploaded by users. I can display the path to the pdf but not document itself. I attempted to use "" in the template but this is not working.
At least one issue is that the incorrect path to the document is used when the template is rendered. The correct file path is media/company1/documents/012022/document.pdf. The file path rendered in the template is: /documents/document/4/documents/012022/document.pd
Here is my model:
from django.db import models
from constrainedfilefield.fields import ConstrainedFileField
class Document(models.Model):
title = models.CharField(max_length= 200)
description = models.TextField()
file = ConstrainedFileField(
null=True,
blank=True,
upload_to='documents/%m%Y',
content_types=['application/pdf'],
max_upload_size=2097152,
)
Here is my view:
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import ListView, DetailView, CreateView
from .models import Document
...
class CompanyDocumentsDetailView(DetailView):
model = Document
template_name = 'company_accounts/document_detail.html'
...
Here is my template:
<!-- templates/document_detail.html -->
{% extends 'base.html' %}
{% block content %}
<div class="section-container container">
<div class="project-entry">
<h2>{{ document.title }}</h2>
<p>{{ document.description }}</p>
<p><embed src="{{document.file}}" type="application/pdf" height="700px" width="500"/></p>
</div>
</div>
{% endblock content %}
I'm writing a code in django framework for a sales website and the number of available pieces of a certain merchandise is limited.
to obtain the number of remaining products I have to call a certain function.
Now I wanted to ask if there's any way to call this function in the models.py or forms.py modules or any other way to set this limit.
This is my view module:
from django.http.response import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from .forms import orderForm
from regpage.models import User
from django.views import View
class orderView(View):
def get(self, request):
form = orderForm()
return render(request, "dashboard/order.html", {'form': form,})
This is my forms module:
from django import forms
from .models import Order
class orderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['productCount']
This is my models module:
from django.db import models
from django.db.models.enums import Choices
from regpage.models import User
from django.core import validators
from django.core.validators import EmailValidator, MaxValueValidator, MinValueValidator
class Order(models.Model):
userID = models.ForeignKey(User, on_delete=models.CASCADE)
productCount = models.PositiveSmallIntegerField() #THE LIMITED FIELD
This is my html file:
{% extends 'dashboard.html' %}
{% block dashTitle %}
Order
{% endblock dashTitle %}
{% block dashContent %}
<p style="text-align:center;font-size:30px;"><b> Order Page </b> </p>
<form style="text-align:center;font-size:25px" method="POST">
{% csrf_token %}
{% for field in form %}
<div class="form-control {% if field.errors %}errors{% endif %}">
{{ field.label_tag }}
{{ field }}
{{ field.errors }}
</div>
<br>
{% endfor %}
<br>
<button type="submit">Order</button>
</form>
{% endblock dashContent %}
There's only one product in this website and one function should be called to obtain the number of remaining products.
Give this a try
class orderForm(forms.ModelForm):
quantity = forms.IntegerField(widget=forms.TextInput(
attrs={
'min':0,
'value':0,
'type':'number',
}))
class Meta:
model = Order
fields = ('__all__')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['productCount'].widget.attrs.update(
{'max': self.instance.productCount},
)
I am very new in Django. Not sure whether this is a bug or an error.
Here is my model in an app called gcbv (for generic class-based view)
from django.db import models
from core.models import TimeStampModel
from django.urls import reverse
# Create your models here.
class Vehicle(TimeStampModel):
maker = models.CharField(max_length=100)
model_year = models.IntegerField()
vehicle_type = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True)
vehicle_model = models.CharField(max_length=100)
website = models.URLField(max_length=100, blank=True)
email = models.EmailField(max_length=100, blank=True)
notes = models.TextField(blank=True, default='')
def __str__(self):
x = self.maker + ' ' + self.vehicle_model
return x
And here are the URLs:
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from . import views
from django.urls import reverse
#from django.views.generic.base import TemplateView
app_name = 'gcbv'
urlpatterns = [
path('sub1/', views.SubView.as_view(), name='sub1'),
path('vehicle_list/', views.VehicleListView.as_view(),
name = 'vehicle_list'),
path('vehicle/<str:slug>/',
views.VehicleDetailView.as_view(),
name='vehicle_detail'),
path('vehicle/create', views.VehicleCreateView.as_view(),
name='vehicle_create'),
path('', views.IndexTemplateView.as_view(), name='index'),
]
And here is the relevant view:
class VehicleCreateView(CreateView):
model = Vehicle
fields = ['maker', 'model_year', 'vehicle_type', 'slug',
'vehicle_model', 'website', 'email', 'notes']
labels = {'maker':'Maker', 'model_year':'Year',
'vehicle_type':'Type', 'vehicle_model':'Model',
'website':'Website', 'email':'Email', 'notes':'Notes'}
Here is the template:
{% extends "core/base.html" %}
{% block body_block %}
<h1>Vehicle Create for GCBV</h1>
<form action="POST" action="">
{% csrf_token %}
{{ form.as_p }}
<button name="submit" class="btn btn-primary">Submit</button>
</form>
<h1>End Vehicle Create for GCBV</h1>
{% endblock %}
It looks as if the data aren't saved in the database, but when i'm adding the same data by hand directly in the admin page, everything works fine. I've attached another screenshot showing that VehicleDetailView has found the relevant template and rendered the information.
Any help would be greatly appreciated.
NB: Everything worked fine when I use function views and regex instead of path.
Form
After submit
List
Details
OK, this is what we septuagenarians call a "senior moment". I have been staring at this code for two days and did not see the obvious.
method="POST"!
NOT
action="POST"
Many, many thanks
In the fourth line of your template, method should be equal to "post"
{% extends "core/base.html" %}
{% block body_block %}
<h1>Vehicle Create for GCBV</h1>
<form method="POST" action="">
{% csrf_token %}
{{ form.as_p }}
<button name="submit" class="btn btn-primary">Submit</button>
</form>
<h1>End Vehicle Create for GCBV</h1>
{% endblock %}
This question already has an answer here:
Why doesn't save() automatically call save_m2m()?
(1 answer)
Closed 6 years ago.
I'm trying to create a Debt model using Django. It has a debtors field which link a debt to many users.
It behaves the way I want through Django's administration panel, but I can't get it to work using a django form. I can create debts but the the debtors field is emptying, despite the browser showing an accurate list of users to choose from.
What's even more surprising is that I thought that using blank=False in the model definition shouldn't allow that.
models.py:
from django.db import models
from django.utils import timezone
class Debt(models.Model):
author = models.ForeignKey('auth.User', related_name='author')
name = models.CharField(max_length=200)
amount = models.FloatField()
debtors = models.ManyToManyField('auth.User', blank=False)
invoice = models.FileField(blank=True)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.name
forms.py:
from django import forms
from .models import Debt
class NewDebtForm(forms.ModelForm):
class Meta:
model = Debt
fields = ('name', 'amount', 'invoice', 'created_date', 'debtors')
views.py:
from django.shortcuts import render, redirect
from .models import Debt
from .forms import NewDebtForm
def debt_list(request):
if request.method == "POST":
form = NewDebtForm(request.POST)
if form.is_valid():
debt = form.save(commit=False)
debt.author = request.user
debt.save()
debts = Debt.objects.order_by('created_date')
form = NewDebtForm()
return render(request, 'debt_share/debt_list.html',
{'debts': debts,
'form': form})
debt_list.html:
{% extends 'debt_share/base.html' %}
{% block content %}
{% for debt in debts %}
<h1>{{ debt.name }}</h1>
<h2>payƩ par {{ debt.author }}</h2>
<h2>{{ debt.amount }} {{ debt.invoice }}</h2>
<p>
Concerne
{% for user in debt.debtors.all %}
{{ user }}
{% endfor %}
</p>
{% endfor %}
<form method="POST">{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
{% endblock content %}
When using ModelForms for many-to-many relationships, and use form.save(commit=False), you have to also call form.save_m2m(). Many-to-many relationships have to be saved in a second step, after the original object has been created; otherwise, its ID would not be known.
For more details, refer to the explanation in the docs: https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#the-save-method