Django: Save data from form in DB
- by Anry
I have a model:
class Cost(models.Model):
project = models.ForeignKey(Project)
cost = models.FloatField()
date = models.DateField()
For the model I created a class form:
class CostForm(ModelForm):
class Meta:
model = Cost
fields = ['date', 'cost']
view.py:
def cost(request, offset):
if request.method == 'POST':
#HOW save data in DB?
return HttpResponseRedirect('/')
else:
form = CostForm()
In the template file determined:
<form action="/cost/{{ project }}/" method="post" accept-charset="utf-8">
<label for="date">Date:</label><input type="text" name="date" value={{ current_date }} id="date" />
<label for="cost">Cost:</label><input type="text" name="cost" value="0" id="cost" />
<p><input type="submit" value="Add"></p>
</form>
How save data from form in DB?
P.S. offset = project name
Model:
class Project(models.Model):
title = models.CharField(max_length=150)
url = models.URLField()
manager = models.ForeignKey(User)
timestamp = models.DateTimeField()
I tried to write:
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.filter(title=offset)
instance.date = request.date
instance.cost = request.cost
instance.save()
return HttpResponseRedirect('/')
else:
form = CostForm()
But it does not work :(