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.
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.
CodePudding user response:
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