Talha Anwar
Talha Anwar

Reputation: 2949

How to add an item to database directly in django without forms

I know, this question has already been discussed, but I am unable to grab that.

Here are two models I have

# Create your models here.
GENDER_CHOICES = [
    ('Male', 'M'),
    ('Female', 'F')]
class upload(models.Model):
    name = models.CharField(max_length=100,null=True)
    gender = models.CharField(max_length=10,null=True, choices=GENDER_CHOICES)
    phone = models.CharField(max_length=50,null=True)
    email=  models.EmailField(max_length=50,null=True)
    file=models.FileField(upload_to='uploads/',null=True)

    def __str__(self):
        return self.name

class text(models.Model):
    texts=models.CharField(max_length=200,null=True,blank=True)
    upload_text=models.ForeignKey(upload, blank=True, null=True, on_delete = models.CASCADE) 

I have a form for model upload. I inserted the data, and an audio file. Then I want this audio file to convert to text and save the text in the database. For that purpose, I created another model text.

But I don't know how to insert the text to this model in relation to the information entered in model upload

Here is my views.py file function

def display(request):
    print('display functio')
    d=upload.objects.last()
    test=sr.takeCommand(d.file.path)
    print(test) **# I can see text here**
    p = text.objects.create(texts=test)
    p.save(force_insert=True)
    print(test)
    return render(request,'thanks.html',{'print':test})

But I am unable to enter it. It throws an error UNIQUE constraint failed: sub_app_text.id

Upvotes: 3

Views: 1730

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

This is because you insert it twice. The .create(…) method [Django-doc] already inserts in in the database. So you can implement this as:

def display(request):
    print('display functio')
    d=upload.objects.last()
    test=sr.takeCommand(d.file.path)
    # will store the record in the database
    p = text.objects.create(texts=test)
    print(test)
    return render(request,'thanks.html',{'print':test})

you can link it to d with:

def display(request):
    print('display functio')
    d=upload.objects.last()
    test=sr.takeCommand(d.file.path)
    # will store the record in the database
    p = text.objects.create(texts=test, upload_text=d)
    print(test)
    return render(request,'thanks.html',{'print':test})

Note: Models in Django are written in PerlCase, not snake_case, so you might want to rename the model from text to Text.

Upvotes: 3

Related Questions