why is my pdf not showing in django template? - django

I am trying to display a pdf file in an html template and also be able to update that pdf file, I read the tutorials on how to display a pdf file but I'm not sure why mine isn't really working, I have a model called Reference
class References(models.Model):
REFERENCE_MATERIAL = (
('seating', 'Seating Plan'),
('organization', 'Organization Chart')
)
# the variable associated with the reference
reference_name = models.CharField(max_length=100, choices=REFERENCE_MATERIAL,)
reference_file = models.FileField(null=True, blank=True, upload_to='references/')
date_updated = models.DateField(auto_now=True)
# on submit click of update entry page, it redirects to the url below.
def get_absolute_url(self):
return reverse('references-home')
Here are the views to update a reference and the one that displays it
class SeatingReferenceView(generic.ListView):
context_object_name = 'seating_plan'
template_name = 'catalog/references-seating.html'
def get_queryset(self):
return References.objects.filter(reference_name='seating').order_by('date_updated').first()
def reference_update(request):
if request.method == 'POST':
form = UploadReference(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('references-home')
else:
form = UploadReference()
return render(request, 'catalog/references_update.html', {'form': form,})
Here is my template
<div class="container maintenance-container">
<div class="row" >
<div class="maintenance-title">
<h1 class="mainrow">Seating Plan</h1>
<h4 class="maintenance-under">Seating Plan for Kitchener Floor 1</h4>
</div>
</div>
<div class="row">
{% if seating_plan %}
<div class="col-lg-12">
{{ seating_plan.read }}
</div>
{% else %}
<div class="col-lg-12">
<div class="mainpanelcontent">
<h4>There are no seating plans to display</h4>
</div>
</div>
{% endif %}
</div>
</div>
{% endblock %}
However I'm receiving nothing in my html template, I am storing my files in a folder under /media/references, I can see the files are in there currently and I can see in my database that under the reference_file column that there are files called seatingplan.pdf but still nothing is showing. Thank you !

Related

Processing a Django form

I have a problem using Django forms while learning Django and adapting code from a variety of online courses and examples. As a result, the code may be “messy” – but if I can get it to work the way I need, I can improve my coding style later.
I wish to display a template that contains a form. Some of the data displayed in the page rendered in the template is read from one table/model, polls_CC_Questions, and I wish to write data input in the page into a related table, polls_CC_Resp_NoFK.
The models used are:
class CC_Questions(models.Model):
q_text = models.CharField('Question text', max_length=200)
C1_Type = models.CharField('Choice 1 Type', max_length=2)
Choice1_text = models.CharField('Choice 1 text', max_length=100)
C2_Type = models.CharField('Choice 2 Type', max_length=2)
Choice2_text = models.CharField('Choice 2 text', max_length=100)
#
def __str__(self):
return self.q_text[:20]
class CC_Resp_NoFK(models.Model):
Person_ID = models.IntegerField()
Test_date = models.DateTimeField('date test taken')
Q_ID = models.IntegerField()
Response_value = models.IntegerField(default=0,
validators=[MaxValueValidator(100), MinValueValidator(-100)])
#
def __str__(self):
return self.Person_ID
Now I can display the template containing valid data when I enter the url:
http://localhost:8000/polls/p2vote/4/
This is processed in urls.py
app_name = 'polls'
urlpatterns = [
…..
……
# ex: /polls/p2vote/<q_id>
path('p2vote/<int:q_id>/', p2_views.p2vote, name='p2vote'),
…..
The views.py entry that is used:
def p2vote(request,q_id):
#next line has been copied from CC_quest view to GET Question data
CC_question = get_object_or_404(CC_Questions, pk=q_id)
#
if request.method == 'POST':
form = VoteForm(request.POST)
if form.is_valid():
form.save()
return redirect('/polls/p2')
else:
formV = VoteForm()
#context = {'form' : formV}
return render(request, 'pollapp2/vote.html', {'var_name':CC_question,'form' : VoteForm()})
in forms.py
class VoteForm(forms.ModelForm):
class Meta:
model = CC_Resp_NoFK
fields = ['Person_ID', 'Test_date', 'Q_ID','Response_value']
The template launched, uses data from the polls_CC_Questions model/table to create the labels of the input field. This works fine so my displayed page
http://localhost:8000/polls/p2vote/5/
Displays data from the CC_Questions table, “carried in the variable varname” what the questions and their choices are. For example, the template displays the contents of {{ var_name.q_text }} and {{ var_name.Choice1_text }} , see below
Also, the page displayed containing the ModelForm is correctly displayed with labels. The template used :
<!-- vote.html based on create.html -->
<!-- 2022-02-17
Change text on page
Extracted data from CC_Question record passed as varname
-->
{% extends "pollapp2/base.html" %}
<!-- load widget tools to give me more control over layout of form in template -->
{% load widget_tweaks %}
<!-- block Title is the name in the tab -->
{% block title %}Vote on Question{% endblock %}
{% block main %}
<div class="row">
<div class="col-lg-10 col-lg-offset-2">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Select one from two choices</h3>
</div>
<form method="POST">
{% csrf_token %}
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<label for="question">Question to answer</label>
{{ var_name.q_text }}
</div>
</div>
</div>
<div class="row">
<div class="col-lg-5">
<div class="form-group">
<label for="Choice1_text ">Choice 1</label>
{{ var_name.Choice1_text }}
</div>
</div>
<div class="col-lg-5">
<div class="form-group">
<label for="option2">Choice 2</label>
{{ var_name.Choice2_text }}
</div>
</div>
</div>
<!-- Attempt at Input fields follow -->
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<label for="Person_id">Person ID</label>
{% render_field form.Person_ID rows="1" class="form-control" %}<br>
<label for="Test_date">Test Date</label>
{% render_field form.Test_date rows="1" class="form-control" %}<br>
<label for="Q_ID">Question ID</label>
{% render_field form.Q_ID rows="1" class="form-control" %} <br>
<label for="Response_value">Response value</label>
{% render_field form.Response_value rows="1" class="form-control" %}
</div>
</div>
</div>
<div class="row">
<hr />
<div class="col-lg-4">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
To summarise. All the above “works” in the sense a page is displayed when url : http://localhost:8000/polls/p2vote/X/ is entered in the browser and “X” is the id of the question , extracting data from the model: CC_questions. Also, on the page are input boxes created by the form, VoteForm, that allow data to be entered into table/model CC_Resp_noFK.
However, what I want to do is NOT offer Q_ID as an input field in the page, but instead populate it with the value from variable {{ var_name.id }}. I can’t work out whether I need to modify the vote.html template in some way, particularly the line:
<label for="Q_ID">Question ID</label>
{% render_field form.Q_ID rows="1" class="form-control" %} << change this ??
or the view, somewhere around form.save() ??
def p2vote(request,q_id):
#next line has been copied from CC_quest view to get Question data
CC_question = get_object_or_404(CC_Questions, pk=q_id)
#
if request.method == 'POST':
form = VoteForm(request.POST)
if form.is_valid():
form.save() << Somewhere around here ??
return redirect('/polls/p2')
else:
formV = VoteForm()
#context = {'form' : formV}
# return render(request, 'pollapp2/vote.html', context)
# following return tries to send question record into vote.html template
return render(request, 'pollapp2/vote.html', {'var_name':CC_question,'form' : VoteForm()})
Step 1: Delete Q_ID from VoteForm.
class VoteForm(forms.ModelForm):
class Meta:
model = CC_Resp_NoFK
fields = ['Person_ID', 'Test_date', 'Response_value']
Step 2: Add Q_ID after check if the form is valid and before save the object.
def p2vote(request,q_id):
#next line has been copied from CC_quest view to get Question data
CC_question = get_object_or_404(CC_Questions, pk=q_id)
if request.method == 'POST':
form = VoteForm(request.POST)
if form.is_valid():
item = form.save(commit=False)
item.Q_ID = q_id
item.save()
return redirect('/polls/p2')

Django Form after redirect is empty after successfully submitting a form

I have a template called courses for the url http://127.0.0.1:8000/gradebook/courses/. This template lists existing Course objects loads the CourseForm form. The form successfully creates new objects.
If I go to the addassessment template with url http://127.0.0.1:8000/gradebook/addassessment/7/, it correctly loads the AssessmentForm. I want to submit this form and then return to the previous courses template. The AssessmentForm submits and the object is saved, but when it redirects back to the courses template, the CourseForm does not load. The courses template loads, the expect html loads correctly other than the form fields. I notice that the url for this page is still http://127.0.0.1:8000/gradebook/addassessment/7/ and not ../gradebook/courses/.
app_name = 'gradebook'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('signup/', SignUpView.as_view(), name='signup'),
path('courses/', views.courses, name='courses'),
path('classroom/', views.classroom, name='classroom'),
path('objective/<int:course_id>/', views.addobjective, name='addobjective'),
path('addassessment/<int:course_id>/', views.addassessment, name='addassessment'),
]
#urls.py project
urlpatterns = [
path('', TemplateView.as_view(template_name='home.html'), name='home'),
path('admin/', admin.site.urls),
path('gradebook/', include('gradebook.urls')),
path('gradebook/', include('django.contrib.auth.urls')),
]
#models.py
class Course(models.Model):
course_name = models.CharField(max_length=10)
class Classroom(models.Model):
classroom_name = models.CharField(max_length=10)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
class Assessment(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE)
assessment_name = models.CharField(max_length=10)
objectives = models.ManyToManyField('Objective')
class Objective(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE)
objective_name = models.CharField(max_length=10)
objective_description = models.CharField(max_length=30)
#views.py
def courses(request):
course_list = Course.objects.order_by('course_name')
context = {'course_list': course_list}
if request.method == 'POST':
details = CourseForm(request.POST)
if details.is_valid():
course = details.save(commit=False)
course.save()
form = CourseForm(None)
context['form'] = form
return render(request, "gradebook/courses.html", context)
else:
context['form'] = details
return render(request, "gradebook/courses.html", context)
else:
form = CourseForm(None)
context['form'] = form
return render(request, "gradebook/courses.html", context)
def addassessment(request, course_id):
course_list = Course.objects.order_by('course_name')
this_course = Course.objects.get(id=course_id)
objectives = Objective.objects.filter(course=this_course).order_by('objective_name')
context = {'this_course': this_course}
context['objectives'] = objectives
context['course_list'] = course_list
if request.method == 'POST':
form = AssessmentForm(request.POST)
if form.is_valid():
assess = form.save(commit=False)
# save the course that the objective belongs to
assess.course = this_course
assess.save()
form.save_m2m()
return render(request, "gradebook/courses.html", context)
else:
context['form'] = form
return render(request, "gradebook/addassessment.html", context)
else:
form = AssessmentForm(None)
form.fields["objectives"].queryset = Objective.objects.filter(course=this_course)
context['form'] = form
return render(request, "gradebook/addassessment.html", context)
#forms.py
class AssessmentForm(ModelForm):
class Meta:
model = Assessment
fields = ('assessment_name', 'objectives',)
class CourseForm(ModelForm):
class Meta:
model = Course
fields = ["course_name"]
def clean(self):
super(CourseForm, self).clean()
course_name = self.cleaned_data.get('course_name')
if course_name and Course.objects.filter(course_name__iexact=course_name).exists():
self.add_error(
'course_name', 'A course with that course name already exists.')
if len(course_name) > 10:
self.add_error(
'Your course name cannot be longer than 10 characters')
return self.cleaned_data
#courses template: course.html
<div class="container">
<div class="row">
<div class="twelve columns">
<h1>Courses</h1>
</div>
</div>
<div class="row">
<div class="col-md-12">
{% if course_list %}
<ul>
{% for course in course_list %}
<li><div class = "row">
<div class = "col-md-3">
{{ course.course_name }}
</div>
</div></li>
{% endfor %}
</ul>
{% else %}
<p>No Courses are available.</p>
{% endif %}
</div>
</div>
<div class="row">
<div class="col-md-3">
<p>Create a new course</p>
</div>
<div class="col-md-3">
<form action="{% url 'gradebook:courses' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<div class="form-group">
<button type="submit" class="btn btn-primary">
Submit
</button>
</div>
</form>
</div>
</div>
</div>
#addassessment template: addassessment.html
<div class="container">
<div class="row">
<div class="twelve columns">
<h1>{{ this_course }}</h1>
</div>
</div>
<div class="row">
<div class="col-md-3">
<p>Add an assessment to your class</p>
</div>
<div class="col-md-3">
<div class="form-group">
<form action="" method="post">
{% csrf_token %} {{ form|crispy }}
<div class="form-group">
<button type="submit" class="btn btn-secondary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
There are no error messages.
When you submit your assessment form at http://127.0.0.1:8000/gradebook/addassessment/7/ your sending a post request back to your addassessment view function to process your form which you know. The url will still be the same as a result, which is what you are seeing.
I would suggest against returning the courses template if your assessment form is valid in the way you have written
#inside addassessment view function
return render(request, "gradebook/courses.html", context)
If you are just wanting to redirect to the courses view upon successfully saving the assessment form I suggest using the redirect shortcut.
# add to your import
from django.shortcuts import render, redirect
#inside addassessment view function - replacing "return render(request, "gradebook/courses.html", context)"
return redirect(courses)
This will send your request object to the courses view function. The redirect will use a GET action instead of a post so you'll just see what you would normally at http://127.0.0.1:8000/gradebook/courses/. This will also be the url!

error saving photo in database 'NoneType' object has no attribute 'user'

I have a model with Usuario where the profile foto goes and it saves perfectly in the database, so to be able to add more images as if it were a gallery, I created another model called Gallery, I copied the same specificiation of what was already working in the model Usuario, however he is not saving the photos in the database, and I do not know where I am going wrong.
I appreciate any help.
and I need the Gallery model to receive the foreign Usuario key
Erro:
IntegrityError at /gallery-novo/
null value in column "usuario_id_id" violates not-null constraint
DETAIL: Failing row contains (3, IMG_20180622_101716179_BURST006.jpg, eu e meu amor, null).
views.py
def gallery(request):
gallery = Gallery.objects.all()
form = GalleryForm()
data = {'gallery': gallery, 'form': form}
return render(request, 'gallery.html', data)
def gallery_novo(request):
if request.method == 'POST':
form = GalleryForm(request.POST, request.FILES)
if form.is_valid():
form.save(user=request.user)
return redirect('sistema_perfil')
else:
form = GalleryForm
return render(request, 'gallery.html', {'form': form})
models.py
class Gallery(models.Model):
gallery = StdImageField( blank=False, variations={
'large': (600, 400),
'thumbnail': (100, 100, True),
'medium': (300, 200),
})
titulo = models.CharField(max_length=50, blank=False)
usuario_id = models.ForeignKey(User, on_delete=models.CASCADE, blank=False)
forms.py
class GalleryForm(forms.ModelForm):
gallery = forms.FileField(
widget=forms.ClearableFileInput(attrs={'multiple': 'True'}))
titulo = forms.CharField()
class Meta:
model = Gallery
fields = ( 'gallery', 'titulo')
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
return super(GalleryForm, self).__init__(*args, **kwargs)
def save(self, commit=True, user=None):
form = super(GalleryForm, self).save(commit=False)
form.usario_id = user
if commit:
form.save()
return form
gallery.html
{%extends 'bases/base.html' %}
{% load static %}
{% load bootstrap %}
{% load widget_tweaks %}
{% load crispy_forms_tags %}
{% block main %}
<div class="card text-white bg-primary">
<div class="card-header"><p class="card-text">
<small class="text-muted">
Home /
<a class="text-white">Cadastro</a>
</small></a></p> Cadastro de Usúario
</div>
<div class="card title ">
<div class="card-body text-secondary">
<form class="exampleone" action="{% url 'sistema_gallery_novo' %}" method="POST" enctype="multipart/form-data" id="form" name="form" validate >
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-4">
{{ form.gallery | as_crispy_field }}
</div>
<div class="form-group col-md-4">
{{ form.titulo | as_crispy_field }}
</div>
<div class="form-group col-md-4">
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block">Cadastrar</button>
</form>
</div>
</div>
</div>
{% endblock %}
{% block rightcol %}
{% include 'bases/rightcol.html' %}
{% endblock %}
{% block footer %}
{% include 'bases/footer.html' %}
{% endblock %}
urls.py
url(r'gallery/$', gallery, name='sistema_gallery'),
url(r'gallery-novo/$', gallery_novo, name='sistema_gallery_novo'),
In my opinion, you are reinventing the wheel, the django right approach is to use commit=False on save method:
def gallery_novo(request):
if request.method == 'POST':
form = GalleryForm(request.POST, request.FILES)
if form.is_valid():
my_novo_gallery = form.save(commit=False) #save no commit
my_novo_gallery.user=request.user #set user
my_novo_gallery.save() #save to db
return redirect('sistema_perfil')

Django: transfer instance across inline form to template

I have related model EntertainmentCollage with image fields and did't now how to transfer instance models to the editing form. I need to display the existing images in the editing form and have the ability to add new ones.
models.py
class Entertainment(models.Model):
main_photo = models.ImageField(upload_to = 'where/')
place = models.CharField(max_length=200)
description = models.CharField(max_length=200)
event_date = models.DateTimeField(auto_now_add=False, blank=True, null = True)
class EntertainmentCollage(models.Model):
img = models.ImageField(upload_to = 'entertainment/portfolio', blank = True)
album = models.ForeignKey(Entertainment, blank = True, null = True)
views.py
def edit_where(request, pk):
place = Entertainment.objects.get(id=pk)
FormSet2 = inlineformset_factory(Entertainment, EntertainmentCollage, fields =['img',], extra=6)
form = WhereCreateForm(instance=place)
form2 = FormSet2()
if request.user.is_authenticated():
if request.method == "POST":
form = WhereCreateForm(request.POST, request.FILES, instance=place)
if form.is_valid():
form2 = FormSet2(request.POST or None, request.FILES)
if form2.is_valid():
form.save()
form2.save()
return redirect('entertainment:where_list')
else:
form = WhereCreateForm()
form2 = FormSet2()
return render(request, "entertainment/where_edit.html", {'form': form, 'form2': form2})
html
<section>
<div class="container">
<div class="row">
<div class="col-md-3">
<h2>Editing Where</h2>
<br>
<form method = "post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.eventname }}</p>
<p>{{ form.place }}</p>
<p>{{ form.event_date }}</p>
</div>
<div class="col-md-9">
<section class="admin-section">
{{ form2.management_form }}
<div class="row">
{% for frm in form2 %}
<div class="col-md-4 admin__block" is-cover="false">
<div class="cover__wrapper edit__wrapper">
<a class="delete-button">Delete</a>
<a class="make-cover-button">Cover</a>
<img src="{{ frm.url }}" alt="">
</div>
</div>
{% endfor %}
</div>
Add photo
</section>
<section>
<h4>Description</h4>
{{ form.description }}
<input type="submit" value="Save">
Cancel
</section>
</form>
</div>
</div>
</div>
</section>
If I try to add
collage = EntertainmentCollage.objects.filter(album = place)
to my views.py and make form2(instance = collage) error occured QuerySet' object has no attribute 'pk'
___ UPDATE ___
I need to get page like http://joxi.ru/Dr8X8w4tkGw1zr
where images are taken from the model EntertainmentCollage,
and if they are added then I could see them in the form.
I realized that my question was incorrectly asked. I just had to display all the images from the queryset and use the inline form to add a button to add a new image.

Django CreateView allows resubmission of the data when the form is displayed when hiting the back button

I'm trying to make an app with an upload image. The thing is that I want to limit the possibility of uploading an image to only once per day. Everything is working fine except if the user is using the back button of the browser. He can spam the system. What is the correct way to prevent this?
models.py
# Admin option to select from
PHOTO_STATUS = (
('ir', 'In Review'),
('ap', 'Approved'),
('tr', 'Trash'),
)
def pause():
return timezone.now() + timezone.timedelta(minutes=5)
# Main photo upload app
class PhotoUpload(models.Model):
'''After the user finishes the challenge
he can upload a photo using this app'''
# The date when a user uploads a photo
date_upload = models.DateTimeField(default=timezone.now)
# The date when user can upload another photo
# pause = date_upload + timezone.timedelta(minutes=20)
pause_upload = models.DateTimeField(default=pause)
# The status of the photo
status = models.CharField(max_length=2, default='ir', choices=PHOTO_STATUS)
# The date when the admin aproves the photo
date_approved = models.DateTimeField(default=timezone.now,
blank=True,
null=True)
# The date when the admin soft-deletes the photo
date_deleted = models.DateTimeField(default=timezone.now,
blank=True,
null=True)
user = models.ForeignKey(User)
# A function that defines the path where the photo
# will be uploaded and that will change the filename.
def path_and_rename(instance, filename):
extension = filename.split('.')[-1]
if User.is_authenticated:
# print(instance._user.username)
return 'uploads/{}-{}.{}'.format(instance.user.username,
instance.date_upload,
extension)
else:
return 'uploads/{}.{}'.format(instance.date_upload, extension)
# Application side file size check
def file_size(value):
limit = 2 * 1024 * 1024
if value.size > limit:
raise ValidationError(
'File too large. Size should not exceed 2 MB.')
image = models.ImageField(upload_to=path_and_rename,
validators=[file_size],
null=True,
blank=True)
def __str__(self):
return str(self.pause_upload)
view
class PhotoUploadCreate(CreateView):
model = PhotoUpload
template_name = 'upload_photo.html'
form_class = PhotoUploadForm
def form_valid(self, form):
form.instance.user = self.request.user
return super(PhotoUploadCreate, self).form_valid(form)
def get_success_url(self):
return reverse('success')
Thank you!
Edit
Here is my template where I use a template tag called photos and a template filter called elapsed.
{% for photo in photos %}
<div class="container vertical-centre">
{% if not photo.pause_upload|elapsed:1 %}
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="centre-colour">
{% if photo.user.first_name %}{{ photo.user.first_name }}{% else %}{{ photo.user.username }}{% endif %} you can upload another photo anytime after:<br>
<div id="clockdiv" class="centre-colour">
<span class="hours"></span> Hours <span class="minutes"></span> minutes
<span class="seconds"></span> seconds
</div>
</h1>
</div>
</div>
{% else %}
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="centre-colour">
CONGRATULATIONS {% if photo.user.first_name %}{{ photo.user.first_name }}{% else %}{{ photo.user.username }}{% endif %}!!!
</h1>
<h2 class="centre-colour">
Upload photo:
</h2>
</div>
</div>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
{% crispy form %}
</div>
</form>
<h4 class="centre-colour">or</h4>
Start again
</div>
</div>
{% endif %}
</div>
{% endfor %}
And here are the template tag and filter
register = template.Library()
#register.inclusion_tag('photos/photos_tags.html')
def photos_up(request, number=1):
a = PhotoUpload.objects.filter(user__username=request).exists()
if a:
return {'form': PhotoUploadForm(),
'photos': PhotoUpload.objects.filter(
user__username=request
).order_by(
'-pause_upload')[:number]
}
else:
return {'form': PhotoUploadForm(),
'photos': PhotoUpload.objects.all()[:number]
}
register = template.Library()
#register.filter(expects_localtime=True)
def elapsed(time, seconds):
return time + timezone.timedelta(seconds=seconds) < timezone.now()
Everything is working as expected unless a user decides to hit the back button from the success page. Then the upload page will go again into the form view instead to go to the counter.
You can put an attribute in your database as lastuploaded (DateTimeField) and when user uploads a photo check that if lastuploaded is one day before current time.
EDIT:
add a lastuploaded field to your model.
class PhotoUpload(models.Model):
last_uploaded = models.DateTimeField(null=True, blank=True, default=timezone.now)
Now in your view's form_valid function put a check.
def form_valid(self, form):
photo_upload_object = PhotoUpload.objects.filter(user=self.request.user).latest('last_uploaded')
if photo_upload_object.last_uploaded + datetime.datetime.timedelta(days=1) < current_time and photo_upload_object.last_uploaded is not None:
form.instance.user = self.request.user
return super(PhotoUploadCreate, self).form_valid(form)
else:
return HttpResponse("some error")
Other approach might be to save last uploaded in cookies but that won't work in all cases like login from different devices.