Home > Net >  ValueError at /freshleadaction for uploading .csv file in Django
ValueError at /freshleadaction for uploading .csv file in Django

Time:11-07

I am stuck on an error in django while uploading a .csv file for fresh leads and I have searched a lot on google for the solution but couldn't find the solution so now decided to upload it so that community can help me. I am displaying the code that I have done so. the error that I am facing:

**ValueError at /freshleadaction
Usecols do not match columns, columns expected but not found: ['StreetNumber', 'Address', 'Owner First Name', 'Cell', 'Legal Description', 'Zip Code', 'Equity', 'Sq Ftg', 'Owner Last Name', 'StreetName', 'Bdrms', 'Email', 'State', 'Orig Ln Amt', 'Prop Value']**
Request Method: POST
Request URL:    http://127.0.0.1:8000/freshleadaction?type=1
Django Version: 3.1.1
Exception Type: ValueError
Exception Value:    
Usecols do not match columns, columns expected but not found: ['StreetNumber', 'Address', 'Owner First Name', 'Cell', 'Legal Description', 'Zip Code', 'Equity', 'Sq Ftg', 'Owner Last Name', 'StreetName', 'Bdrms', 'Email', 'State', 'Orig Ln Amt', 'Prop Value']
Exception Location: C:\Users\Dell\Documents\REaltorBIT\bit-realtorbit\venv\lib\site-packages\pandas\io\parsers\base_parser.py, line 866, in _validate_usecols_names
Python Executable:  C:\Users\Dell\Documents\REaltorBIT\bit-realtorbit\venv\Scripts\python.exe
Python Version: 3.9.4
Python Path:    
['C:\\Users\\Dell\\Documents\\REaltorBIT\\bit-realtorbit',
 'C:\\Users\\Dell\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
 'C:\\Users\\Dell\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
 'C:\\Users\\Dell\\AppData\\Local\\Programs\\Python\\Python39\\lib',
 'C:\\Users\\Dell\\AppData\\Local\\Programs\\Python\\Python39',
 'C:\\Users\\Dell\\Documents\\REaltorBIT\\bit-realtorbit\\venv',
 'C:\\Users\\Dell\\Documents\\REaltorBIT\\bit-realtorbit\\venv\\lib\\site-packages']

Models.py:

class fresh_leads_model(models.Model):
    fname = models.CharField(max_length=20)
    lname = models.CharField(max_length=20)
    street_number = models.CharField(max_length=20)
    street_name = models.CharField(max_length=50)
    state = models.CharField(max_length=50)
    zip_code = models.CharField(max_length=50)
    bedrooms = models.CharField(max_length=20)
    legal_description = models.CharField(max_length=100)
    sq_ft = models.CharField(max_length=50)
    address = models.CharField(max_length=50)
    orign_ln_amt = models.CharField(max_length=50)
    prop_value = models.CharField(max_length=50)
    equity = models.CharField(max_length=255)
    email = models.CharField(max_length=50)
    cell = models.CharField(max_length=50)
    submitted_date = models.DateField(auto_now_add=True)
    updated_date = models.DateField(auto_now_add=True)
    deleted_date = models.DateField(auto_now_add=True)

my views.py file for fresh leads upload:

@login_required
@allowed_users(allowed_roles=['admin'])
def upload_fresh_leads(request):
    get_type = request.GET['type']
    lst = []
    if request.method == 'POST':
        leads = Fresh_leads_Form(request.POST, request.FILES)

        data = request.FILES.getlist('csv')
        # data = Fresh_leads_Form(request.FILES)
        # csv_file = request.GET['csv']
        # df = pd.read_csv(csv_file)
        # return HttpResponse(print(df)))

        # data = []

        # message = 2
        # return render(request, 'admin/src/tabs/fresh_leads.html', {'message': message})
        if get_type == '1':
            if leads.is_valid():
                # csv = data['csv']
                for d in data:
                    # df = pd.read_csv(d, usecols=['Owner First Name'])
                    # return HttpResponse(df.to_string())

                    df = pd.read_csv(
                        d,
                        dtype='str',
                        usecols=[
                            'Owner First Name',
                            'Owner Last Name',
                            'StreetNumber',
                            'StreetName',
                            'State',
                            'Zip Code',
                            'Bdrms',
                            'Legal Description',
                            'Sq Ftg',
                            'Address',
                            'Orig Ln Amt',
                            'Prop Value',
                            'Equity',
                            'Email',
                            'Cell'
                        ])
                    df = df.fillna(0)
                    df.columns = [
                        'Owner_FirstName',
                        'Owner_LastName',
                        'StreetNumber',
                        'StreetName',
                        'State',
                        'ZipCode',
                        'Bdrms',
                        'Legal_Description',
                        'Sq_Ftg',
                        'Address',
                        'Orig_Ln_Amt',
                        'Prop_Value',
                        'Equity',
                        'Email',
                        'Cell']

                    json_record = df.reset_index().to_json(orient='records')

                    lst = json.loads(json_record)

                    bulk_data = df.to_dict('records')

                    model_instances = [fresh_leads_model(
                        fname=i['Owner_FirstName'],
                        lname=i['Owner_LastName'],
                        street_number=i['StreetNumber'],
                        street_name=i['StreetName'],
                        state=i['State'],
                        zip_code=i['ZipCode'],
                        bedrooms=i['Bdrms'],
                        legal_description=i['Legal_Description'],
                        sq_ft=i['Sq_Ftg'],
                        address=i['Address'],
                        orign_ln_amt=i['Orig_Ln_Amt'],
                        prop_value=i['Prop_Value'],
                        equity=i['Equity'],
                        email=i['Email'],
                        cell=i['Cell']
                    )for i in bulk_data]
                    fresh_leads_model.objects.bulk_create(model_instances)

                # message = 2
                # return render(request, 'admin/src/tabs/fresh_leads.html', {'data': lst, 'message': message})
                return redirect('main:FreshLeadView')
        # message = 1
        # return render(request, 'admin/src/tabs/fresh_leads.html', {'message': message})

        # message = 3
        # return render(request, 'admin/src/tabs/fresh_leads.html', {'message': message})

    return render(request, 'frontend-layout/500.html')

