I am trying to set up a webapp that accepts image uploads from a user, using ImageField, but I cant seem to figure out how to save the uploaded image. My media folder is empty even though there doesnt seem to be any errors.
Went through a lot of tutorials to no avail. I get the basic concept, create a form, model, set media in settings.py, handle upload in views, and I am getting a working view with a image upload form, but uploading an image does not save.
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py
urlpatterns = [
path('embed/', embed, name = 'embed'),
path('success', success, name = 'success'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
forms.py
class imguploadform(forms.ModelForm):
class Meta:
model = imgupload
fields = ['title', 'image']
models.py
class imgupload(models.Model):
title = models.CharField(max_length = 20)
image = models.ImageField(upload_to="media/images/", default = None)
def __str__(self):
return self.title
views.py
def embed(request):
if request.method == 'POST':
form = imguploadform(request.POST, request.FILES)
if form.is_valid():
newimg = imgupload(title=request.POST['title'], image=request.FILES['image'])
newimg.save()
return redirect('success')
else:
form = imguploadform()
return render(request, 'webapp/imgupload.html', {'form' : form})
def success(request):
return HttpResponse("Successfully uploaded")
imgupload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Image</title>
</head>
<body>
<form method = "post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
</body>
</html>
Another thing to note, the admin panel does not show the image model
The following code worked at my machine whoes os system is ubuntu18 with newest django and pillow
models.py
class Imgupload(models.Model):
title = models.CharField(max_length=20)
image = models.ImageField(upload_to="images/", default=None)
def __str__(self):
return self.title
views.py
def embed(request):
if request.method == "POST":
form = Imguploadform(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect("success")
else:
form = Imguploadform()
img = Imgupload.objects.last()
return render(request, "webapp/imgupload.html", {"form": form, "img": img})
def success(request):
return HttpResponse("Successfully uploaded")
imgupload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Image</title>
</head>
<body>
<form method = "post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
{% if img %}
Image uploaded latest:
<img src="{{ img.image.url }}">
{% endif %}
</body>
</html>
Related
I use modelformset_factory to upload image, but I want to separate the already saved image (A in the below link) and upload image (B in the below link) on two different html template.
How do I resolve this problem?
Here is my code below:
views.py
def post_image(request):
PictureFormSet = modelformset_factory(Picture, form=PictureForm, extra=3)
if request.method == 'POST':
formset = PictureFormSet(request.POST, request.FILES)
if formset.is_valid():
formset.save()
return HttpResponse("Upload done!!")
else:
return HttpResponse("Upload Failed!!")
else:
formset = PictureFormSet()
return render(request, "Image.html", {"formset": formset})
models.py
class Picture(models.Model):
article = models.ForeignKey("Article", related_name="article_photo", on_delete=models.CASCADE)
photo = models.ImageField(upload_to="photo", height_field=None, width_field=None, max_length=100)
first_photo = models.BooleanField(default=False)
urls.py
path('post/image/', post_image),
html
<html lang="zh-Hant-TW">
<head>
<meta charset="UTF-8">
<title>post_image</title>
</head>
<form action="" method="POST" enctype="multipart/form-data">{% csrf_token %}
{{ formset.management_form }}
<table>
{% for form in formset %}
{{ form }}
{% endfor %}
</table>
<input type="submit" value="Sumbit">
</form>
I'm trying to utilize Django forms.ModelForm function. However, I can not get it to render in the browser (Firefox and Chrome tested). In both browser inspection of code, the table\form does not show and there is no error coming from Django at all. The only thing that shows from the html file is the "Save button" Is there something I am missing here?
In Models.py
from django.db import models
class Product_sell_create(models.Model):
product_product_sell = models.CharField(max_length=120)
product_price_sell = models.DecimalField(decimal_places=2, max_digits=500)
product_volume_sell = models.DecimalField(decimal_places=2, max_digits=500)
product_location_sell = models.CharField(max_length=120)
product_description_sell = models.TextField(blank=False, null=False)
Forms.py
from django import forms
from .models import Product_sell_create
class ProductName(forms.ModelForm):
class Meta:
model = Product_sell_create
fields = [
'product_product_sell',
'product_volume_sell',
'product_price_sell',
'product_location_sell',
'product_description_sell'
]
Views.py
from django.shortcuts import render
from .forms import ProductName
def products_create_view(request):
form = ProductName(request.POST or None)
if form.is_valid():
form.save()
form = ProductName()
context = {
'form': form
}
return render(request, "sell.html", context)
sell.html
{% include 'navbar.html' %}
<h1> Upper test</h1>
<form>
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" />
</form>
<h1> TEST </h1>
{% block content %}
{% endblock %}
just did it, you would have problems POSTing your object too:
views.py:
from django.shortcuts import render, redirect
from .forms import ProductName
from .models import Product_sell_create
def products_create_view(request):
if request.method == 'POST':
form = ProductName(request.POST)
if form.is_valid():
prod = form.save(commit=False)
prod.save()
return redirect('../thanks')
else:
form = ProductName()
context = {
'form': form
}
return render(request, "form_test.html", context)
def thanks_view(request):
query = Product_sell_create.objects.all()
return render (request, 'thanks.html', {'query' : query})
forms.py and models.py keeps the same
sell.html:
<h1> Upper test</h1>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" />
</form>
<h1> TEST2 </h1>
thanks.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>{{ query }}</h1>
<h2>THANKS</h2>
</body>
</html>
did you create the 'sell.html' inside a 'templates' folder in your app folder?
MyApp/templates/sell.html
Befor all :
Djano VERSION = 1.8, and it's obligatory that I use this version
Question
I do not know why I cannot update the User instance by a form.
I mean by updating: changing the value in the database and in the request
The User model is not created by me but I use django.contrib.auth.models.User
Code
This is my code
app/forms.py
from django import forms
from django.contrib.auth.models import User
class ModificationForm(forms.ModelForm):
class Meta:
model = User
fields = ['email']
app/views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from app.forms import ModificationForm
#login_required
def profil(request):
if request.method == "POST":
form = ModificationForm(data=request.POST, instance=request.user)
if form.is_valid():
form.save()
else:
form = ModificationForm()
return render(request, "profil.html", {'form':form})
profile.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Profil</title>
</head>
<body>
<h1>Profil</h1>
<a href='/deconnexion'> Logout </a>
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Enregistrer" />
</form>
</body>
</html>
Your posting to the wrong link!
If you do not know it, just leave the action empty in the html insted of action="." !
so I have a very simple blog app and I'm trying to figure out why the data entered in the form doesn't save to the database and it doesn't redirect me to my index page.
forms.py
from django import forms
class NewBlog(forms.Form):
blogger = forms.CharField(max_length=20, widget=forms.TextInput(attrs=
{'placeholder' : 'Name'}))
text = forms.CharField(widget=forms.Textarea(attrs={'placeholder' :
'Text'}))
new_blog.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>New Blog</title>
</head>
<body>
<form action="{% url 'new_blog' %}" method="POST">
{% csrf_token %}
<h2>Write your blog here:</h2>
{{ form }}
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
views.py
from django.shortcuts import render, redirect
from .models import BlogPost
from .forms import NewBlog
def index(request):
blogs = BlogPost.objects.all()
context = {'blogs' : blogs}
return render(request, 'blog/index.html', context)
def newBlog(request):
if request == 'POST':
form = NewBlog(request.POST)
if form.is_valid():
blogger = form.cleaned_data['blogger']
text = form.cleaned_data['text']
new_blog = BlogPost(blogger = blogger, text = text)
new_blog.save()
return redirect('index')
else:
form = NewBlog()
context = {'form' : form}
return render(request, 'blog/new_blog.html', context)
I think the problem is likely to be the first line of your view.
if request == 'POST':
should be:
if request.method == 'POST':
To save an Object into database
instead of
new_blog = BlogPost(blogger = blogger, text = text)
new_blog.save()
use the best way:
BlogPost.objects.create(blogger = blogger, text = text)
It will be automatically saved
In my project i want to set HTTP Session tracking for 30 second after 30 second user should be logout automatically, if user is not doing any think and also one more condition after login if user click on back button of my browser and than forward button of my browser than it must be transfer on login page for entering username and password.
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from .models import Reg
from .forms import LoginForm
from .forms import RegForm
def reg(request):
if request.method == 'POST':
form = RegForm(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponse('reg success')
else:
print(form.errors)
return HttpResponse("error")
else:
form = RegForm()
return render(request,'reg.html', {'form': form})
def login(request):
if request.method == "POST":
MyLoginForm = LoginForm(request.POST)
if MyLoginForm.is_valid():
un =MyLoginForm.cleaned_data['user']
pw=MyLoginForm.cleaned_data['pwd']
dbuser = Reg.objects.filter(user=un,pwd=pw)
if not dbuser:
return HttpResponse('opppppss login faield')
else:
return HttpResponse('login success')
else:
form = LoginForm()
return render(request, 'login.html', {'form': form})
def home(request):
return render(request,'home.html')
models.py
from __future__ import unicode_literals
from django.db import models
class Reg(models.Model):
user = models.CharField(primary_key=True,max_length=20)
pwd = models.CharField(max_length=20)
fname=models.CharField(max_length=10)
lname=models.CharField(max_length=10)
dob=models.DateField()
mobno=models.IntegerField()
forms.py
from django import forms
from .models import Reg
class RegForm(forms.ModelForm):
class Meta:
password = forms.CharField(widget=forms.PasswordInput)
model = Reg
widgets = {'pwd': forms.PasswordInput(),}
fields = ['user', 'pwd','fname','lname','dob','mobno']
class LoginForm(forms.Form):
user = forms.CharField(max_length=20)
pwd = forms.CharField(widget=forms.PasswordInput())
home.html
<!DOCTYPE html>
</html>
<html>
<body bgcolor="#00ffff">
<h1>welcome </h1>
click here to register<br>
click here to login
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form }}
<br>
<input type="submit" value="submit">
</form>
</body>
</html>
reg.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form }}
<br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
Try adding this to your settings.py
SESSION_COOKIE_AGE = 30