Django saving data from html field to database - django

I am new to Django, I am trying to take input from user using html generated text field and not use django forms.
<form action="" method="post">
{ % csrf_token % }
<label for="name">Enter name: </label>
<input id="namefield" type="text" name="name_field" value="Default name">
<input type="submit" value="OK">
</form>
I want to save the name to my database, without creating a django form and taking in data from the form and saving it in the database via views.py file.

In your view:
If request.method == 'POST' :
name = request.POST['field_name']
#now you can save them into related model
MyModel.objects.create(username=name,other fields goes here)

You must create in the views.py file a method in which the templates and the logic of it, an example can be the following
#csrf_exempt
def home(request):
if request.method == 'POST':
var1 = request.POST.get('var1')
var2 = request.POST.get('var2')
var3 = request.POST.get('var3')
#Save to the database here
return render_to_response(
'home.html',
{'message': 'Update Success', }
)
else:
return render_to_response(
'home.html',
{}
)

Related

tags will not store in database in django

Tags will not store in database in Django
def addque(request):
if request.method == "POST":
user = request.user
if user.is_anonymous:
return redirect('addquery')
if user.is_active:
question = request.POST['question']
body = request.POST['body']
tags = request.POST['tags']
aquuid = request.user.aquuid
addquery = Question(question=question, user_id=aquuid, que_body=body, tags=tags)
addquery.save()
return redirect('addquery')
else:
return render(request, 'question/ask.html')
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. What is the issue with the code?
Tags are Many-to-Many objects and you can't add those to an object until the object has been saved. The documentation shows that you need to use .add() to add tags to a model instance. Your code should be:
addquery = Question(question=question, user_id=aquuid, que_body=body)
addquery.save()
addquery.tags.add(tags)
As an aside, you might be better served by a ModelForm which can handle the tags and all of this stuff that you're doing:
question = request.POST['question']
body = request.POST['body']
tags = request.POST['tags']
https://django-taggit.readthedocs.io/en/latest/forms.html
Use model form
In html use id of forms like this
HTML
<form action="{% url 'addquery' %}" method="post">
{% csrf_token %}
<div class="psrelative">
<input id="id_question" name="question" type="text" maxlength="300" tabindex="100" placeholder="e.g. Is there an R function for finding the index of an element in a vector?" class="s-input js-post-title-field" value="" data-min-length="15" data-max-length="150" autocomplete="off" required>
</div>
<textarea name="que_body" id="id_que_body" class="textarea-body"></textarea required>
<div class="psrelative">
<input id="id_tags" name="tags" type="text" maxlength="300" tabindex="100"
placeholder="e.g. (ruby-on-rails vba spring)" class="s-input js-post-title-field" value="" data-min-length="15" data-max-length="150" autocomplete="off" required>
</div>
<button class="review-question-btn" type="submit" tabindex="120"> Submit your question
</button>
</form>
Forms.py
from django import forms
from .models import Question
class Addqueform(forms.ModelForm):
class Meta:
model = Question
fields = ['question','que_body','tags']
Views.py
from .forms import Addqueform
def addque(request):
queform = Addqueform(request.POST)
if request.method == "POST":
user = request.user
if user.is_anonymous:
return redirect('addquery')
if user.is_active:
if queform.is_valid():
aquuid = request.user.aquuid
question = queform.cleaned_data['question']
body = queform.cleaned_data['que_body']
tags = queform.cleaned_data['tags']
addquery = Question(question=question, user_id=aquuid, que_body=body)
for tag in tags:
addquery.tags.add(tag)
addquery.save()
return redirect('addquery')
else:
queform = Addqueform()
return render(request, 'question/ask.html', {'form': queform})
else:
return render(request, 'question/ask.html', {'form': queform})
I think It will Work

Update ImageField without forms in django

