0

After I click submit nothing happens, I think because it can't import Mobile from .models so that the from .models import Mobile from forms.py is unused. How to import it so that I can upload a CSV file successfully and insert the data to Mobile model.

forms.py looks like this

import io
import csv
from django import forms
from .models import Mobile



class DataForm(forms.Form):
    data_file = forms.FileField()

    def clean_data_file(self):
        f = self.cleaned_data['data_file']

        if f:
            ext = f.name.split('.')[-1]
            if ext != 'csv':
                raise forms.ValidationError('File Type not supported')
            return f

    def process_data(self):
        f = io.TextIOWrapper(self.cleaned_data['data_file'].file)
        Mobile = csv.DictReader(f)

        for i in Mobile:
            Mobile.objects.create_data(i['mobile_owner'], i['mobile_number'])

views.py looks like this:

from .models import Mobile
from django.views.generic import TemplateView

from .forms import DataForm
from django.views.generic import FormView


class DataView(FormView):
    template_name = 'sms/mobile.html'
    form_class = DataForm
    success_url = '/upload/'

    def form_valid(self, form):
        form.process.data()
        return super().form_valid(form)

mobile.html looks like this

{% extends 'base/base.html' %}

{% block title %}Add SMS Data{% endblock title %}


{% block scripts %}

{% endblock scripts %}


{% block content %}

<form action="{% url 'mobile' %}" method="POST" enctype="multipart/form-data">
  {% csrf_token %}
  <label>Upload mobile numbers</label>
  <input type="file" name="data_file">
  <input type="submit" value="submit">
</form>


{% endblock content %}

urls.py looks like this:

from django.urls import path, include
from . import views

urlpatterns = [
    path('mobile', views.index, name='mobile'),
    ]

1 Answer 1

2

Hi it looks like you have typo in your form_valid method.

from .models import Mobile
from django.views.generic import TemplateView

from .forms import DataForm
from django.views.generic import FormView


class DataView(FormView):
    template_name = 'sms/mobile.html'
    form_class = DataForm
    success_url = '/upload/'

    def form_valid(self, form):
        form.process_data()
        return super().form_valid(form)

Change form.process.data() to form.process_data() and you should be good to go.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.