Note:
My model table consists of id field and File field which will be pdf.
I am inserting data into the model using django admin.(I have no custom upload form)
I am trying to view the pdf in the browser(as it normally opens in chrome).
I am trying to find the file by taking the id field(by user) in a custom HTML template using a form(Please look at the codes mentioned below.)
I am attaching the urls.py, index.html, views.py, models.py and forms.py codes below. Please patiently go through and let me the know the problem and the solution.
I think my code should work but I am getting a Suspicious File Operation Error.
urls.py
urlpatterns = [
path('',views.index),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
def index(request):
if request.method == "POST":
form = Form(request.POST)
if form.is_valid():
id=request.POST.get("id")
ans = query.objects.get(id=id)
response=ans.repo
if ans is None:
return redirect("index.html")
else:
#return render (request,"ans.html",{'ans':response})
return redirect(response)
else:
form = Form()
return render(request,"index.html",{'form':form})
forms.py
class Form(forms.Form):
id = forms.CharField(label="Report ID", max_length=100)
models.py
class query(models.Model):
id=models.IntegerField(primary_key=True)
repo=models.FileField(upload_to='documents/')
index.html
<!-- Search Form -->
<form id="signup-form" method="POST" action="">
{% csrf_token %}
{{form}}
<input type="submit" value="Check" />
</form>
The URL for a file field is in the url attribute, so you need to use ans.repo.url.
Related
I started to learn Django today, but I am stuck at using forms. I have created two forms: /contact and /blog-new. The form at the Contact page is working fine, but the one at /blog-new is redirecting me to the home page after the submission button is pressed and no information is printed in the terminal nor saved in the database.
Code on Github
I appreciate if someone can explain to me what I did wrong as I cannot figure it out. Thank you!
mysite/blog/forms.py
from django import forms
from .models import BlogPost
class BlogPostModelForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = ['title', 'slug', 'content']
mysite/blog/views.py
from .forms import BlogPostModelForm
def blog_post_create_view(request):
# create objects
# ? use a form
# request.user -> return something
form = BlogPostModelForm(request.POST or None)
if form.is_valid():
print(form.cleaned_data)
form.save()
form = BlogPostModelForm()
template_name = 'form.html'
context = {'form': form}
return render(request, template_name, context)
mysite/blog/models.py
from django.db import models
# Create your models here.
class BlogPost(models.Model):
title = models.TextField()
slug = models.SlugField(unique=True)
content = models.TextField(null=True, blank=True)
mysite/mysite/urls.py
from blog.views import (
blog_post_create_view,
)
urlpatterns = [
..
path('blog-new', blog_post_create_view),
..
]
mysite/templates/form.html
{% extends "base.html" %}
{% block content %}
{% if title %}
<h1>{{ title }}</h1>
{% endif %}
<form method='POST' action='.'> {% csrf_token %}
{{ form.as_p }}
<button type='submit'>Send</button>
</form>
{% endblock %}
You need to point to right url in action attribute of form.
<form action="/blog-new/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
I think it's not necessary in your case but you could also refactor your view to match the docs.
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import SomeForm
def some_view(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = SomeForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = SomeForm()
return render(request, 'template_name.html', {'form': form})
You need to point to right url in action attribute of form.
That was not actually the solution but something that helped me to figure out what was wrong.
It is not necessary to point to /blog-new/ as . for action will point to the same page, but I have tried with /blog-new/ as action URL and I was surprised to see that /blog-new/ page doesn't exist.
The bug was in mysite/mysite/urls.py for missing a /:
path('blog-new', blog_post_create_view),
It is funny (and annoying) how a symbol like / missing from your code will mess up everything and make you spend hours trying to find a solution as simple as that.
Thank you for your time spend to have a look over my code and try to help me!
I'm trying to upload image using django forms, and then assign it to my model object image field.
forms.py
class MemberRegistrationForm(forms.ModelForm):
birthday=forms.DateField(input_formats=settings.DATE_INPUT_FORMATS)
class Meta:
model=Member
fields=('birthday','photo',)
models.py
class Member(models.Model):
user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
birthday=models.DateField(blank=True,null=True)
photo=models.ImageField(upload_to='account/%Y/%m/%d',blank=True)
def __str__(self):
return "{} /'s profile ".format(self.user.username)
urls.py
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Parsing form page
<form class="" action="." method="post">
{{form.as_p}}
{{form_member.as_p}}
{% csrf_token %}
<input type="submit" name="" value="Create my account">
</form>
Display page
<img width="90px;" height="180px;"src="{{member.photo.url}}" alt="">
views.py
I guess problem is here.I can not extract the uploaded image from form and assign it to my model object field
def user_signup(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
form_member=MemberRegistrationForm(request.POST,request.FILES)
if form.is_valid() and form_member.is_valid():
user=form.save(commit=False)
user.set_password(
form.cleaned_data['password']
)
user.save()
member=Member.objects.create(user=user,
photo=request.FILES['photo'], #HERE I'M NOT SURE IF THIS THE RIGHT WAY OR NOT
birthday=form_member.cleaned_data['birthday'])
return render(request,
'account/registeration_done.html',
{'user':user,
'member':member,
'form':form,
'form_member':form_member,
})
You have to specify enctype="multipart/form-data" in your html markup.
Also, you can find the work example upload form here
https://github.com/miletskiy/FortyTwoTestTask/blob/master/apps/hello/templates/edit_applicant.html#L20
I am trying to display a simple form (3 fields) on a webpage using Django but no fields are displaying - see code below.
I've gone through the Django doc, MDN doc, most of the StackOverflow posts here, but it's still not working.
I was able to see, using {% debug %}, that there is no object EmailInput on the page.
At this point, I am not sure what is causing this issue. Any help would be very much appreciated.
Thanks
forms.py
from django import forms
class EmailInput(forms.Form):
email = forms.EmailField()
first_name = forms.CharField()
last_name = forms.CharField()
views.py
from django.shortcuts import render
from .models import journalEntry
from django.http import HttpResponseRedirect
from django.urls import reverse
from journal.forms import EmailInput
def index(request):
post = journalEntry.objects.filter(status__exact='f')
latest_post = journalEntry.objects.filter(status__exact='f').order_by('-created')[:5]
return render(request, 'journal_index.html', context = {'post':post,'latest_post':latest_post})
def email_input(request):
if request.method == 'POST':
form = EmailInput(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('journal-index'))
else:
form = EmailInput()
return render(request, 'journal_index.html',{'form':form})
journal_index.html
{% extends "base_generic.html" %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit"/>
</form>
{% endblock content %}
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='journal-index'),
]
If you want to display it in the index page then you have to send it as a context variable in your index function. And now it will be available in your journal_index.html template file.
def index(request):
post = journalEntry.objects.filter(status__exact='f')
latest_post = journalEntry.objects.filter(status__exact='f').order_by('-created')[:5]
form = EmailInput()
context = {
'post': post,
'latest_post': latest_post,
'form': form
}
return render(request, 'journal_index.html', context = context)
The code from your email_input function is not called anywhere so there is no way this form could be displayed. Also you have to figure out where do you want to display this form. If you don't want to display it together with the stuff from your index page then you would have to create a new template file, add the form there and add a new url path to display that page.
It is because you are not even calling email_input.
you need to bind it to a url like this
urlpatterns = [
url(r'^$', views.email_input),
]
A frontend developer has given me a front-end layout which consists of html forms. I being a backend developer need to fetch the data from the form and store it in the database. I am using django version 2.0 for the website development. I donot want to use django forms as then I will be forced to make a lot of changes in the html code. How can I extract data from input fields in the HTML forms?
Let us say the we have a simple HTML form in a file index.html
myapp/templates/index.html
In the form, the data must be sent using post method only.
<form action="{% url 'myapp:update' %}" method="post">
<input type="text" name="first_field"/><br>
<input type="text" name="second_field"/><br><br>
<button type="submit" value="Submit"/>
</form>
The purpose of the form is to update the database.
myapp/models.py
from django.db import models
class Person(models.Model):
first_name=models.CharField(max_length=30)
last_name=models.CharField(max_length=30)
myapp/urls.py
from django.urls import path,include
from . import views
app_name='myapp'
urlpatterns = [
path('index/', views.index, name='index'),
path('update/', views.update, name='update'),
]
myapp/views.py
In views.py file, any element in the form can be fetched using request.POST['nameOfTheFieldInTheForm']
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'myapp/index.html', {})
def update(request):
# print('Inside update function')
if request.method=='POST':
# print("Inside post block")
first_field_data=request.POST['first_field']
second_field_data=request.POST['second_field']
x=Person(first_field=first_field_data,
second_field=second_field_data)
x.save()
return index(request)
I want the user to upload the profile picture on the profile page but it is not storing it in the media/documents folder, and yes, I have put enctype="multipart/form-data" in the html form and the method is post. I'm new to django so please provide a simple solution
models.py
class User(models.Model):
first_name=models.CharField(max_length=20)
last_name=models.CharField(max_length=20)
username=models.CharField(max_length=25, primary_key=True)
password=models.CharField(max_length=15)
email_id=models.CharField(max_length=30, default='NULL')
profile_pic=models.ImageField(upload_to='profilepics/%Y/%m/%d/',height_field=200,width_field=200,default='')
forms.py
class ProfilePicForm(forms.ModelForm):
class Meta:
model=User
fields=['username','profile_pic']
views.py
def upload(request):
if request.method == 'POST':
username=request.POST['username']
m=User(username=username)
m.profile_pic=request.FILES['profile_pic']
m.save()
return render(request,'LoginPage/done.html')
else:
pic=ProfilePicForm()
return render(request,'AfterLogin/profile.html')
html file
<form method="POST" enctype="multipart/form-data" action="{% url 'LoginPage:upload' %}">
{% csrf_token %}
<p>Upload your profile photo</p><br>
<input id="id_image" type="file" class="" name="image">
<input type="hidden" name="username" value="{{ username }}">
<input type="submit" value="Submit"/>
</form>
Have a look at this:
Need a minimal Django file upload example
Also, try sharing the error you are getting when trying to upload picture.
I think it would be better for you to use the standard User model created by Django which already has the fields first_name, last_name, username, password and email. Then you create a new model with a OneToOneField with the model user.
If the image uploads and if you get a 404 when going directly to the image url when running the server, then you have forgotten to serve the image, which you have to do when you are in production phase.
urlpatterns = [
...patterns...
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Something like this should work:
modles.py
from django.contrib.auth.models import User
class UserPicture(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
picture = models.ImageField(upload_to='...')
forms.py
class ProfilePicForm(forms.ModelForm):
class Meta:
model = UserPicture
fields=['profile_pic']
views.py
def your_view(request):
...
if request.method == 'POST':
form = UserPicture(request.POST, request.FILES)
if form.is_valid():
userprofile = form.save()
userprofile.user = request.user
userprofile.save()
...
You don't have to define own User model since Django has it's own: https://docs.djangoproject.com/en/1.10/ref/contrib/auth/#user-model
And as Jonatan suggested - post error code. If there's none, remove this try ... except: pass.