Currently I am starting to develop a django project which need to provide a HTML page for other students to upload their experiment results which are excel files (maybe CSV), and save them to databases. But I don't know what should I do with the model.py file for each student have diffenent assignments which means the first row of different experiments are not the same. Can anyone help me?
Django 2.1.7
try this
in template
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
in forms.py
from django import forms
from .models import YourModel
class YourModelForm(forms.ModelForm):
class Meta:
model = YourModel
fields = ('myfile', )
in views.py
def file_upload(request):
if request.method == 'POST':
form = YourModelForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
form = DocumentForm()
return render(request, 'template', {
'form': form
})
for more details refer this
hope it helps
Related
I have an update form to update information. Here problem is, product_title is updating but product_image is not working. Where is the problem that's for why the photo is not updating?
views.py:
def update_product(request,id):
product = Products.objects.get(pk=id)
form = update_product_info(request.POST or None, instance=product)
if request.method == 'POST' and form.is_valid():
form.save()
print(form.errors)
messages.success(request,"Successfully product information updated.")
return redirect("my_products")
context = {
'product':product,
"form":form
}
return render(request, "update_product.html", context)
update form:
class update_product_info(forms.ModelForm):
class Meta:
model = Products
fields = ('product_title','product_image')
widgets = {
'product_title':forms.TextInput(attrs={'class':'form-control', 'style':'font-size:13px;'}),
'product_image':forms.FileInput(attrs={'class':'form-control', 'style':'font-size:13px;'})
}
template:
<form action="" method="POST" class="needs-validation" style="font-size: 13px;" novalidate="" autocomplete="off" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<div class="d-flex align-items-center">
<button type="submit" class="btn btn-outline-dark ms-auto" value="Update" style="font-size: 13px;">Add</button>
</div>
You should pass both request.POST and request.FILES to the form:
from django.shortcuts import get_object_or_404
def update_product(request, id):
product = get_object_or_404(Products, pk=id)
if request.method == 'POST':
form = update_product_info(request.POST, request.FILES, instance=product)
if form.is_valid():
form.save()
messages.success(request, 'Successfully product information updated.')
return redirect('my_products')
else:
form = update_product_info(instance=product)
context = {'product': product, 'form': form}
return render(request, 'update_product.html', context)
Note: It is often better to use get_object_or_404(…) [Django-doc],
then to use .get(…) [Django-doc] directly. In case the object does not exists,
for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using
.get(…) will result in a HTTP 500 Server Error.
Note: normally a Django model is given a singular name, so Product instead of Products.
Note: Usually a Form or a ModelForm ends with a …Form suffix,
to avoid collisions with the name of the model, and to make it clear that we are
working with a form. Therefore it might be better to use ProductInfoForm instead of
update_product_info.
views.py
def post(request):
if request.method == 'POST':
form = PostModelForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
# using the for loop i am able to save the tags data.
# for tag in form.cleaned_data['tags']:
# post.tags.add(tag)
images = request.FILES.getlist('images')
for image in images:
ImagesPostModel.objects.create(post=post, images=image)
return redirect('/Blog/home/')
else:
form = PostModelForm(request.POST)
return render(request, 'post.html', {'form': form})
models.py
class PostModel(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
date_time = models.DateTimeField(auto_now_add=True)
title = models.TextField(null=True)
body = models.TextField(null=True)
tags = TaggableManager()
def __str__(self):
return str(self.user)
post.html
{% extends 'base.html' %}
{% block content %}
<form action="{% url 'post' %}" enctype="multipart/form-data" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="file" multiple name="images">
<input type="submit">
</form>
{% endblock %}
After giving the input the data is stored in the tags field but, not saving in the database.
I can manually insert data through the admin panel successfully but not as a non-staff user.
I have installed taggit and placed it in the installed_apps in settings.py.
Tags are being saved using post.tags.add(tag) inside for loop. What is the issue with the code?
This is because you use commit=False for the form: then the form has no means to save the many-to-many fields. It is also not necessary to do that, you can work with:
def post(request):
if request.method == 'POST':
form = PostModelForm(request.POST)
if form.is_valid():
form.instance.user = request.user # set the user
post = form.save() # save the form
ImagesPostModel.objects.bulk_create([
ImagesPostModel(post=post, images=image)
for image in request.FILES.getlist('images')
])
return redirect('/Blog/home/')
else:
form = PostModelForm()
return render(request, 'post.html', {'form': form})
Note: Models normally have no Model suffix. Therefore it might be better to rename PostModel to Post.
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
I am using a dropdown on a template. I do want an alphabetical order in that dropdown and don't know how to get this.
template.html:
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset>
{{ form|crispy }}
</fieldset>
<div>
<button type="submit">OK</button>
</div>
</form>
The context comes from views.py:
def my_view(request):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
…
return render(request, 'xxx/template.html', {'form': form})
The form is defined in forms.py:
from django import forms
from .models import Project
class MyForm(forms.Form):
project = forms.ModelChoiceField(queryset=Project.objects)
field_order = ['name', ]
models.py:
class Project(models.Model):
name = models.CharField()
…
The documentation talks about field_order. The line field_order = ['name', ] in form.py has no effect.
What's wrong?
As documentation states this is ordering of form fields
for example of:
class MyForm(forms.Form):
project = forms.somefield
name = forms.somefield
field_order = ['name', ]
would show name prior to project in form
What you want is change sort order of ModelChoiceField that means you should change your queryset argument
forms.ModelChoiceField(Project.objects.order_by('name'))
You can order them by changing your query to
queryset=Project.objects.order_by("name")
or if you need reverse order ...order_by("-name").
I am trying to load a simple csv file into django model named as class Team
class Team(models.Model):
Team = models.CharField(max_length=255,primary_key=True)
Description = models.CharField(max_length=255)
def __str__(self):
return self.Team
Views.py
def model_form_upload(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
form = DocumentForm()
return render(request, 'core/model_form_upload.html', {
'form': form
})
HTML
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
<p>Return to home</p>
{% endblock %}
forms.py
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('description', 'document', )
I have create a simple html page to load the file into the following location MEDIA_ROOT=os.path.join(BASE_DIR,"media")
I am able to load my file into that location but I need some help with passing on the data to the actual database and load the values into the table "Team". Any suggestiond on this?
I have a template which displays a certain ModelForm at one of the URLs of my Django site. The ModelForm is based on a model with two fields,
class ActionCode(models.Model):
action_code = models.CharField(blank=False, max_length=10,
verbose_name="Action Code")
description = models.TextField(blank=True)
class Meta:
unique_together = ('action_code',)
I would like my ModelForm to give the user only the first field (Action Code), then when it is submitted, verify if the value entered already exists or not. If it doesn't already exist, I want to redirect the user to be able to enter a Description for that Action Code (the second field in my model). So I wrote a second ModelForm which uses the Description field of the model, and I would like my first form to redirect to the second form after validating that the data is new. Ideally then, the Description would be linked to this specific piece of data and both would go into the same Django database table (hence them coming from the same model). However, when I enter a new piece of data and hit Submit, the site simply stays at the /action_code/ URL and displays a Submit button, and nothing else. How do I get the first form to redirect to the second form, and what is the best way to make sure it only does so if the data is new?
Here are my urls.py:
url(r'^action_code/', action_code_form, name="actioncode"),
url(r'descr_form/', code_description_form, name='description'),
Here are my two forms in `forms.py':
class ActionCodeForm(ModelForm):
class Meta:
model = ActionCode
fields = ('action_code',)
class ActionCodeDescriptionForm(ModelForm):
class Meta:
model = ActionCode
fields = ('description',)
Here is my views.py:
def action_code_form(request):
form = ActionCodeForm()
description_form = ActionCodeDescriptionForm
if request.method == 'POST':
form = ActionCodeForm(request.POST)
if form.is_valid():
action_code = form.cleaned_data['action_code']
form.save()
return render(request, 'description_form.html',
{'form': description_form})
return render(request, 'action_code_form.html', {'form': form})
def code_description_form(request):
form = ActionCodeDescriptionForm()
if request.method == 'POST':
form = ActionCodeDescriptionForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'description_form.html', {'descr_form': form})
And my templates:
action_code_form.html:
<form method="post" action="">
{% csrf_token %}
<table>
{{ form }}
</table>
<input type="submit" value="Submit"/>
</form>
description_form.html:
<form method="post" action="">
{% csrf_token %}
<table>
{{ descr_form }}
</table>
<input type="submit" value="Submit"/>
</form>
Forms don't redirect to anything. It's the view's responsibility to do the redirect.
You need two views, with two URLs; when the first form submission is successful, the view should redirect to the second URL.