django model form is not displaying any errors - django

I am not getting any errors in the template. It just gives me back the form without error. Although the uploading function works fine, but if I don't give any input it doesn't give me any errors. How would I get the errors if there are in my template?
html:
{% block content %}
<form action="/{{ user.username }}/upload_photos/" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Upload"/>
</form>
{% endblock %}
views.py:
def upload_photos(request, user_name):
user = User.objects.get(username=unquote(user_name))
if request.method=='POST':
form = PhotoForm(request.POST, request.FILES)
if form.is_valid():
forum = form.save(commit=False)
forum.user = user
forum.save()
return HttpResponseRedirect('/'+user.username+'/photos')
else:
form = PhotoForm()
return render(request, 'upload_photos.html',{'form':form})
else:
form = PhotoForm()
return render(request, 'upload_photos.html',{'form':form})

I've commented out the line that empties your form.
def upload_photos(request, user_name):
user = User.objects.get(username=unquote(user_name))
if request.method=='POST':
form = PhotoForm(request.POST, request.FILES)
if form.is_valid():
forum = form.save(commit=False)
forum.user = user
forum.save()
return HttpResponseRedirect('/'+user.username+'/photos')
else:
# form = PhotoForm() Don't overwrite the submitted form.
return render(request, 'upload_photos.html',{'form':form})
else:
form = PhotoForm()
return render(request, 'upload_photos.html',{'form':form})

Related

django model based forms - why isn't form valid?

I'm trying to make model based form but something went wrong.
model:
class Topic(models.Model):
name = models.CharField(max_length=200)
icon = models.ImageField(upload_to = 'images/')
form:
class TopicCreationForm(ModelForm):
class Meta:
model = Topic
fields = '__all__'
view:
def TopicCreateView(request):
form = TopicCreationForm()
if request.method == 'POST':
form = TopicCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
print('aaa') # It displays in console
context = {'form':form}
return render(request, 'blog/topic_form.html', context)
my form html part
<form method="POST">
{% csrf_token %}
<fieldset >
<legend> New Topic</legend>
{{ form|crispy }}
</fieldset>
<div>
<input type="submit" value="submit" class="button-33" role="button">
</div>
</form>
where did i make mistake ?
You need to pass both request.POST and request.FILES [Django-doc], so:
def topic_create(request):
if request.method == 'POST':
form = TopicCreationForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
print('aaa') # It display in console
else:
form = TopicCreationForm()
context = {'form':form}
return render(request, 'blog/topic_form.html', context)
In the HTML form, you need to specify that the files should be encoded with the enctype="…" attribute [mdn]:
<form method="post" enctype="multipart/form-data">
…
</form>

Django I need upload file button only remove choose file and don't need refresh page when upload

