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 %}
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 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
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 %}
I'm new in Django, I researched how to create drop-down. I tried everything, but still, the dropdown is not showing in HTML view.
My sample script is this.
This is the model.py
from django.db import models
class samplemodel(models.Model):
list = (
('sample1','SAMPLE1'),
('sample2','SAMPLE2'),
)
list_choices = models.CharField(max_length=6, choices=list)
The forms.py
from .models import samplemodel
from django.forms import ModelForm
class sampleForm(ModelForm):
class Meta:
model = samplemodel
fields = ['list_choices']
This is the views.py
from django.shortcuts import render
from .models import samplemodel
from .forms import sampleForm
from django.views.generic import CreateView
class sampleView(CreateView):
model = samplemodel
form_class = sampleForm
template_name = 'home/sample.html'
This is the home.html
{% extends 'base.html' %}
{% block head %}
<title>Home</title>
{% endblock %}
{% block body %}
<div class="container">
<form class="post">
{% csrf_token %}
{{ form.as_p }}
</form>
</div>
{% endblock %}
I tried everything that I saw on the internet. But I can't still show the drop-down. I don't know if the imports are the issue or not.
you model should be like this
from django.db import models
class SampleModel(models.Model):
list = (
('sample1','SAMPLE1'),
('sample2','SAMPLE2'),
)
list_choices = models.CharField(max_length=6, choices=list)
in your urlconf
from django.views.generic import CreateView
from app.models import Samplemodel
from django.forms import ModelForm
url(r'^sample_form$',CreateView.as_view(model=SampleModel, template_name='home/sample.html', success_url='index', name='sample_form'))
thats all you don't need forms.py . django will take care of everything