Django: model doesn't create from models form - django

I try to create new object from model form, but objects isn't saved.
models.py
class VideoFile(models.Model):
name = models.CharField(max_length=200, blank=True)
file = models.FileField(upload_to="video/", validators=[validate_file_extension])
forms.py
class VideoCreateForm(ModelForm):
class Meta:
model = VideoFile
fields = ['name', 'file']
views.py
def add_video(request):
if request.method == "POST":
form = VideoCreateForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save()
messages.success(request, "saved")
else:
messages.error(request, 'No success!.')
return redirect('vtv:video')
else:
form = VideoCreateForm()
return render(request, "vtv/video_add.html", {'form': form})
templates.html
<h3>Add new video</h3>
<form method = "post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" />
</form>
What's wrong?

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 MultiValueDictKeyError for upload file

There has a file upload page for upload file to a object by id in model. However, it shown MultiValueDictKeyError after submitted. I would appreciate if any help.
models.py:
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
items = models.ManyToManyField(OrderItem)
img_upload = models.FileField(upload_to='payment', null=True)
forms.py:
class Upload_File(forms.Form):
class Meta:
model = Order
fields = ('img_upload')
views.py:
def upload_page(request, id):
order = get_object_or_404(Order, id=id)
form = Upload_File(request.POST or None, request.FILES or None)
if request.method == 'POST':
order.img_upload = request.FILES['file']
if form.is_valid():
form.save()
messages.success(request, 'Succeed')
return redirect('user_info')
else:
form = Upload_File()
context = {
'form': form,
}
return render(request, 'upload.html', context)
html:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input class="form-group" type="file" name="file">
<button class="form-group" type="submit">Submit</button>
</form>

Django is rendering empty template to create new profile instead of submitting form

First some code:
models.py
class Findings(models.Model):
patient = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE)
finding_type = models.CharField(max_length=35, null=True)
upload = models.FileField(null=True, blank=True)
date_created = models.DateField(auto_now=True)
description = models.TextField(null=True, blank=True)
def __str__(self):
return self.finding_type
forms.py
class AddFindingForm(ModelForm):
class Meta:
model = Findings
fields = ('finding_type', 'description', 'upload', 'patient')
labels = {
'finding_type' : _('Rodzaj badania'),
'description': _('Opis'),
'upload': _('Dodaj plik'),
}
views.py
def add_finding(request):
form = AddFindingForm()
if request.method == 'POST':
form = UserProfileForm(request.POST, request.FILES)
if form.is_valid():
form = form.save(commit=False)
form.patient = request.user.profile
form.save()
return redirect('profile')
context = {'form': form}
return render(request, 'add_finding.html', context)
template
{% block content %}
<form method="POST" enctype="multipart/form-data" action="">
{% csrf_token %}
{{ form.as_p}}
<button type="submit"> Wyślij </button>
</form>
{% endblock %}
So, everytime i'm trying to submit a filled form it displays another form to create new Profile, even if i'm setting patient manually.
The empty form it's displaying is on the same url.
I have no idea why it's doing that...
You are submitting your request.POST data to wrong form. Doing this user's submitted data never gets into AddFindingForm() instead it should be,
def add_finding(request):
form = AddFindingForm()
if request.method == 'POST':
form = AddFindingForm(request.POST, request.FILES) # Change Here
if form.is_valid():
form = form.save(commit=False)
form.patient = request.user.profile
form.save()
return redirect('profile')
context = {'form': form}
return render(request, 'add_finding.html', context)

Django ModelForm does not save to database

I try to add a comment but it does not save it to the database. There is no error.
My Views is
def add_comment(request, id):
article = get_object_or_404(Article, id=id)
if request.method == "POST":
form = CommentForm(request.POST,instance=article)
if form.is_valid():
comment = form.save(commit=False)
comment.post = article
comment.save()
return redirect('articles:detail', pk=article.pk)
else:
form = CommentForm()
template="article/comment.html"
return render(request, template, {'form': form})
comment.html:
<form method="POST">{% csrf_token %}
{{form.as_p}}
<button type="submit">Send</button>
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('name', 'comment')

django: if model has related models (ForeignKey) display Fields in main modelform

I have two models:
class Post(models.Model):
image = models.ImageField(upload_to='%Y/%m/%d')
title = models.CharField(max_length=200)
class Addimg(models.Model):
addimages = models.ForeignKey('Post', null=True)
addimg = models.ImageField(upload_to='images')
I wish to add images to my Post model with the "Addimg" model which works fine so far, but now i want that when I edit my parent model (Post), all the appended "Addimg" models also appear in the form. How could i do that? What would be the simplest solution?
Here is my view which handles my "parent" form:
def edit(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(request.POST, request.FILES, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('blog.views.detail', pk=post.pk)
else:
form = PostForm(instance=post)
return render(request, 'blog/edit.html', {'form': form})
and my forms.py:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('image', 'title',)
class AddimgForm(forms.ModelForm):
class Meta:
model = Addimg
fields = ('addimages', 'addimg',)
In my form template I have:
<form enctype="multipart/form-data" method="POST" class="post-form">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" >Save</button>
</form>
I would be very happy about any tips or usefull links since i'm very new to django/programming I even don't know the right keywords to search for. Thanks
Have a look at inline formsets.
Ok got it easy thing for django:
in forms.py:
from django.forms.models import inlineformset_factory
MyFormSet = inlineformset_factory(Post, Addimg, extra=1, fields = ('addimages', 'addimg',))
in views.py:
from .forms import PostForm, MyFormSet
def manageimages(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
formset = MyFormSet(request.POST, request.FILES, instance=post)
if formset.is_valid():
formset.save()
post.save()
return redirect('blog.views.someview')
else:
formset = MyFormSet(instance=post)
return render(request, 'blog/myformsettemplate.html', {'formset': formset})
and in myformsettemplate.html:
<form enctype="multipart/form-data" method="POST" class="post-form">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
<div class="third">
{{ form.as_p }}
</div>
{% endfor %}
<button type="submit" >Save</button>
</form>