I am trying to update an image field in django model from an html form. Update goes fine except for the image field. Originally I successfully uploaded this image within a django form which means the settings are fine.
Please, tell me what's wrong in my code.
That's my views.py file:
'''
def update_product(request, product_id):
if request.method=="POST"
model_name=request.POST['model_name']
image = request.FILES ['image']
Product.objects.filter(id=product_id).update(model_name=model_name, image=image)
return redirect ('listing)
'''
That's my html file:
'''
<form action={% url update_product product.id %} method ="POST enctype='multipart/form-data'>
{% csrf_token %}
<input type='text' name='model_name'>
<input type='file' name='image'>
<button type='submit'> Update </button>
</form>
Update() method doesn’t run save().
Do something like this:
def update_product(request, product_id):
if request.method == "POST":
product = get_object_or_404(Product, id=product_id)
product.model_name = request.POST['model_name']
product.image = request.FILES['image']
product.save()
return redirect('listing')

Why values are not storing in the table when i have clicked Submit button?

I have created a form for getting the value and placing it in the table. But whenever I click on Submit button, it doesn't store or give any error.It is simply staying in that page itself.
Model.py
class Employee(models.Model):
ename=models.CharField(max_length=120)
eaddress=models.CharField(max_length=120)
eemail=models.CharField(max_length=120)
ephone=models.CharField(max_length=120)
emobile=models.CharField(max_length=120)
eid=models.CharField(max_length=120)
egender=models.CharField(max_length=120)
ehire=models.DateTimeField()
edob=models.DateTimeField()
class Meta:
db_table="employee"
views.py
def employee(request):
emp=Employee.objects.all()
return render(request,'employee.html',{'emp':emp})
def addemployee(request):
if request.method == 'POST':
emp = EmployeeForm(request.POST)
if emp.is_valid():
try:
form.save()
return redirect(employee)
except:
pass
else:
emp = EmployeeForm()
return render(request,'addemployee.html',{'emp':emp})
addemployee.html:
<form method="POST" action="add_employee">
{% csrf_token %}
{{emp.ename}}
{{emp.eemail}}
{{emp.emobile}}
<button type="submit">Submit</button>
</form>
You need to display your form errors in template. So update your view and template like this:
def addemployee(request):
emp = EmployeeForm(request.POST or None)
if request.method == 'POST':
if emp.is_valid():
try:
emp.save()
return redirect(employee)
except Exception as e:
raise e # for debug purpose now
return render(request,'addemployee.html',{'emp':emp})
addemployee.html:
<form method="POST" action="add_employee">
{% csrf_token %}
{{ emp.errors }} // it will render form errors
{{emp.ename}}
{{emp.eemail}}
{{emp.emobile}}
<button type="submit">Submit</button>
</form>
I am assuming your form is not validating because you have many fields like eid, egender etc which are required for saving it in Database. If you are using Modelform, then you can use {{ emp.as_p }} as per form rendering documentation for rendering form instead of {{emp.ename}} {{emp.eemail}} {{emp.emobile}}.

Invalid form when uploading a file

I am trying a basic example in uploading a file with django.
I tried the code from the django documentaion but I keep getting invalid form. And when I don't test the validation of the form and try to handle the file directly, I get:
MultiValueDictKeyError at /neurons/nblast
"
'file'"
P.S:
Previously, I had used a model with a FileField and set the (upload_to), but in my current case I don't need to use the model, I only need to let the user uploads his files.
This is my code:
Template
<body>
<form action="" method="post">
{{ form }}
<br>
<button class="btn btn-success" name="btn_upload">
<span class="glyphicon glyphicon-upload"></span>
<b>Upload</b>
</button>
{% csrf_token %}
</form>
</body>
Views
def test(request):
if request.method == GET:
form = UploadFileForm()
if request.method == POST:
if 'btn_upload' in request.POST:
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
else:
print 'Not Valid'
form = UploadFileForm()
return render_to_response('test.html',
{'form': form},
context_instance=RequestContext(request))
Forms:
class UploadFileForm(forms.Form):
file = forms.FileField()
Thank you very much
Have you tried looking at The Django 'File Uploads' docs , especially the enctype="multipart/form-data" attribute?
u missed this one enctype="multipart/form-data"

Form is not rendered in the template after redirection (django)

I have a view and its template that handles and prints a form. The form has a ChoiceField that takes a list of models as choices. Here is my view, template and form:
*views.py*
def index(request):
form = dbForm()
print "form is: ", form
return render(request, 'Directories/index.html', {'form':form})
*index.html*
<div id="content" align="center">
<form action="" method="get"> {% csrf_token %}
{{form.as_p}}
<input type="submit" value="Edit" name="_add" />
</form>
*forms.py*
model_classes = []
class dbForm(forms.Form):
model_classes_field = forms.ChoiceField(choices=models())
def models():
apps = get_app('Directories')
for model in get_models(apps):
model_classes.append( (model._meta.verbose_name, model._meta.db_table), )
return model_classes
The model choice submitted is sent to another view where a ModelForm displays the model's fields and expects data for each of the fields to be submitted. The submitted data are then stored in the database and the user is redirected back to the index to start again from the beginning. Here is the view, template and form:
*views.py*
def modelUpdate(request):
if 'update' in request.POST: # If the form has been submitted...
form_class = get_dynamic_form(request.GET['model_classes_field'])
form = form_class(request.POST)
if form.is_valid(): # All validation rules pass
row = form.save() #saves into database
return render(request, 'Directories/index.html')
else:
print "form errors: ", form.errors
return HttpResponse('ERROR -- Return to form submission')
*create.html*
<form action="" method="post"> {% csrf_token %}
{% for f_name in field_names %}
{% if not forloop.first %}
{{f_name}}: <input id="edit-{{f_name}}" type="text" name={{f_name}} /><br />
{% endif %}
{% endfor %}<br />
<input type="submit" name="update" value="Update" />
<input type="reset" name="Clear" value="Clear" />
</form>
*forms.py*
#create a ModelForm using a dynamic model
def get_dynamic_form(c_model):
model_class = get_model('Directories', c_model)
class ObjForm(forms.ModelForm ):
class Meta:
model = model_class
return ObjForm
The problem occurs when the form is redirected back to the index.html return render(request, 'Directories/index.html') after the data have been saved into the database. What happens is that the index.html does not display the form {{form.as_p}}at all. Although when i check print "form is: ", form in my server (Apache) error.log, my form is there printed as it should be.
I cannot understand why the data are not rendered in my template after the redirection occurs but still they are displayed correctly in my server log.
You should pass the form instance to your template as you do in index view. Your code shall be updated to
def modelUpdate(request):
if 'update' in request.POST: # If the form has been submitted...
form_class = get_dynamic_form(request.GET['model_classes_field'])
form = form_class(request.POST)
if form.is_valid(): # All validation rules pass
row = form.save() #saves into database
#------------------------------------------------v pass it to template
return render(request, 'Directories/index.html', {'form': form})
else:
print "form errors: ", form.errors
return HttpResponse('ERROR -- Return to form submission')