Uploading and retrieving files from django frontend to postgresql backend - python

This is my table in postgres:
How would I bring this into the frontend so that users can upload their documents without having to access the DB. Right now I can only upload docs into the filesystem instead of the DB:
views.py:
def upload(request):
if request.user.is_authenticated:
username = request.user.username
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
return render(request, 'app/upload.html', {
"uploaded_file_url": uploaded_file_url,
"username": username,
})
return render(request, 'app/upload.html', {
"username": username,
})
upload.html:
{% if form.errors %}
<p>You did not select a file to upload!</p>
{% endif %}
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>
{% if uploaded_file_url %}
<p>File uploaded at: {{ uploaded_file_url }}</p>
{% endif %}
models.py:
class Document(models.Model):
Document_name = models.CharField(max_length=255, default='Document_name')
Date = models.DateField()
Client_id = models.ForeignKey(ClientDetail, on_delete=models.CASCADE)
def __str__(self):
return self.Document_name
Schema:
Also how would I retrieve the uploaded documents.

An example for you:
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py
from django.conf.urls.static import static
urlpatterns = [
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
from django.core.validators import FileExtensionValidator
class Document(models.Model):
name = models.CharField(max_length=255, default='Document_name')
date = models.DateField()
client = models.ForeignKey(ClientDetail, on_delete=models.CASCADE)
myfile = models.FileField(validators=[
FileExtensionValidator(allowed_extensions=['pdf', 'doc', 'ppt', 'xlsx'])
])
def __str__(self):
return self.name
forms.py
from django import forms
from .models import Document
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = '__all__'
upload.html:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="ok">
</form>
{% if uploaded_file_url %}
<p>File uploaded at: {{ uploaded_file_url }}</p>
{% endif %}
views.py
def upload(request):
if request.user.is_authenticated:
# Is it better to use #login_required ?
username = request.user.username
else:
username = ''
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
doc = form.save()
return render(request, 'app/upload.html', {
"form": DocumentForm(),
"uploaded_file_url": doc.myfile.url,
"username": username,
})
else:
form = DocumentForm()
return render(request, 'app/upload.html', {"form": form})

Related

My comments are not being displayed in a django blog

I am trying to add a comment section to add a comment section to my blog detail using django but when i run my server i get no error in the development server and the comments are not being displayed. I added the comments from my admin site.
The snippet of my code is below.
views.py
from .models import Post
from django.utils import timezone
from .forms import PostForm, CommentsForm
from django.contrib.auth.decorators import user_passes_test
# Create your views here.
def home(request):
return render (request, 'blogapp/home.html')
def blog_list(request):
post = Post.objects.order_by('-published_date')
context = {
'posts':post
}
return render(request, 'blogapp/blog_list.html', context)
def blog_detail(request, pk=None):
detail = Post.objects.get(pk=pk)
context = {
'detail': detail
}
return render(request, 'blogapp/blog_detail.html', context)
def add_post(request, pk=None):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid:
body = form.save(commit=False)
body.published_date = timezone.now()
body.save()
return redirect('blog_list')
form = PostForm()
else:
form = PostForm()
context = {
'form': form
}
return render(request, 'blogapp/add_post.html', context)
def add_comments(request, pk=None):
if request.method == "POST":
form = CommentsForm(request.POST)
if form.is_valid:
comment = form.save(commit=False)
comment.date_added = timezone.now()
comment.save()
return redirect('blog_detail')
form = CommentsForm()
else:
form = CommentsForm()
context = {
'form': form
}
return render(request, 'blogapp/add_comments.html', context)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="homepage"),
path('blog/', views.blog_list, name="blog_list"),
path('blog/post/<int:pk>/', views.blog_detail, name="blog_detail"),
path('blog/add_post/', views.add_post, name="add_post"),
path('blog/add_comments/', views.add_comments, name="add_comments"),
]
forms.py
from django import forms
from .models import Post, Comments
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('author', 'title', 'post_description', 'image', 'image_description', 'body',)
class CommentsForm(forms.ModelForm):
class Meta:
model = Comments
fields = ('post', 'name', 'body',)
models.py
from django.db import models
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.user', on_delete=models.CASCADE)
title = models.CharField(max_length=300)
body = models.TextField()
post_description = models.CharField(max_length=500, blank=True, null=True)
image = models.ImageField(blank=True, null=True, upload_to="image/")
image_description = models.CharField(max_length=500, blank=True, null=True)
published_date = models.DateTimeField(default=timezone.now, blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
class Comments(models.Model):
post = models.ForeignKey('Post', related_name="comments", on_delete=models.CASCADE)
body = models.TextField()
name = models.CharField(max_length=300)
date_added = models.DateTimeField(default=timezone.now, blank=True, null=True)
def __str__(self):
return '%s - %s' % (self.post.title, self.name)
blog_detail.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<article>
<strong>
<h1><b>{{ detail.title }}</b></h1>
</strong>
<h3>POST AUTHOR: {{ detail.author }}</h3>
<h4><i>{{ detail.post_description }}</i></h4>
<h4>PUBLISHED:{{ detail.published_date }}</h4>
<p>
<hr>
{% if detail.image %}
<center>
<br>
<img src="{{ detail.image.url }}" width="1000" height="700">
<br><br>
<i>IMAGE DESCRIPTION: {{ detail.image_description }}</i>
</center>
{% endif %}
<hr>
<br><br><br>
{{ detail.body|linebreaksbr }}
</p>
<hr class="solid">
<h2>COMMENTS ...</h2>Add One
{% for comment in post.comments.all %}
<strong>
{{ comment.name }}-{{ comment.date_added }}
</strong>
{{ comment.body }}
{% endfor %}
</article>
{% endblock %}
add_comments.html
{% extends 'base.html' %}
{% block content %}
<article>
{% if user.is_authenticated %}
<h1>CREATE NEW BLOG POST.</h1>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">ADD COMMENT</button>
<input type="hidden" name="next" value="{% url 'blog_detail' pk=post.pk %}"/>
</form>
{% else %}
<h2>Login HERE to add comments.</h2>
{% endif %}
</article>
{% endblock %}
in your template you use
{% for comment in post.comments.all %}
but in template context there is no post variable
you should use {% for comment in detail.comments.all %}

nothing is saved after updating form

I have a Candidat models and Experience_Pro models as shown below with fk relation between them .
i can register or login a candidat(user) and a profil page with firstname and lastname of that candidat shown, and a form for Experience_Pro for the user to add if he does have one .
but when i enter all the info in the Experience_Pro form and click update nothing is added to candidat
I don't know what i am missing but the form is showing with no errors and even after i update the profile no errors but nothing is saved to candidat
models.py
class Candidat(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
experience_Pro = models.ForeignKey('Experience_Pro' ,on_delete=models.CASCADE,blank=True,
null=True,default='')
class Experience_Pro(models.Model):
annee_debut = models.IntegerField()
annee_fin = models.IntegerField()
description_exp_pro = models.TextField(null=True,blank=True)
forms.py
class UpdateCandidat(forms.ModelForm):
class Meta:
model=Candidat
fields=['experience_Pro']
class CreateExperience_Pro(forms.ModelForm):
class Meta:
model=Experience_Pro
fields='__all__'
views.py
#login_required
def profil(request):
exp_form = CreateExperience_Pro()
c_form = UpdateCandidat()
if exp_form.is_valid():
exp = exp_form.save()
candidat = c_form.save(commit=False)
candidat.save(experience_Pro=exp)
return redirect('profil')
context={
'exp_form':exp_form
}
return render(request ,'candidats/profil.html',context)
profil.html
<h1>Profil Candidat</h1>
<p>Prenom: {{ user.first_name }}</p>
<p>Nom: {{ user.last_name }}</p>
<p>Email: {{ user.email }}</p>
<form method="POST" action="">
{% csrf_token %}
{% comment %} {{ c_form }} {% endcomment %}
{{ exp_form }}
<input type="submit" value="Update">
</form>
You need to do some update:
#login_required
def profil(request):
if request.method == 'POST':
exp_form = CreateExperience_Pro(request.POST)
c_form = UpdateCandidat(request.POST)
if exp_form.is_valid() and c_form.is_valid():
exp = exp_form.save()
candidat = c_form.save()
return redirect('profil')
else:
context = {
'exp_form': exp_form,
'c_form': c_form,
}
return render(request, 'candidats/profil.html', context)
else:
exp_form = CreateExperience_Pro()
c_form = UpdateCandidat()
context = {'exp_form': exp_form, 'c_form': c_form}
return render(request, 'candidats/profil.html', context)

"This field is required" when field is populated on Django modelForm

After clicking the upload button on a form I get a bullet point beneath the 'Job ID' field stating "This field is required." even though I have values enterred into the field. Here is my code:
forms.py:
class UploadFileForm(forms.ModelForm):
class Meta:
model = Job
fields = ['jobID',
'original_file']
labels = { 'jobID': _('Job ID'),
'original_file': _('File'),}
error_messages = {
'jobID': {'max_length': _("Job ID is limited to 50 characters."),
},
NON_FIELD_ERRORS: {
'unique_together': "%(model_name)s's %(field_labels)s are not unique.",
}
}
models.py:
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
class Job(models.Model):
user = models.ForeignKey('auth.User')
original_file = models.FileField()
jobID = models.CharField(max_length=50)
rev = models.IntegerField()
create_date = models.DateTimeField(default = timezone.now)
def save(self):
"Get last value of rev considering jobID and User and increment"
"see https://stackoverflow.com/questions/1065089/auto-increment-a-value-in-django-with-respect-to-the-previous-one"
last_rev = Job.objects.filter(user=self.user).filter(jobID=self.jobID).order_by('-rev')
if last_rev:
rev = last_rev[0].rev + 1
else:
rev = 1
super(Job,self).save()
def __unicode__(self):
return self.jobID + " rev " + str(self.rev)
class Meta:
indexes = [
models.Index(fields=['user','jobID']),
]
unique_together = ("user","jobID","rev")
ordering = ['-create_date']
views.py
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import UploadFileForm
from .models import Job
# Create your views here.
def upload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return render(request,'precheck/prestage.html')
else:
form = UploadFileForm()
return render(request, 'precheck/upload.html',{'form': form})
def success(request):
return render(request, 'precheck/prestage.html')
upload.html
{% extends 'base.html' %}
{% block content %}
<h2>Upload File</h2>
{% if error %}
{{ error }}
<br />
<br />
{% endif %}
<form method = "POST" action="{% url 'precheck:upload' %}">
{% csrf_token %}
{{ form.as_p }}
<br />
<input type="submit" class="btn btn-primary" value="Upload">
</form>
{% endblock %}
I tried manually building the form (ie not using a modelform) with the same results. Thanks for the help.
EDIT:
Changing the form to include enctype="multipart/form-data" did the trick:
<form method = "POST" action="{% url 'precheck:upload' %}" enctype="multipart/form-data">
The error is not for jobID, but for original_file. This is because you are not using the enctype="multipart/form-data" attribute on the form element.

trouble with subscribing form (Django)

Please, help.. I do not udersatand what I should do this code to work..
home.html:
<form class="subscribe-form" action="{% url 'subscribe' %}" method="POST">{% csrf_token %}
{{ form }}
<button class="btn btn-main btn-lg" type="submit">Подписаться!</button>
</form>
{% if success %}
<div class="subscribe-result">
{{ success }}
</div>
{% endif %}
urls.py:
url(r'^$', 'interior_app.views.home', name='home'),
url(r'^subscribe/$', 'interior_app.views.subscribe', name='subscribe')
models.py:
class Subscriber(models.Model):
email = models.EmailField('', max_length=100, null=True, blank=True)
forms.py:
class SubscriberForm(forms.ModelForm):
class Meta:
model = Subscriber
fields = ['email']
admin.py:
class SubscriberAdmin(admin.ModelAdmin):
list_display = ('email',)
admin.site.register(Subscriber, SubscriberAdmin)
views.py:
def home(request):
portfolios = PortfolioObject.objects.all()
photos = []
for portfolio in portfolios:
for obj in portfolio.photo_set.all():
photos.append(obj)
form = SubscriberForm()
context = {"photos": photos[::2], "form": form}
return render(request, "home.html", context)
def subscribe(request):
print request
success = ''
if request.method == "POST":
print request.POST
form = SubscriberForm(request.POST)
print form
if form.is_valid():
form.save()
success = "Ваш Email успешно отправлен"
form = SubscriberForm()
else:
form = SubscriberForm()
context = {"photos": photos[::2], "form": form, "success": success}
return render(request, "home.html", context)
I input email in the form, push button and nothing is happening.
Any data in admin, any {{ success }}.
I need not AJAX.. I would like to do this feature only with Django

uploading files from form

I have a ModelForm that I'm using to upload files with and it doesn't want to work. I had it working yesterday but I'm not sure what was done to make it stop all of a sudden.
Here's my ModelForm:
class UserForm(forms.ModelForm):
description = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'cols': 80, 'rows': 5}))
class Meta:
model = UserProfile
exclude = {'user', 'description'}
Here's the Model:
def get_image_path(instance, filename):
return os.path.join('images', str(instance.id), filename)
def get_video_path(instance, filename):
return os.path.join('videos', str(instance.id), filename)
def get_randfile_path(instance, filename):
return os.path.join('randfile', str(instance.id), filename)
class UserProfile(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length=500, blank=True, null=True)
photo = models.FileField(upload_to=get_image_path, blank=True, null=True)
video = models.FileField(upload_to=get_video_path, blank=True, null=True)
rand_file = models.FileField(upload_to=get_randfile_path, blank=True, null=True)
def photo_name(self):
return os.path.basename(self.photo.name)
def video_name(self):
return os.path.basename(self.video.name)
Here's the View:
def detail(request, user_id):
user = get_object_or_404(User, pk=user_id)
userprofile = get_object_or_404(UserProfile, user=user)
year = datetime.now().year
userform = UserForm()
delvid = Del_Video()
if request.method == 'POST':
userform = UserForm(request.POST, request.FILES, instance=user)
delvid = Del_Video(request.POST)
if userform.is_valid():
userprofile.description = request.POST.get('description', userprofile.description)
userprofile.photo = request.FILES.get('photo', userprofile.photo)
userprofile.video = request.FILES.get('video', userprofile.video)
userprofile.rand_file = request.FILES.get('rand_file', userprofile.rand_file)
userprofile.save()
else:
messages.add_message(request, messages.INFO, 'Invalid Form')
userform = UserForm()
if delvid.is_valid():
if request.POST['Delete']:
userprofile.video.delete()
else:
delvid = Del_Video()
context = {'user': user, 'year': year, 'userform': userform, 'userprofile': userprofile, 'delvid': delvid}
return render(request, 'users/detail.html', context)
And here is the form in the template:
<div class="row">
<div class="col-md-4">
<h4>Update User:</h4>
{% if userform.errors %}
<h6>{{ userform.errors }}</h6>
{% endif %}
{% if messages %}
{% for message in messages %}
<h5>{{ message }}</h5>
{% endfor %}
{% endif %}
<form action="{% url 'users:detail' user.id %}" method="post" enctype="multipart/form-data" data-ajax="false">
{% csrf_token %}
{{ userform.as_p }}
<input type="submit" value="Update">
</form>
</div>
</div>

Categories