Reputation: 21
I am new to Django...I have a model FileField to upload document, and I want the file path is according to the client ID.
Like this: enter image description here
I have a Customer model and I have a upload model, linked to Customer:
model.py
class BasicUploadTo():
prefix = ''
suffix = dt.now().strftime("%Y%m%d%H%M%S")
def upload_rules(self, instance, filename):
(filename, extension) = os.path.splitext(filename)
id = instance.customer_id.customer_id.user_id
return os.path.join(str(id), "Docs", f"{self.prefix}_{self.suffix}{extension}")
def upload_br(self, instance, filename):
instance1 = Customer.customer_id
self.prefix = "BR"
dir = self.upload_rules(instance, filename)
return dir
class AttachmentsBasic(models.Model):
customer_id = models.OneToOneField("Customer", verbose_name="client ID", on_delete=models.DO_NOTHING, blank=False, null=True)
br = models.FileField(upload_to=BasicUploadTo().upload_br, verbose_name="BR", null=True, blank=True)
class Customer(models.Model):
customer_id = models.OneToOneField("UserID", blank=False, null=True, verbose_name="Client ID", on_delete=DO_NOTHING)
...
class UserID(models.Model):
user_id = models.CharField(max_length=5, blank=False, verbose_name="Client ID")
class Meta():
verbose_name = "Client"
verbose_name_plural = "Client"
def __str__(self):
return f"{self.user_id}"
form.py:
class ClientUploadForm(ModelForm):
class Meta:
model = AttachmentsBasic
fields = ( "br",)
def __init__(self, path, *args, **kwargs):
super(ClientUploadForm, self).__init__(*args, **kwargs)
print(path)
for x in self.fields:
self.fields[x].required = False
def save(self, client_id, commit=True):
clientDoc = super(ClientUploadForm, self).save(commit=True)
print(self)
instance = Customer.objects.get(customer_id__user_id=client_id)
clientDoc.customer_id = instance
if commit:
clientDoc.save()
return clientDoc
views.py
def clienInfo(request, client):
clientsIDs = [c.customer_id.user_id for c in Customer.objects.all()]
if client in clientsIDs:
matching_client = Customer.objects.filter(customer_id__user_id=client)
if request.method == "POST":
instance = Customer.objects.get(customer_id__user_id=client)
uploadForm = ClientUploadForm(request.POST, request.FILES, instance.customer_id.user_id)
if uploadForm.is_valid():
uploadForm.save(request.POST["customer_id"])
else:
print("Client's document form got error.")
else:
print("Client form got error.")
uploadForm = ClientUploadForm
sale = sales.objects.all()
return render(request=request,
template_name="home/client-info-test.html",
context={"clientInfo": matching_client,
"uploadForm": uploadForm,
"sales": sale})
But I got none when I upload file though my site, but I can upload the file though Django admin page
<input type="file" class="" name="br">
Error: enter image description here
Could someone help me...many thanks!!!!!
Upvotes: 1
Views: 357
Reputation: 21
I have solved the problem, just use the {{form.br}} in the frontend site, use the original form from the view. view.py
def updateClienInfo(request, client_id):
clientDoc = AttachmentsBasic.objects.get(customer_id__customer_id__user_id=client_id)
docForm = ClientUploadForm(instance=clientDoc)
if request.method == "POST":
docForm = ClientUploadForm(request.POST or None,
request.FILES or None,
instance=clientDoc)
if docForm.is_valid():
docForm.save()
return HttpResponseRedirect('/')
else:
print(docForm.errors)
print("Upload document form got errors.")
else:
print("Client's saving form got error.")
return render(request=request,
template_name="home/client-info-test1.html",
context={"docForm" : docForm,
})
home/client-info-test1.html
<div class="card-body">
<label class="card-text">BR</label>
{{docForm.br}}
</div>
forms.py
class ClientUpdateForm(ModelForm):
class Meta:
model = Customer
fields = ("company_name", ...) #your model field name
def __init__(self, *args, **kwargs):
super(ClientUpdateForm, self).__init__(*args, **kwargs)
for visible in self.visible_fields():
visible.field.widget.attrs['class'] = 'form-control'
for x in self.fields:
self.fields[x].required = False
Upvotes: 1