fresh_leads.html:

{% extends 'admin/admin_dashboard/dashboard_theme.html' %}

{% block tabs %}
{% load static %}


<div class="row">
    <div class="col-lg-12 col-md-12 col-sm-12">
        <div class="card text-center">
            <div class="card-header">
                <h4>Upload Fresh Leads</h4>
            </div>
            <div class="card-body">
                {% if message == 1 %}
                    <div class="alert alert-danger alert-dismissible">
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                        <strong>Warning!</strong> Wrong file type only CSV & XLS is uploaded
                    </div>
                {% endif %}
                {% if message == 2 %}
                    <div class="alert alert-success alert-dismissible">
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                        <strong>Successfully!</strong> Leads are uploaded in Database
                    </div>
                {% endif %}
                {% if message == 3 %}
                    <div class="alert alert-warning alert-dismissible">
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                        <strong>Successfully!</strong> Leads are uploaded in Database
                    </div>
                {% endif %}
                <form action="{% url 'main:FreshLeadAction' %}?type=1" method="POST" enctype="multipart/form-data">
                    {% csrf_token %}
                    <div class="alert alert-Warning">
                        <strong>Notice:</strong> Only CSV file is accepted!<br>
                    </div>
                    <input class="form-control" type="file" name="csv" accept=".csv">

                    <br>

                    <input type="submit" value="Upload CSV File" class="btn btn-primary">
                </form>
                
            </div>
        </div>
    </div>
</div>

{% if data is not None %}
    <div class="row">
       <div class="col-lg-12 col-md-12 col-sm-12">
            <div class="card">
                <div class="card-header">
                    <h5>Data inside your file</h5>
                    <div class="row">
                        <div class="col-lg-12 col-md-12 col-sm-12">
                            <a href="{% url 'main:FreshLeadAction' %}?type=2" class="btn btn-success">UPLOAD IN DATABASE</a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                   
                    <div class="row">
                        <div class="col-lg-12 col-md-12 col-sm-12">
                            <table class="table table-dark table-striped">
                                <thead>
                                  <tr>
                                    <th>Owner First Name</th>
                                    <th>Owner Last Name</th>
                                    <th>Street#</th>
                                    <th>Street Name</th>
                                    <th>State</th>
                                    <th>Zip Code</th>
                                    <th>Bedrooms</th>
                                    <th>Legal Description</th>
                                    <th>Square foots</th>
                                    <th>Address</th>
                                    <th>Orig Ln Amt</th>
                                    <th>Property Value</th>
                                    <th>Equity</th>
                                    <th>Email</th>
                                    <th>Cell</th>
                                  </tr>
                                </thead>
                                <tbody>
                                <!-- jinja2 Technique -->
                                    {% if data %}  
                                        {% for i in data %}
                                        <tr>
                                            <td>{{ i.Owner_FirstName }}</td>
                                            <td>{{ i.Owner_LastName }}</td>
                                            <td>{{ i.StreetNumber }}</td>
                                            <td>{{ i.StreetName }}</td>
                                            <td>{{ i.State }}</td>
                                            <td>{{ i.ZipCode }}</td>
                                            <td>{{ i.Bdrms }}</td>
                                            <td>{{ i.Legal_Description }}</td>
                                            <td>{{ i.Sq_Ftg }}</td>
                                            <td>{{ i.Address }}</td>
                                            <td>{{ i.Orig_Ln_Amt }}</td>
                                            <td>{{ i.Prop_Value }}</td>
                                            <td>{{ i.Equity }}</td>
                                            <td>{{ i.Email }}</td>
                                            <td>{{ i.Cell }}</td>
                                        </tr>
                                        {% endfor %}
                                    {% endif %}
                                </tbody>
                            </table>
                        </div>
                    </div>
                   
                </div>
            </div>
       </div>
    </div>
{% endif %}

{% endblock %}

CodePudding user response:

I got the issue resolved just by replacing usecols by names in my views.py and my issue got resolved.

  • Related