I have this view for my form:
if request.method == 'POST':
vehicle = VehicleForm(request.POST or None)
photos = PhotosFormSet(request.POST or None)
if vehicle.is_valid() and photos.is_valid():
new = vehicle.save()
photos = PhotosFormSet(request.POST, instance=new)
photos.save()
return HttpResponseRedirect('/vehicles/')
else:
prefix = "09-"
queryset = Vehicle.objects.all().order_by("stock_number")
if queryset == None:
last_rec = queryset.reverse()[0]
a = str(last_rec.stock_number)
b = int(a[-3:])+1
next = prefix+str(b)
else:
next = prefix+"001"
vehicle = VehicleForm(initial={'stock_number': next})
photos = PhotosFormSet(instance=Vehicle())
However when I try to save the record, the image field in PhotosFormset gives an error saying This field is required.
PhotosFormset is declared as PhotosFormSet = generic_inlineformset_factory(Photo, extra=5)
What am I missing here?
You don't appear to be binding uploaded files to your formset. You need to pass in request.FILES as well as request.POST:
photos = PhotosFormSet(request.POST, request.FILES, instance=new)
More info in the Django docs
Related
How to save image in Django form that is not validated. I could able to save data of Charfield using
title = form_name["title"].data
Other data that are passed are getting saved but image is not getting saved. How to fix it.
form = forms.FormName()
if request.method == "POST":
form_name = FormName(data = request.POST)
title = form_name["title"].data
thumbnail = form_name["thumbnail"].data
content = form_name["content"].data
tags = form_name["tags"].data
instance = htmlpage(title=title, thumbnail=thumbnail, content= content, tags=tags, by=request.user)
instance.save()
I'm working with Modelforms and would like to set the initial value of the "feeder" field. I get the following Type Error: "invalid literal for int() with base 10: 'None'" What might be the problem?
Many thanks all
forms.py:
class CashFlowForm(forms.ModelForm):
class Meta:
model = models.CashFlow
fields = ['type', 'amount', 'description','date']
widgets = {'date': DatePicker()}
views.py:
def create_cashflow(request, fundslug):
funddetail = Fund.objects.get(slug=fundslug)
if request.method == 'POST':
cf = CashFlowForm(request.POST)
cf.feeder = funddetail.feeder
if cf.is_valid():
instance_cf = cf.save()
messages.success(request, 'Cash Flow successfully added!')
return redirect('funds:create_cashflow', fundslug = fundslug)
else:
cf = CashFlowForm()
return render(request, 'funds/create_cashflow.html', {'cf': cf})
I fink funddetail.feeder return None or You can try
cf.cleaned_data['feeder'] = funddetail.feeder
Models don't matter unless there's a foreign key involved. For the Type Error, it's mostly to do with the value your model fields are getting from the form.
For assigning value after form submission, do something like
if request.method == 'POST':
cf = CashFlowForm(request.POST)
cf.save(commit=False)
cf.feeder = funddetail.feeder
cf.save()
I have tried various options for this but no luck so far. I am trying to get instance data to be pre-populated into my ModelField. Here is what I have:
forms.py
class edit_project_info(ModelForm):
project_name = forms.CharField(max_length=150)
class Meta:
model = Project
exclude = ['project_type', 'created_date', 'start_date', 'end_date', 'pm_scope', 'dev_scope', 'design_scope', 'testing_scope' ]
View.py
def edit_project (request, offset):
this_project = Project.objects.get(pk=offset)
data = {'project_name' : 'abc'}
if request.method == 'POST':
form = edit_project_info(request.POST, instance=this_project, initial=data)
if form.is_valid():
form.save()
return HttpResponseRedirect('/project_profile/%s/' % offset)
else:
form = edit_project_info()
All I get is an empty field. I can add the initial value to forms.py, but then it is static rather than populated based on the form instance. What I have done here with creating a dict and then passing it to initial in the form instance does not seem to do anything. I'm sure I am missing something basic. Any help would be great! Thanks ahead of time.
Two last lines recreate your form variable. Just remove else: form = edit_project_info():
def edit_project (request, offset):
this_project = Project.objects.get(pk=offset)
data = {'project_name' : 'abc'}
form = edit_project_info(request.POST, instance=this_project, initial=data)
if request.method == 'POST':
if form.is_valid():
form.save()
return HttpResponseRedirect('/project_profile/%s/' % offset)
# else:
# form = edit_project_info()
# ...
i'm new in django and i have a problem with Uploading File Please Help me!! :X
here is my view.py
def uploadimg(request):
try:
user = request.session['user']
if request.method == 'POST':
form = User_image_form(request.POST, request.FILES)
#if form.is_valid():
usr_img = User_image(imgfile = request.FILES['imgfile'])
return HttpResponse("yes")
#usr_img.user = user
usr_img.save()
return HttpResponse("yees the first upload is right !! :X")
else:
return HttpResponse("Noooooo!!!")
except:
pass
this is my form.py
class User_image_form(forms.Form):
imgfile = forms.FileField()
and this is my models.py
class User_image(models.Model):
imgfile = models.ImageField(upload_to = 'User-Image')
#user = models.ForeignKey(User_account)
and i have problem in view.py at line which
usr_img = User_image(imgfile = request.FILES['imgfile'])
and it's never get to the
return HttpResponse("Yes")
error:
Exception Value: The view User.views.uploadimg didn't return an HttpResponse object.
Plz Help
If there is an exception, you are not returning an HttpResponse object. Hence the error.
use form.is_valid() to see if the form is valid.
Something like this:
if request.method == 'POST':
form = User_image_form(request.POST, request.FILES)
if form.is_valid():
usr_img = User_image(imgfile = form.cleaned_data['imgfile'])
usr_img.user = user
usr_img.save()
return HttpResponse("yees the first upload is right !! :X")
else:
print form.errors #for debugging purposes only.
return HttpResponse("Noooooo!!!")
I have an object Task and a form that saves it. I want to automatically asign created_by field to the currently logged in user. So, my view is this:
def new_task(request, task_id=None):
message = None
if task_id is not None:
task = Task.objects.get(pk=task_id)
message = 'TaskOK'
submit = 'Update'
else:
task = Task(created_by = GPUser(user=request.user))
submit = 'Create'
if request.method == 'POST': # If the form has been submitted...
form = TaskForm(request.POST, instance=task)
if form.is_valid():
task = form.save(commit=False);
task.created_by = GPUser(user=request.user)
task.save()
if message == None:
message = 'taskOK'
return tasks(request, message)
else:
form = TaskForm(instance=task)
return custom_render('user/new_task.html',
{'form': form, 'submit': submit, 'task_id':task.id},
request)
The problem is, you guessed, the created_by field doesn't get saved. Any ideas? Thanks
You are creating GPUser, but you don't save it. You must save it first, so it gets pk and only after that it can be assigned to a ForeignKey. Try this:
task.created_by = GPUser.object.create(user=request.user)
or
gpuser = GPUser(user=request.user)
gpuser.save()
task.created_by = gpuser