PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 31, 2022

[FIXED] How to add the name of an uploaded file to a model in django

 July 31, 2022     django, django-forms, file-upload, model, python     No comments   

Issue

I am learning django. I am stuck with this problem.

I have created a form in which a user uploads a text file and selects a gender. The user is also supposed to write the name of the text file in the text box.

sample output

In the backend I want to save the name of the text file along with the gender in a model. The purpose of doing this is because when multiple users will use the application, I should know which user selected what gender so that I can produce the desired output.

As I have already mentioned the user needs to type the name of the file, I was thinking is it possible to get the name of the file from the uploaded file and then save it to the model so the user need not type the name of the file and hence no text box.

Here is the link to my git repository - https://github.com/AnshulGupta22/auto_generation.git

Can someone please tell me how to do it? As I already said I am new to django and some help will be appreciated.


Solution

You can get the name of file from request.POST and you can create an object for file_name

##in views.py  
def get_gender(request):
    if request.method == 'POST':
        form = GenderForm(request.POST)
        uploaded_file = request.FILES['document']
        file_name = request.FILES["name"] #NEW
        Gender.objects.create(file_name=file_name) #NEW
        fs = FileSystemStorage()
        name = fs.save(uploaded_file.name, uploaded_file)
        fbh = name[:-4]
        if form.is_valid():
            form.save()
            run(["gnome-terminal", "--", "sh", "-c", f"espeak -ven+m1 -f {uploaded_file.name} -w {fbh}.wav "])
            return  HttpResponse("Blog created")


##in models.py
class Gender(models.Model):
    file_name = models.CharField(max_length=120) #NEW


Answered By - enes islam
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing