Home > Mobile >  How can i send data to two different column from the same form field?
How can i send data to two different column from the same form field?

Time:05-17

In my project i am using Django 1.11.10 and postgresql for database. When someone enters data to 'order_id' field i want to send it a item_barcode column whether its first 2 character is letters. How can I do that?

models.py

from django.db import models


class Customer(models.Model):


    item_barcode = models.TextField(max_length=50,unique=True,null=True)
    order_id = models.TextField(max_length=50,unique=True,null=True)
    full_name = models.TextField(max_length=50)
    company = models.TextField(max_length=60,blank=True)
    email = models.EmailField(max_length=40)
    phone_number = models.TextField(max_length=17)
    note = models.TextField(max_length=256,blank=True)


    def __str__(self):
        return self.order_id

forms.py

class CustomerForm(forms.ModelForm):

    class Meta:
        model = Customer
        fields = (
        'order_id','full_name','company','email',
        'phone_number','note')

views.py

def guaform(request):

    form = CustomerForm()

    if request.method == "POST":
        form = CustomerForm(request.POST)

        if form.is_valid():
            form.save(commit=True)
        
        else:

            HttpResponse("Error from invalid")

    return render(request,'customer_form.html',{'form':form})

*My database columns is same of the models.py

CodePudding user response:

You can do some work after validating the form.

if form.is_valid():
    #test to see if first two characters are letters
    first_two_characters = form.cleaned_data['order_id'][0:2]
    if first_two_characters.isAlpha():
        #get an instance of the object without saving to db
        form_uncommitted = form.save(commit=False)
        #set the item_barcode field and only then save to db
        form.uncommitted.item_barcode = form.cleaned_data['order_id'] #or what you want it to be
        form_uncommitted.order_id = None
        form_uncommitted.save
    else:
        #it's not a barcode so we can just save
        form.save()
    
  • Related