My form for uploading photos does not work. Django - django

When I use the form provided by django admin everything works fine. But after creating my own form, django does not write data to my model. Is something missing in my code?
Models.py
class Offert(models.Model):
name = models.CharField(max_length=50)
file = models.FileField(upload_to='app/documents/')
forms.py
class OffertFormCV(forms.ModelForm):
class Meta:
model = Offert
fields = ( 'name',
'file')
views.py
def my_views(request):
if request.method == 'POST':
form = OffertFormCV(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('app:thank_you_page'))
else:
form = OffertFormCV()
context = {'form': form}
return render(request, 'form_application.html', context)
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('app.urls', namespace='app'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'app/media')
form_application.html
<form method="post">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-primary">Send</button>
</form>
After sending the form, nothing happens. Any help will be appreciated.

You need to add enctype="multipart/form-data" to your form to be able to upload files:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-primary">Send</button>
</form>

Related

Problem is that image is not saving . when i am select image and upload all code working properly but image does not save django

Problem is that image is not saving. when I am select an image and upload all the code working properly but the image does not save. I checked all the code line by line I do not understand what's the problem. I also see the media file any image is saved or not, but the image wasn't saved.
this is models.py in this file I use the image field
models.py
class Answer (models.Model):
question=models.ForeignKey(Question,on_delete=models.CASCADE)
user=models.ForeignKey(User,on_delete=models.CASCADE, null=True)
img=models.ImageField(null=True,blank=True,upload_to='Answer_Img')
detail=RichTextUploadingField()
add_time=models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.detail
forms.py
class AnswerForm(ModelForm):
class Meta:
model=Answer
fields=('detail','img')
labels={'img':'Upload Image'}
views.py
def answer(request,pk,slug):
try:
trend=Question.objects.get(pk=pk,slug=slug)
except:
raise Http404("Post Does Not Exist")
tags=trend.tags.split(',')
ans=Answer.objects.filter(question=trend)
answerform=AnswerForm
if request.method=='POST':
answerData=AnswerForm(request.POST)
if answerData.is_valid():
answer=answerData.save(commit=False)
answer.question=trend
answer.user=request.user
answer.save()
p=messages.success(request,'Answer has been submitted.')
return HttpResponseRedirect(trend.slug)
return render(request,"ask/answer.html" ,{
'trends':trend,
'tags':tags,
'answer':ans,
'form':answerform,
})
answer.html
{% if user.is_authenticated %}
<div class="container">
<div class="py-5 text-center bg-secondary text-white">
<h1 class="mb-3">Upload Image</h1>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form}}
<input type="submit" class="btn btn-danger" value="Upload">
</form>
</div>
{% else %}
<h3><P>Sign In/Sign Up before posting answers</P></h3>
<h4><li>Sign In</li><h4>
<h4> <li>Sign Up</li><h4>
{% endif %}
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
urls.py
urlpatterns = [
# my url patterns here
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Use request.files to get the img. please check if the media folder is in your base directory and the subfolder is named correctly.
if request.method == "POST":
answer_form = Answer_form(data=request.POST)
if(answer_form.is_valid()):
ans = answer_form.save(commit=False)
#ans.user = user
if 'img' in request.FILES:
ans.img = request.FILES['img']
ans.save()
else:
print(answer_form.errors)
Here is the documentation page :
File Uploads

How to upload and display videos on django

I have been trying to add a view that uploades videos and displays them in the main template, well while adding code, I realized that the view that uploades the file isn't being rendered while the view that shows the uploded file in the template gets rendered but it doesnt show anything because nothing is being uploded. I dont know where the error might be but I think it is on the views.py, maybe the urls.py.
views.py
def upload(request):
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
return redirect('home')
print('succesfully uploded')
else:
form = PostForm()
print('didnt upload')
return render(request, 'home.html', {'form': form})
def home(request):
contents = Post.objects.all()
context = {
"contents": contents,
}
print("nice")
return render(request, 'home.html', context)
urls.py
urlpatterns = [
path('', views.home, name='home'),
path('upload', views.upload, name='upload'),
]
models.py
class Post(models.Model):
text = models.CharField(max_length=200)
video = models.FileField(upload_to='clips', null=True, blank="True")
user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username')
def __str__(self):
return str(self.text)
forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('text', 'video')
exclude = ['user']
home.html (uplodes the content and displays it)
<div class="user-content">
{% for content in contents %}
<li class="">{{ content.text }}
{% if content.video %}
<video class="video" width='400'>
<source src='{{ content.video.url }}' type='video/mp4'>
</video>
{% endif %}
</li>
{% endfor %}
</div>
<div class="uplodes">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="text" placeholder="Add a comment..." required="" id="id_text">
<input type="file" name="video" id="id_video">
<button class="submit-button" type="submit">Save</button>
</form>
</div>

how do I store an image in views file in Django

I am making a Django website where I need to display images selected by user.
These are the things I've done:
Html form for image:
<form action="" method="POST">
{% csrf_token %}
<div class="form-group">
<label >Article Logo</label>
<input type="file" class="btn btn-primary" name="article_image">
</div>
<input type="submit" class="btn btn-success">
</form>
models.py
class Content(models.Model):
article_image = models.ImageField(upload_to = 'media', null=True)
views.py
def submit_article(request):
if request.method == 'POST':
a_image = request.FILES['article_image']
new_article.article_image = a_image
new_article.save()
I've added below code to settings.py to specify media directory:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Added below code to urls.py of the website:
urlpatterns = [
path(r'admin/', admin.site.urls),
url(r'', include('logio.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The form is not able to add images to the media folder. If I'm adding images through the admin panel it works.
Thanks in advance....
You need to add enctype="multipart/form-data" to your form, like this:
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
For more information, please check the documentation.
Just a suggestion, it is better to use a Django form to handle this. For example, you can have a form:
class ContentForm(forms.ModelForm):
class Meta:
model = Content
fields = ['article_image']
Then pass this form via context to template and render it:
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<input type="submit" value="submit'>
</form>
Finally, handle validation in view:
def submit_article(request):
if request.method == 'POST':
form = ContentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
...

Generic view UpdateView from django tutorial does not save files or images

UpdateView does not save files or images anywhere, what can be the problem?
settings:
MEDIA_ROOT=""
article_form.html:
<form method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save">
</form>
views.py:
from django.views.generic.edit import UpdateView
class updatingexample(UpdateView):
model = Article
fields = ['file1','file2','photo']
url.py
app_name = 'polls'
urlpatterns=[
path('<int:pk>/upd/', updatingexample.as_view(),name="ugh")
]
models:
class Article(models.Model):
title = models.CharField(max_length=200)
pub_date = models.DateField()
file1 = models.FileField(upload_to='uploads/',blank=True)
file2 = models.FileField(upload_to='uploads/%Y/%m/%d/',blank=True)
photo = models.ImageField(upload_to='uploads',blank=True)
def get_absolute_url(self):
return reverse('polls:ugh', kwargs={'pk': self.pk})#back to itself
Just add on your form
enctype="multipart/form-data"
So it'll end like:
<form method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save">
</form>
And I also suggest that set MEDIA_ROOT and MEDIA_URL in your settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
And add it at the end of your urls.py
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

redirection to success_url is not working with django 1.10

I have a pretty simple contact us form but the success_url is not working. The page isn't getting redirected to home after successful form submission.
I've followed the documentation available here https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-editing/
class ContactFormView(SuccessMessageMixin, FormView):
form_class = ContactForm
template_name = 'contact.html'
success_message = 'Thank you!'
success_url = reverse_lazy('home')
def form_valid(self, form):
form.send_email()
return super(ContactFormView, self).form_valid(form)
form_valid is being called but redirection to sucess_url doesn't happen and there are no errors.
Thanks for your help.
-------------UPDATED-----------------
forms.py
class ContactForm(forms.Form):
name = forms.CharField(widget = TextInput(attrs={'placeholder': 'Your Name'}))
email = forms.CharField(widget = EmailInput(attrs={'placeholder': 'Email'}))
phone = forms.CharField(widget = TextInput(attrs={'placeholder': 'Phone'}))
comment = forms.CharField(widget = forms.Textarea(attrs={'placeholder': 'Please write a comment'}))
def send_email(self):
# send email using the self.cleaned_data dictionary
print("email sent!")
urls.py
import web.views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^contact/', web.views.ContactFormView.as_view(), name='contact'),
url(r'^$', web.views.home, name='home')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
contact.html
<div class="as-form">
<form method="post" class="myform" action="{% url 'contact' %}">
{% csrf_token %}
{% if form.errors %}{{ form.errors }}{% endif %}
<p> {{form.name}} </p>
<p> {{form.phone}} </p>
<p> {{form.email}} </p>
<p class="as-comment"> {{form.comment}} </p>
<hr>
<p class="as-submit"> <input type="submit" value="Submit" class="as-bgcolor"> </p>
</form>
</div>
I don't know how you set it up but the below works brilliantly (Django 1.10, Python 3.5)
# urls.py
urlpatterns = [
url(r'^$', home_view, name='home'),
url(r'^form/$', ContactFormView.as_view(), name='contact')
]
# forms.py
class ContactForm(forms.Form):
name = forms.CharField(max_length=20)
def send_email(self):
print('Email sent!')
# views.py
# Your ContactFormView as is
# contact.html
<form action="" method="post">{% csrf_token %}
{% if form.errors %}{{ form.errors }}{% endif %}
{{ form.as_p }}
</form>