Hi there,
I have one model Detail
which has OneToOne
relation with default User
Model. I have a field FileField
in my Detail
model, where I want to upload the files using forms from frontend/templates.
I have been working around it a lot but I am not getting it done. I need help, please.
My models.py
is:
from django.db import models
from django.contrib.auth.models import User
class Detail(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
file = models.FileField(verbose_name="CSV File", upload_to='csv_files')
file_desc = models.TextField("CSV File Description")
def __str__(self):
return ("{} ({} {})".format(self.user.email, self.user.first_name, self.user.last_name))
My forms.py
is:
from django.forms import ModelForm
from .models import Detail
class DetailForm(ModelForm):
class Meta:
model = Detail
fields = ['file', 'file_desc']
My views.py
is:
from django.views import View
class UserAPI(View):
template_name = 'accounts/user.html'
def get(self, request):
form = DetailForm(instance=request.user)
context = {'form': form}
return render(request, self.template_name, context)
def post(self, request):
form = DetailForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('user')
context = {'form': form}
return render(request, self.template_name, context)
and my user.html (template)
is:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
Every time I go to localhost:8000/user
and fill the form and click on Submit Button, it gives me following error on frontend:
No File Chosen
and also the following statement appears above the File Selection Button:
This field is required
.
I shall appreciate for the help. Thanks