Issue
I have this model to store information about computers. I am trying to add a feature to import Excel file containing data directly instead of typing data into the table in case there is a lot of data to input.
models.py
class Product(models.Model):
model=models.CharField(max_length=50, null=True)
serial=models.CharField(max_length=50, null=True)
hd_size=models.CharField(max_length=50,null=True)
ram=models.CharField(max_length=50, null=True)
processor=models.CharField(max_length=50, null=True)
date_created = models.DateTimeField(default=timezone.now)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.serial + ' - ' + self.model
Views.py
@login_required
def product_mgt(request):
context['page_title'] = "Computer List"
products = Product.objects.all()
context['products'] = products
return render(request, 'product_mgt.html', context)
Forms.py
class SaveProduct(forms.ModelForm):
model= forms.CharField(max_length=50,)
serial= forms.CharField(max_length=50, )
hd_size= forms.CharField(max_length=50, )
ram= forms.CharField(max_length=50, )
processor= forms.CharField(max_length=50, )
class Meta:
model = Product
fields = ('model','serial','hd_size','ram', 'processor')
def clean_serial(self):
id = self.instance.id if self.instance.id else 0
serial = self.cleaned_data['serial']
try:
if int(id) > 0:
product = Product.objects.exclude(id=id).get(serial = serial)
else:
product = Product.objects.get(serial = serial)
except:
return serial
raise forms.ValidationError(f"{serial} Computer Already Exists.")
Solution
Yoooh. I actually solved this issue some weeks ago using this code
def import_product(request):
if request.method == 'POST':
excel_file = request.FILES['excel_file']
wb = openpyxl.load_workbook(excel_file)
ws = wb.active
for row in ws.iter_rows(min_row=2, values_only=True):
model, serial, hd_size, ram, processor = row
Product.objects.create(model= model, serial= serial, hd_size= hd_size, ram= ram, processor= processor)
return render(request, 'import_success_2.html')
return render(request, 'import_product.html')
def import_success_2(request):
return render(request, 'computers/import_success_2.html')
I also did: pip install openpyxl
Then i created two templates: import_product and success
import_product.html
<p style="color:whitesmoke;font-size:20px;">
Select a file containing the Computers you want to Import
</p>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="excel_file">
<button type="submit">Import</button>
</form>
<div class="container-fluid">
<button onclick="goBack()">Go Back</button>
</div>
Answered By - David Mutuku
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.