hi im currently try to import a csv file into a django project with out using the django admin. the code ive written seems to work when in python run but im unsure about how to build the html template as i cant seem to find any examples. Is anyone able to either post an example or point me in the right direction
my code is
Forms
class DataInput(forms.Form):
file = forms.FileField()
def save(self):
records = csv.reader(self.cleaned_data["file"])
for line in records:
parts = Part()
parts.supplier_id = line[0]
parts.name = line[1]
parts.description = line[2]
parts.save()
view
def csv_import(request):
if request.method == "POST":
form = DataInput(request.POST, request.FILES)
if form.is_valid():
form.save()
success = True
context = {"form": form, "success": success}
return render_to_response("imported.html", context,
context_instance=RequestContext(request))
else:
form = DataInput()
context = {"form": form}
return render_to_response("imported.html", context,
context_instance=RequestContext(request))
thanks in advance
Your upload template will look something like this if you just want to use the default form rendering:
<!DOCTYPE html>
<html>
...
<form enctype="multipart/form-data" method="post" action=".">
{{ form }}
</form>
...
</html>
The distinguishing part is the enctype="multipart/form-data" that lets it handle the file upload field.
Related
I have a big command-line script for parsing data in Excel (with pandas) and I want to wrap it with Django. I've tried both uploading files thru request.FILES and pandas, but get stuck on uploading file and, for example, saving it (not necessarily but just to check the upload for now).
Haven't had any problems with other apps on Django which didn't require uploading and parsing anything external and thought that would be much easier..:)
I've also tried Redirecting, doesn't really work, the only redirect which is actually happening is action in the form tag..
Here are the code snippets:
views.py:
def uploads(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
excel_file = request.FILES['document']
excel_file.save()
return render(request, 'index.html')
else:
form = DocumentForm()
return render(request, 'index.html', {'form': form})
models.py
class Document(models.Model):
document = models.FileField(upload_to="files/")
forms.py:
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('document', )
index.html:
<form
action="{% url 'reports'%}"
method="post"
enctype="multipart/form-data"
>
{% csrf_token %}
<span>
Upload .xlsx file <input type="file" name="document" />
</span>
<button type="submit">
SUBMIT
</button>
</form>
I think you must save the form's content actually:
form.save()
The reason was that I had another function in views.py leading to the same url route.
I have a form.py including Floatfield and Charfield. Now I want to add a new Filefield to upload a text file. But I fail.
The float var is submitted successfully and I could see they are changed with the change of the input, but I cannot find the file in located folders.
And also, how could I check whether file extensions are correct? Should I achieve it in view or model?
Could someone help me? I truly struggled with it.
model.py
file = models.FileField(upload_to='/Folder', null = True)
form.py
file = forms.FileField(label='data', required=False)
view.py is followed the structure in Django official document.
def handle_uploaded_file(f):
with open('./test_temp_file.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
def file_upload(request):
if request.method=='POST':
form = input_form(request.POST,request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
name = request.FILES['filename'].name
time = cleaned_data(timezone.now())
form = {
'name' : name,
'time' : time
}
return render(request, 'home/results.html',{'form':form})
else:
form = input_form()
return render(request, 'home/input.html', {'form': form})
------Uploaded:
HTML page is like this:
<form method = "POST" enctype="multipart/form-data" name="temp_data_upload">
{% csrf_token %}
{{ form_upload.temp_data.errors }}
{{ form_upload.temp_data }}
{% endif%}
</form>
You should save your form and refactor the code.
def file_upload(request):
if request.method=='POST':
form = input_form(request.POST,request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
name = request.FILES['filename'].name
time = cleaned_data(timezone.now())
form = {
'name' : name,
'time' : time
}
form.save() # <-- save your form
return render(request, 'home/results.html',{'form':form})
else:
form = input_form()
return render(request, 'home/input.html', {'form': form})
EDIT
Make sure your forms contain the correct values.
<form method="POST" enctype="multipart/form-data">
My question about implementing a script into a view in a django web app.
I have a .py script that I want to run inside this django web app using the user-supplied data, the configfile, the modelfile and the choice as command line arguments. The output is then a list with different scores which will then be displayed inside the html (not the part I need help with yet).
So I have 2 forms, one that uploads a ML model and another one (the one I need help with) that uses user-supplied data to run a uploaded model:
class Meta:
model = MlModel
fields = [
'modelname',
'configfile',
'modelfile',
'choice',
]
class TestForm(forms.Form):
testdata = forms.FileField()
model = forms.ModelChoiceField(queryset=MlModel.objects.all())
My views are as follow, where the test view is where the testing happens:
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/mltesting/')
else:
form = UploadForm()
context = {'form':form}
return render(request,'mltesting/upload.html', context=context)
def test_model(request):
submitbutton = request.POST.get("submit")
testdata = ''
modfile = ''
confile = ''
choice = ''
form = TestForm(request.POST, request.FILES)
if form.is_valid():
testdata = request.FILES['testdata']
model = form.cleaned_data.get('model')
model = MlModel.objects.get(modelname=model)
modfile = model.modelfile.path
confile = model.configfile.path
choice = model.choice
else:
form = TestForm()
context = {'form': form, 'testdata': testdata, 'submitbutton': submitbutton, 'modelfile':modfile, 'configfile': confile,'choice': choice}
return render(request,'mltesting/test.html', context=context)
And this is the HTML template where the output of the testing is supposed to be:
{% block content %}
<p>Compound Protein Interaction Tool</p>
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_table }}
<input type="Submit" name="submit" value="Submit"/>
</form>
{% if submitbutton == "Submit" %}
{% endif %}
{% endblock %}
I am fairly new to Django in general so I apologise for the (probable) bad formulation of my question, but all help is greatly appreciated.
You can follow the answer from this solution
Make a folder in the same directory, add the py file there and then import the module you want in the view.py.
call the function as you would call any custom module.
** EDIT **
Call the script as stated in this answer
def test_model(request):
if form.is_valid():
testdata = request.FILES['testdata']
model = form.cleaned_data.get('model')
model = MlModel.objects.get(modelname=model)
modfile = model.modelfile.path
confile = model.configfile.path
choice = model.choice
else:
form = TestForm()
#########################################
###########Here you run your script
###########Any variable from the script will be loaded here
exec(open("./path/toYour/script.py").read(), globals())
#Add the information you want from the script to the context
context = {'someVariableFromTheScript':someVariableFromTheScript, 'form': form, 'testdata': testdata, 'submitbutton': submitbutton, 'modelfile':modfile, 'configfile': confile,'choice': choice}
return render(request,'mltesting/test.html', context=context)
I have model whiuch has photo attachment.
class Forum_message(models.Model):
text = models.TextField()
photo = models.ImageField(upload_to= 'forum_attachments')
I have my form(I prefer writing forms in pure html so I can have full access to modifying them)
<form action="/forum_new" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="img_msg" type="file">
<textarea name="new_msg"></textarea>
<input type="submit" value="Submit"/>
</form>
What do I write in my function
def forum_new(request): in views.py to handle file upload and save new forum message to database?
I needed something like this:
def forum_new(request):
msg = Forum_message()
msg.user = request.user
if 'image' in request.FILES:
msg.photo = request.FILES['image']
msg.text = request.GET.get('text')
msg.save()
In views.py, you can use what is propose on the django website (https://docs.djangoproject.com/en/1.11/topics/http/file-uploads/)
If the picture is not so large, you can directly handle it as follow :
def forum_new(request):
if request.method == 'POST':
form = your_form_here(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('/bar.html/')
else:
form = your_form_here()
return render(request, 'url.html', {'form': form})
The file should be saved in your media files in the folder forum_attachments
I must just be overlooking something here, but after stripping everything back - I can't seem to get Django to render either a Form or ModelForm to my template. Code below:
#forms.py
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
#views.py
def index(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid(): # All validation rules pass
return HttpResponseRedirect('/thanks/')
else:
form = ContactForm() # An unbound form
return render_to_response('home/new_website.html',{
'form': form,
})
#new_website_html
<html>
<body>
<form method = "post" action = "">
{{ form.as_p }}
</form>
</body>
</html>
I had the same issue and after many tries this is my solution:
Change the view from this
#views.py
else:
form = ContactForm() # An unbound form
return render_to_response('home/new_website.html',{
'form': form,
})
To that:
#views.py
else:
form = ContactForm() # An unbound form
return render_to_response('home/new_website.html',{
'form': form,
})
Or a simple newline is enough:
#views.py
else:
form = ContactForm() # An unbound form
return render_to_response('home/new_website.html',{
'form': form,
})
Strange thing is, after these changes the original code worked.
Any error page or just blank page? Actually I just try your code and get form rendering correct(I don't know how to insert local result image here)
Please make sure DEBUG=TRUE in settings.py while it's not the problem.
#Burhan I think indent problem only happens because he edits it in stackoverflow.
Btw, your form doesn't have a submit button, maybe add it in html like