It is not saving up the data:
# Models
class Comment(models.Model):
created = models.DateTimeField(auto_now_add=True)
author = models.CharField(max_length=60)
body = models.TextField()
# Forms
class CommentForm(ModelForm):
class Meta:
model = Comment
#Views.py
def add_comment(request):
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
save_it = form.save()
save_it.save()
comment = form.cleaned_data["body"]
return render(request, 'task-result.html', {
'form': form, 'comment': comment,
})
else:
form = CommentForm()
return render(request, 'Task-form.html', {
'form': form,
})
AS you may see, I am not only trying to save comment's data to database but also and print it comment out. So where is my mistake?
Related
Scenario: A user has already completed a form.
What's required: How do you return a completed model form in Views.py? I have followed a few guides on here such as this one with no success. Here is my shortened code containing the relevant sections:
models.py
APPROVAL_CHOICES = [
(None, 'Please select an option'),
("Yes", "Yes"),
("No", "No"),
]
class Direct(models.Model):
def __str__(self):
return self.registered_company_name
class Meta:
verbose_name_plural = 'Company Direct Application'
user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True)
registered_company_name = models.CharField(max_length=250,verbose_name="Company")
trading_name = models.CharField(max_length=250)
registered_company_address = models.CharField(max_length=250)
further_details_required = models.CharField(max_length=3, hoices=APPROVAL_CHOICES, blank=True, verbose_name="Further Details Required")
forms.py
class CompanyDirectApplication(forms.ModelForm):
class Meta:
model = Direct
fields = ["registered_company_name", "trading_name", "registered_company_address"]
widgets = {
"registered_company_name": TextInput(attrs={'class': 'form-control'}),
"trading_name": TextInput(attrs={'class': 'form-control'}),
"registered_company_address": TextInput(attrs={'class': 'form-control'})
}
views.py
if Direct.objects.filter(further_details_required="Yes", user=request.user).exists():
form = CompanyDirectApplication()
form.instance.user = request.user
return render(request, 'direct_application.html', {'form': form})
#otherwise render a blank model form
else:
form = CompanyDirectApplication()
return render(request, 'direct_application.html', {'form': form})
The HTML template renders the form with a simple {{form.as_p}}. How do I return a completed model form in Views.py to render in my template {{form.as_p}}?
You can use instance parameter to initialize the form with object:
directs = Direct.objects.filter(further_details_required="Yes", user=request.user)
if directs.exists():
form = CompanyDirectApplication(instance=directs.first())
else:
form = CompanyDirectApplication()
return render(request, 'direct_application.html', {'form': form})
Change the view like this. Its will fill the existing data.
if Direct.objects.filter(further_details_required="Yes", user=request.user).exists():
direct = Direct.objects.get(further_details_required="Yes", user=request.user)
form = CompanyDirectApplication(instance=direct)
return render(request, 'direct_application.html', {'form': form})
else:
form = CompanyDirectApplication()
return render(request, 'direct_application.html', {'form': form})
I have a simple model which has four different fileFields for uploading different files and images.
this is my models:
class DocumentInfo(models.Model):
id = models.AutoField(primary_key=True)
certificate = models.FileField(upload_to="documents", null=True)
id_card = models.FileField(upload_to="documents", null=True)
service_certificate = models.FileField(upload_to="documents", null=True)
educational_certificate = models.FileField(upload_to="documents", null=True)
users need to simply upload some images in four individual fields so, I created a simple form and passed it to views like this:
class DocumentForm(forms.ModelForm):
class Meta:
model = DocumentInfo
fields = ['certificate','id_card','service_certificate','educational_certificate']
views.py:
def document_info(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect('document')
if 'delete' in request.GET:
return delete_item(DocumentInfo, request.GET['id'])
else:
form = DocumentForm()
documents = DocumentInfo.objects.filter(user=request.user)
context = {
'form': form,
'documents': documents,
}
return render(request, 'reg/documents.html', context)
it works just fine at first but I cant reupload anything! the uploaded image neither gets saved the second time around nor deleted. what am I doing wrong?
try this.
views.py
def document_info(request):
documents = DocumentInfo.objects.filter(user=request.user).order_by('-pk')
if request.method == 'POST':
if documents:
form = DocumentForm(request.POST, request.FILES,instance=documents[0])
else:
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
if not documents:
form.instance.user = request.user
form.save()
return redirect('document')
else:
if documents:#if the user already has a document.
form = DocumentForm(instance=documents[0])
else:
form = DocumentForm()
context = {
'form': form,
'documents': documents,
}
return render(request, 'reg/documents.html', context)
I've a category and I've added a form for user in each category.
So I've two fields to fill and after filling them correctly I submit but the page reload, and nothing appears in my DB... only one error on Image field: This field required. I don't really know what's wrong here.
class Picture(models.Model):
catego = models.ForeignKey(Catego,on_delete=models.CASCADE,related_name="catego_pictures")
user = models.ForeignKey(User, blank=True, null=True,on_delete=models.CASCADE,related_name='user_pictures')
image = models.ImageField(upload_to='nutriscore/')
pictureoption = models.CharField(max_length=20,choices=Pictureoption.choices,default=Pictureoption.HOME,)
publishing_date = models.DateField(auto_now_add=True)
class CreatePictureForm(forms.ModelForm):
def __init__(self,*args,**kwargs):
super(CreatePictureForm, self).__init__(*args,**kwargs)
self.helper = FormHelper()
self.helper.form_method="post"
self.helper.layout = Layout(
Field("image",css_class="single-input"),
Field("pictureoption",css_class="single-input"),
)
self.helper.add_input(Submit('submit','Upload a pic',css_class="single-input textinput textInput form-control"))
class Meta:
model = Picture
fields = [
'image',
'pictureoption',
]
def __str__(self):
return self.catego.name
views.py
#login_required(login_url='/cooker/login')
def catego(request, slug):
catego = Catego.objects.get(slug=slug)
context = {
'catego': catego
}
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = CreatePictureForm(request.POST)
# check whether it's valid:
if form.is_valid():
form.instance.catego = self.object
form.instance.user = self.request.user
form.save()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
else:
form = CreatePictureForm()
context['form'] = form # add `form` to the context
return render(request, 'post_catego.html', context)
here is the answer
#login_required(login_url='/cooker/login')
def catego(request, slug):
catego = Catego.objects.get(slug=slug)
context = {
'catego': catego
}
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = CreatePictureForm(request.POST, request.FILES)
# check whether it's valid:
if form.is_valid():
form.instance.catego = catego
form.instance.user = request.user
form.save()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
else:
form = CreatePictureForm()
context['form'] = form # add `form` to the context
return render(request, 'post_catego.html', context)
This is my code for my view:
def edit(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
else:
if form.is_valid():
user = form.save()
form = EditProfileForm(instance=request.user)
args = {'form': form}
return render(request, 'social/edit.html', args)
And here is the code for the form:
class EditProfileForm(UserChangeForm):
edit ='social/edit.html'
class Meta:
model = UserProfile
fields = ('description', 'image')
Here is the model:
class UserProfile(models.Model):
description = models.CharField(max_length=300, default=' ', blank=True)
image = models.ImageField(upload_to='profile_image', blank=True)
if you need any more information to help I would be more than gladly to give it to you
The problem is with the view function.
Every View must return some sort of response (HTTP Response in General)
you have an if else statement in your view if its a post it will just execute
form = EditProfileForm(request.POST, instance=request.user)
and then it doesn't return anything.
I think you have to do is,
For GET Request (when you visit the url, it has to render the form)
if request.method == 'GET':
form = EditProfileForm(instance=request.user)
args = {'form': form}
return render(request, 'social/edit.html', args)
For POST request (when you send POST to this view or different one)
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
user = form.save()
# use render/redirect as needed. make sure it returns an HTTP Response
# note that render method also return HTTP Response
return HttpResponse('Done')
Make sure Form class is simply this
class EditProfileForm(UserChangeForm):
class Meta:
model = UserProfile
fields = ('description', 'image')
This question already has answers here:
Saving Many To Many data via a modelform in Django
(2 answers)
Closed 4 years ago.
There's form with many fields (Date, Char, Text, Image, URL...) and they works fine. I mean values are submitted to DB as they must. But when I added ManyToManyField, it didn't save the value of this MultipleChoice form to DB. Any ideas why?
models.py:
class EventTag(models.Model):
tags = models.CharField(max_length=300)
def __str__(self):
return self.tags
class Article(models.Model):
source = models.CharField(max_length=100)
source_img = models.ImageField(default='default.png', blank=True)
#other fields
event_tags = models.ManyToManyField(EventTag, blank=True)
forms.py:
class CreateArticle(forms.ModelForm):
class Meta:
model = models.Article
fields = ['source', 'source_img', 'event_tags', ]
views.py:
def article_create(request):
if request.method == 'POST':
form = forms.CreateArticle(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.author = request.user
instance.save()
return redirect('articles:list')
else:
form = forms.CreateArticle()
return render(request, 'articles/article_create.html', { 'form': form })
after save your form you must call form.save_m2m(). your view must be like this:
def article_create(request):
if request.method == 'POST':
form = forms.CreateArticle(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.author = request.user
instance.save()
form.save_m2m()
return redirect('articles:list')
else:
form = forms.CreateArticle()
return render(request, 'articles/article_create.html', { 'form': form })