I want to upload only button and don't need refresh when upload how to fix this
model_form_upload.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" >Upload</button>
</form>
forms.py
class DocumentForm(forms.ModelForm):
class Meta:
model = DocumentFile
fields = ['document']
views.py
def model_form_upload(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
form = DocumentForm()
print(form)
return render(request, 'model_form_upload.html', {'form': form})

request.FILES empty, though file is present in request

Following the example on the django website I'm trying to upload a file, perform checks on the contents, then feedback to the user and store the file contents.
However, I'm having trouble with the request.FILES which is always empty. My code is as follows (note the output after the print statements):
**forms.py**
class UploadFileForm(forms.Form):
data_import = forms.FileField()
class Meta:
model = Recipe
fields = ('data_import',)
**view**
def recipes_list(request):
template = 'recipes/recipes_list.html'
if request.method == 'GET':
user = request.user
queryset = Recipe.objects.filter(user=user)
form = UploadFileForm()
return render(request, 'recipes/recipes_list.html', context={'recipes': queryset, 'form': form})
elif request.method == 'POST':
print(request.FILES) # <MultiValueDict: {}>
print(request.POST) # <QueryDict: {'csrfmiddlewaretoken': ['...'], 'data_import': ['recette.json']}>
form = UploadFileForm(request.POST, request.POST.data_import)
if form.is_valid():
return HttpResponseRedirect(template)
else:
print(form.errors)
**template**
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">submit</button>
</form>
The error I'm getting is:
<ul class="errorlist"><li>data_import<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
But i can see that the file is uploaded, and is in the request.POST.get('data_import').
I would like to run validation on the form, but I can't do this if request.FILES is empty.
I'm clearly doing something wrong, can someone please point me in the right direction?
<form method="post" enctype= multipart/form-data>
{% csrf_token %}
{{ form }}
<button type="submit">submit</button>
</form>
change your form to the upper one

My function Register catches more mistakes, in Django framework

I have a problem:
In my function register() I use FormRegistration of Django and my custom ProfilForm, but I cannot display the different errors (username not unique, passwords do not match, ...).
views.py
def register(request):
if request.method == 'POST':
form = UserCreate(request.POST)
form2 = ProfilForm(request.POST)
if form.is_valid() and form2.is_valid():
user = form.save()
form2 = form2.save(commit=False)
form2.user = user
form2.skill = form2.cleaned_data.get('skill')
form2.board = form2.cleaned_data.get('board')
form2.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('/accueil')
else:
form = UserCreate()
form2 = ProfilForm()
return render(
request,
'registration/register.html',
{'form2': form2},
{'form': form})
This is my template register.html for displaying errors :
{% if form.errors %}
<div class="alert alert-danger">
<p><strong>Error !</strong> <p>There was a problem while trying to register, check your fields.</p></p>
</div>
{% endif %}
{% if form.errors %}
<div class="alert alert-danger">
<p><strong>Error !</strong> <p>{{ form.username.errors|striptags }}</p></p>
</div>
{% endif %}
Any suggestions?
There are a few issues:
The line form2 = form2.save(commit=False) does not look right; you should assign the output of save() to another variable, but right now you are just overriding form2.
The last return statement should only get one dict for context:
Change you code
return render(
request,
'registration/register.html',
{'form2': form2},
{'form': form})
to
return render(
request,
'registration/register.html',
{'form2': form2, 'form': form})

Django Requiring Optional Form Field Error

To new readers: Neverwalkaloner's solution solved the initial error but the photo upload is still required and making required false in forms.py gives me a MultiValueDictKeyError. Any help on making it optional would be greatly appreciated.
I have a model and form to upload either a picture and text, or just text. My intention, actually was to make it a choice between an image, text or both and any help with that would be appreciated, but I digress. Uploading only works when an image is included, if it is just text, I get the error:
The view lesyeux.views.posts didn't return an HttpResponse object. It
returned None instead.The view lesyeux
My model is:
class Post(models.Model):
image = models.ImageField(upload_to='uploaded_images', blank=True,
null=True)
text_post = models.CharField(max_length=1000)
author = models.ForeignKey(User)
My form is:
class PostForm(forms.ModelForm):
image = forms.FileField(label='Select an image file',
help_text='Please select a photo to upload')
text_post = forms.CharField(help_text="Please enter some text.")
class Meta:
model = Post
fields = ('image', 'text_post',)
exclude = ('author',)
My view is:
def posts(request, id=None):
neighborhood = get_object_or_404(Neighborhood, id=id)
form = PostForm()
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
post = Post(image = request.FILES['image'])
post = form.save(commit=False)
post.author = request.user
post = post.save()
next = request.POST.get('next', '/')
return HttpResponseRedirect(next)
else:
form = PostForm()
posts = Post.objects.all().order_by('-id')
return render(request, 'posts.html', context = {'form':form,
'posts':posts, 'neighborhood':neighborhood})
and my form is:
<form id="PostForm" method="post" action="/view/{{ neighborhood.id }}/posts/" enctype="multipart/form-data">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input type="hidden" name="next" value="{{ request.path }}">
<input type="submit" name="submit" value="Post" />
</form>
Your view doesnt return response if form is not valid. To fixt it rewrite view like this:
def posts(request, id=None):
neighborhood = get_object_or_404(Neighborhood, id=id)
form = PostForm()
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
post = Post(image = request.FILES['image'])
post = form.save(commit=False)
post.author = request.user
post = post.save()
next = request.POST.get('next', '/')
return HttpResponseRedirect(next)
else:
form = PostForm()
posts = Post.objects.all().order_by('-id')
return render(request, 'posts.html', context = {'form':form, 'posts':posts, 'neighborhood':neighborhood})