Problems with Django ImageField upload - python

I have a question, I wrote peace of Djnago code, to upload profile picture for user, from admin area model works fine, but from website itself image cannot be uploaded, it seems that code is not even being called. Here is my code, could you check and tell me what might be wrong?
models.py:
from django.conf import settings
from django.db import models
from django.core.files import File
def upload_location(instance, filename):
location = str(instance.user.id)
return "%s/%s" %(location, filename)
class ProfilePicture(models.Model):
user = models.ForeignKey(User)
profile_picture = models.ImageField(upload_to=upload_location, null=True, blank=True)
def __unicode__(self):
return unicode(self.user.id)
forms.py:
from django import forms
from .models import ProfilePicture
class ProfileEditPicture(forms.ModelForm):
class Meta:
model = ProfilePicture
fields = [
"profile_picture"
]
views.py:
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from django.shortcuts import render, get_object_or_404, render_to_response
rom .forms import ProfileEditPicture
from .models import ProfilePicture
#login_required()
def profile_picture(request, id):
user = get_object_or_404(User, id=id)
title = "Profile Edit"
profile, created = Profile.objects.get_or_create(user=user)
form = ProfileEditPicture(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
context = {
"form":form,
"title":title,
"profile":profile
}
return render(request, "profile/form.html", context)
urls.py:
urlpatterns = [
...
url(r'^profile_picture/(?P<id>[\w.#+-]+)/', 'profiles.views.profile_picture', name='profile_picture'),
...
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
HTML code in template is default django form.
Thanks in advance :)

A useful piece of documentation is "Binding uploaded files to a form". Possibly if you follow this you will overcome your issue.
Among other things, it is important that include this attribute in your forms element:
<form method="post" action="..." enctype="multipart/form-data">

Related

Login Button not redirecting back to home page

I am not getting redirected back to the homepage for some reason. I checked the creds to make sure it was correct and it was. I am not sure what's going on. I am not sure if I have to make it a button but I did the same thing before and it worked.
urls.py
from django.urls import path
from .views import pplCreate, pplCreate, pplList, pplDetail,pplUpdate,pplDelete,authView
urlpatterns = [
path('login/', authView.as_view(),name='login'),
path('', pplList.as_view(), name='pplLst'),
path('people/<int:pk>', pplDetail.as_view(), name='pplDet'),
path('people-update/<int:pk>', pplUpdate.as_view(), name='pplUpd'),
path('people-create/', pplCreate.as_view(), name='pplCre'),
path('people-delete/<int:pk>', pplDelete.as_view(), name='pplDel'),
]
views.py
from distutils.log import Log
import imp
from .models import People
from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django.contrib.auth.views import LoginView
# Create your views here.
class authView(LoginView):
template_name = 'base/login.html'
fields = '__all__'
redirect_authenticated_user = True
def get_success_url(self):
return reverse_lazy('pplLst')
class pplList(ListView):
model = People
context_object_name = 'people'
class pplDetail(DetailView):
model = People
context_object_name ='cnd'
template_name = 'base/people.html'
class pplCreate(CreateView):
model = People
fields = '__all__'
success_url = reverse_lazy('pplLst')
class pplUpdate(UpdateView):
model = People
fields = '__all__'
success_url = reverse_lazy('pplLst')
class pplDelete(DeleteView):
model = People
context_object_name = 'cnd'
success_url = reverse_lazy('pplLst')
login.html
<h1>Login</h1>
<from method="POST">
{%csrf_token %}
{{form.as_p}}
<input type="submit" value="Login">
</from>
In settings.py file, simply you can add this.
LOGIN_REDIRECT_URL = 'pplLst' #This is path name from urls
Add this in settings.py file, then you will get redirected to home page
Just remove auth view from views and do following way:
In urls.py:
from django.contrib.auth import views as auth_views
path('login/',auth_views.LoginView.as_view(template_name='base/login.html'),name='login'),

Django Attribute Error: 'NoneType' object has no attribute 'videofile'

I am following this tutorial to create a video uploader in my Django project and have run into this error:
..src/video/views.py", line 9, in showvideo
videofile= lastvideo.videofile
AttributeError: 'NoneType' object has no attribute 'videofile'
I'm sure I am missing something obvious and have been looking for the answer for a while now. Would be grateful for any help.
views.py
from django.shortcuts import render
from .models import VideoUpload
from .forms import VideoForm
def showvideo(request):
lastvideo= VideoUpload.objects.last()
videofile= lastvideo.videofile
form= VideoForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
context= {'videofile': videofile,
'form': form
}
return render(request, 'video.html', context)
forms.py
from django import forms
from .models import VideoUpload
class VideoForm(forms.ModelForm):
class Meta:
model = VideoUpload
fields = ["name", "videofile"]
models.py
from django.db import models
class VideoUpload(models.Model):
name= models.CharField(max_length=500)
videofile= models.FileField(upload_to='videos/', null=True, verbose_name="")
def __str__(self):
return self.name + ": " + str(self.videofile)
from django.conf import settings
from django.contrib import admin
from django.urls import path
from django.conf.urls.static import static
from video.views import (
showvideo,
)
urlpatterns = [
path('showvideo', showvideo, name='showvideo'),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
FYI I updated the name of the model to 'VideoUpload' vs the tutorial.
There is no last_video record in your database. To prevent this from erroring out in such and instance, you could change the line: videofile= lastvideo.videofile into
videofile = lastvideo.videofile if lastvideo else None
This will prevent an error from being thrown. Alternatively you could put the whole bit in a try/except block.

Please why is there a circular import error

I am working on a django project, but it returns the included urlconf "myapp.urls"does not appear to have any patterns in it.
I tried checking my views to ensure I imported everything correctly
from django.contrib import admin
from django.urls import path
from .views import home
from accounts.views import login_view
urlpatterns = [
path('admin/', admin.site.urls),
path('',home),
path('accounts/login/', login_view),
]
I expect the site to run and redirect me to the login page
This is my views in the same directory with the urls.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
#login_required
def home(request):
return render(request,"home.html")
This is the views.py for the accounts.
from django.shortcuts import render,redirect
from django.contrib.auth import(
authenticate,
get_user_model,
login,
logout
)
from .forms import UserLoginForm, UserRegisterForm
def login_view(request):
next = request.GET.get('next')
form = UserLoginForm()
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username,password=password)
login(request,user)
if next:
return redirect(next)
return redirect("/")
context = {
'form': form,
}
return render(request, "login.html",context)
When I run your project on Django 2.2, I don't see a circular import. Instead I see the error:
django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form UserRegisterForm needs updating.
Looking at your form, you haven't set fields, you have model = Userfields = [...] instead.
class UserRegisterForm(forms.ModelForm):
...
class Meta:
model = Userfields = [
'username',
'email',
'password',
"c_password"
]
Change it so that you set fields. You can remove 'password' and 'c_password' since you define these on your form separately.
class UserRegisterForm(forms.ModelForm):
...
class Meta:
fields = [
'username',
'email',
]

Form not Displaying in Django 1.8

I am making a form using Django 1.8 and Python 3.5
But the form is not showing up,IDK why ?
This are my files respectivel
urlpatterns = [
url(r'^login', 'login.views.login', name='login'),
url(r'^admin/', include(admin.site.urls)),
] + static(settings.STATIC_URL , document_root=settings.STATIC_ROOT)
login/view.py==
from django.shortcuts import render
from .forms import allusers1
# Create your views here.
def login(request):
form1=allusers1()
context = {
"form1": form1
}
return render(request, "login.html",context)
login/forms.py==
from django import forms
from .models import allusers1
class signupform(forms.ModelForm):
class Meta:
model = allusers1
fields = ['name','phoneno']
login/models.py
from django.db import models
# Create your models here.
class allusers1(models.Model):
name=models.CharField(max_length=400)
phoneno=models.CharField(max_length=10)
otp=models.IntegerField()
# def __str__(self):
# return self.name
login.html
{{form1}}
output
allusers1 object
But output should have been Name and ,Email fields for input
WHAT IS THE ERROR ?
Your form is actually named signupform, and not allusers1.
In your views.py, you should import your form like this:
from django.shortcuts import render
from .forms import signupform # <= here
# Create your views here.
def login(request):
form1=signupform() # <= and here
context = {
"form1": form1
}
return render(request, "login.html",context)

Image not showing in Django [duplicate]

This question already has answers here:
How to display images from model in Django?
(3 answers)
Closed 5 years ago.
I don't know why the images aren't showing in Django. Something to do with the media root?
settings code
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')'
models code
from django.db import models
from django.core.urlresolvers import reverse
Create your models here.
class Post(models.Model):
## Post Properties
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
summary = models.CharField(max_length=255)
content = models.TextField()
published = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to='img',default='media/placeholder.png')
class Meta:
ordering = ['-created']
def __unicode__(self):
return u'%s'% self.title
def get_absolute_url(self):
return reverse('blog.views.post', args=[self.slug])
I didn't add a url for the picture, could that be a problem?
urls
urlpatterns = [
url(r'^post/(.*)', blogViews.post),
url(r'^about/$', blogViews.about),
url(r'^$', blogViews.index),
url(r'^admin/', admin.site.urls),
index.html code
<img src="{{post.image}}">
<p> {{post.image}} </p>
**Views.py **
from django.shortcuts import render, render_to_response, get_object_or_404
from django.http import HttpResponse
from .models import Post
# Create your views here.
def index(request):
posts = Post.objects.all()
return render(request, 'index.html', {'posts': posts})
def post(request, slug):
return render_to_response('post.html', {
'post': get_object_or_404(Post,slug=slug)
})
def about(request):
return render(request, 'about.html', {})
In the website all that shows is a blank picture as well as the file name (either 'placeholder.png' which is the default or img/... which I uploaded through admin)
Edit:
This was marked as a duplicate, I saw that post and tried to change my code to reflect that code but it wasn't working. Figured it would be better to post my own.
Thanks in advance, first question on this site!
Try this,
<img src="{{post.image.url}}">
Also, add in your urls.py,
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
For learning more about serving static, refer the documentation here...

Categories