Home > Net >  Django: change TextField before save
Django: change TextField before save

Time:12-23

This is my model :

class Card(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    imp_id = models.TextField(null = True)

And here is my view :

def Add(request):
if request.method == 'POST':
    form = Add_card(request.POST)

    if form.is_valid():
        save = form.save(commit = False)
        save.user = request.user
        save.imp_id = "asd" # I tried to change it here but I failed
        save.save()
else:
    form = Add_card()

cards = Card.objects.all()
return render(request, 'addcard.html', {'form': form, 'cards' : cards})

How can I change that textfield before save?

CodePudding user response:

you can do it like this

def Add(request):
    if request.method == 'POST':
        request.POST.imp_id="asd"
        form = Add_card(request.POST)

        if form.is_valid():
            save = form.save(commit = False)
            save.user = request.user
            save.save()
    else:
        form = Add_card()

    cards = Card.objects.all()
    return render(request, 'addcard.html', {'form': form, 'cards' : cards})

CodePudding user response:

The problem could be solved by using default='asd'.

  • Related