10👍
✅
I found the solution. Rewrote view.py
as follows:
def cost(request, offset):
if request.method == 'POST':
project = Project.objects.get(title=offset)
date = request.POST.get('date', '')
cost = request.POST.get('cost', '')
cost_obj = Cost(project=project, date=date, cost=cost)
cost_obj.save()
return HttpResponseRedirect('/')
The rest of the code has not changed.
14👍
A couple things don’t look right:
-
Project.objects.filter()
will return a queryset. UseProject.objects.get()
instead… it will return just a singleProject
object -
You wont need to explicitly set the cost and date, that will be handled by your
instance=form.save(commit=False)
-
You aren’t using the form in your template…
Try this:
Template:
<form action="/cost/{{ project }}/" method="post" accept-charset="utf-8">
{{form.as_p}}
<p><input type="submit" value="Add"></p>
</form>
View:
def cost(request, offset):
if request.method == 'POST':
form = CostForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.project = Project.objects.get(title=offset)
instance.save()
return HttpResponseRedirect('/')
else:
form = CostForm()
render_to_response('path/to/template.html',{'form':form},context_instance=RequestContext(request))
Also, I think you will need to add blank=True
to your models.ForeignKey(Project)
in the Cost
model. That will allow your ModelForm to validate.
- Django Check and set permissions for a user group
- Create DB Constraint via Django
- Custom authentication backend. Django
- Validating a Django model field based on another field's value?
1👍
I did it this way:
def save_model(self, request, obj, form, change):
obj.save()
To modify something, do it through:
obj.xyz = 'something'
obj.save()
Source:stackexchange.com