Date and Time Field in Django Form - python

I have two field in my django form as well as model, One is date other is time . I want to submit date and time in database. But I haven't succeeded in it yet. Please suggest some code that can make it possible.
form.py
class dated1(forms.ModelForm):
cur_date=forms.DateField()
cur_time=forms.TimeField(datetime.time)
class Meta:
model=dated
model.py
class dated(models.Model):
cur_date = models.DateField()
cur_time = models.TimeField()
def __unicode__(self):
return self.cur_date
view.py
def datetime1(request):
if request.method =='POST':
form = dated1(request.POST)
if form.is_valid():
f=dated(
cur_date=request.POST('cur_date'),
cur_time=request.POST('cur_time'),
)
f.save()
return HttpResponse("Success")
else:
return HttpResponse("Failure")
else:
form = dated1()
return render(request, 'formdata/dt.html',{'form': form})

instead of
f=dated(
cur_date=request.POST('cur_date'),
cur_time=request.POST('cur_time'),
)
f.save()
try this
f = form.save(commit=False)
f.save()

in the template, I made some changes :
{% extends 'formdata/template1.html' %}
{% block js %}
<script type="text/javascript">
$(function()
{
$( "#id_cur_date" ).datepicker({dateFormat: $.datepicker.ATOM});
});
$(function()
{
$('#id_cur_time').timepicker({timeFormat: 'H:i:s'});
});
</script>
{% endblock %}
{% block content %}
<form id="dtform" method="post" action="#">
{% csrf_token %}
<h3>Date:</h3>
{{ form.cur_date }}
<h3>Time:</h3>
{{ form.cur_time }} <br>
<input type="submit" value="submit">
</form>
{% endblock %}
then I made some changes in views.py
def datetime1(request):
if request.method =='POST':
form = dated1(request.POST)
f=dated(
cur_date=request.POST['cur_date'],
cur_time=request.POST['cur_time']
)
f.save(force_insert=True)
return HttpResponse("Success")
else:
form = dated1()
return render(request, 'formdata/dt.html',{'form': form})
now when I remove "if form.is_valid()" in the views, it has been submitted successfully in standard format I wanted. Also I add a date picker and time picker through jQuery.
with this answer my question is; why the statement "if form.is_valid()" was not working in above case. #abhi #Paul Collingwood

Related

Django adds square brackets and quotes to charfield input

recently I encountered a rather weird problem with my Django forms. I am currently working on my todo list project. Everything works fine, except that whenever I add a new task, its title seems to be saved in database with additional square brackets and quotes around it. It looks like one-element list, but it is a string. I kinda solved it by displaying the silced version of the string from the database, but it still shows for example while editing a task. Hope anyone has some idea what might be going on?
models.py:
from django.db import models
class Task(models.Model):
title = models.CharField(max_length=35)
completed = models.BooleanField(default=False)
created_date = models.DateTimeField(auto_now_add=True)
# added_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
author = models.CharField(max_length=50, default='')
def __str__(self):
return self.title
forms.py:
from django import forms
from .models import *
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = '__all__'
widgets = {
'title': forms.TextInput(attrs={'class': 'new_task_text', 'placeholder': 'Add new task'}),
}
class TaskEditForm(forms.ModelForm):
class Meta:
model = Task
fields = ['title', 'completed']
widgets = {
'title': forms.TextInput(attrs={'class': 'new_task_text'}),
}
views.py:
from django.shortcuts import render, redirect
from .forms import *
from django.contrib.auth.decorators import login_required
#login_required
def list_homepage(request):
tasks = Task.objects.filter(author=request.user.username)
for task in tasks:
if "['" and "']" in task.title:
task.title = task.title[2:-2] # CharField returns a string that is looking like one-element list. Have no idea why yet.
# try using form instead of modelform.
form = TaskForm()
if request.method == 'POST':
form = TaskForm({**request.POST, **{'author': request.user.username}})
if form.is_valid():
form.save()
else:
print(form.errors)
return redirect('/list/home')
context = {
'page_title': 'Todo list',
'tasks': tasks,
'form': form,
}
return render(request, 'tasks/list.html', context)
#login_required
def update_task(request, pk):
task = Task.objects.get(id=pk)
form = TaskEditForm(instance=task)
if request.method == 'POST':
form = TaskEditForm(request.POST, instance=task)
if form.is_valid():
form.save()
return redirect('../..')
context = {
'form': form,
'page_title': 'Update task',
}
return render(request, 'tasks/update_task.html', context)
#login_required
def delete_task(request, pk):
task = Task.objects.get(id=pk)
if request.method == 'POST':
task.delete()
return redirect('/list')
context = {
'page_title': 'Delete task',
'task': task,
}
return render(request, 'tasks/delete_task.html', context)
list.html:
{% extends 'tasks/base.html' %}
{% block content %}
<div class="new-task-column">
<form method="POST", action="#"> {% csrf_token %}
{{ form.title }}
<input class="submit" type="submit", value="Create task">
</form>
</div>
<div class="task-column">
{% for task in tasks %}
<div class="item-row">
<div class="task">
{% if task.completed == True %}
<s>{{ task }} </s>
{% else %}
{{ task }}
{% endif %}
</div>
<div class="del_upd_container">
<div class="single-upd-container"><a class="edit_button" href="/list/update_task/{{ task.id }}">Update</a></div>
<div class="single-del-container"><a class="edit_button" href="/list/delete_task/{{ task.id }}">Delete</a></div>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
update_task.html:
{% extends 'tasks/base.html' %}
{% block content %}
<div class="new-task-column">
<form method="POST"> {% csrf_token %}
<span class="update-task-layout">
{{ form }}
<input class="submit" type="submit" name="Update item">
</span>
</form>
</div>
{% endblock content %}
Thank you so much for any help, I really appreciate it!
Had the same problem, solved it by using the method dict() to transform request.POST's weird type (QueryDict) into a normal dict. The rest of the code, like the save() method for example, might need to be a bit adjusted.

How to auto-fill fields while updating django forms?

I am creating a to-do app in django and while updating a task, i want to auto-fill the fields with previous data. Where am i messing up?
This is my views.py for the same:-
task = get_object_or_404(ToDoList, id=id)
if request.method == "POST":
form = UpdateTaskForm(request.POST)
if form.is_valid():
task.description = form.cleaned_data['description']
task.save()
form.save()
return redirect(reverse('list'))
else:
form = UpdateTaskForm(instance=task)
context = {
'form':form,
'task':task,
}
return render(request, 'TaskList/update.html', context)
and this is my forms.py:-
class Meta:
model = ToDoList
fields = ['title', 'description', 'due_date', 'completed']
here is my template file:-
{% load crispy_forms_tags %}
{% block title %} Updating task {% endblock %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-success" value="Submit"> Save </button>
</form>
{% endblock %}
and here is my models.py:-
from django.utils import timezone
# Create your models here.
class ToDoList(models.Model):
title = models.CharField(max_length=120)
description = models.TextField(help_text='Explain your task!', blank=True)
created_date = models.DateTimeField(default=timezone.now())
due_date = models.DateTimeField(default=timezone.now())
completed = models.BooleanField(default=False)
#Author foreign key
def __str__(self):
return self.title
If you are updating an instance you must also pass the same instance in the POST method also, so after
if request.method == "POST": add form = UpdateTaskForm(request.POST,instance=task)
I guess you are using crispy forms, so according to this question here They are rendering the forms using {% crispy form %} instead of the way you have done as {{ form|crispy }} maybe that is the issue.

Django - saving form to the built in database SQLite

This is my first time using Django and I am very simply trying to save text to the database. I have created the table inputs in the database.
I am getting the following error;
Error - Page not found (404)
My code is as follows;
Models.py
from django.db import models
class Input(models.Model):
waist = models.IntegerField(default=0)
height = models.IntegerField(default=0)
def __unicode__(self):
return "{0} {1} {2}".format(
self, self.waist, self.height)
forms.py
class InputForm(forms.ModelForm):
class Meta:
model = Input
fields ={
'waist',
'height'
}
views.py
def InputView(request):
if request.POST:
form = InputForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('account/input')
else:
form = InputForm()
args = {'form' : form}
return render(request,'accounts/input.html', args)
urls.py
url(r'^input/$',views.InputView, name='view_input')
input.html
{% extends 'base.html' %}
{% block head %}
<title> Edit Profile </title>
{% endblock %}
{% block body %}
<div class="container">
<h1> Enter Body Details </h1>
<br>
<br>
<form action="account/input" method="post">
{% csrf_token %}
<ul>
{{form.as_ul}}
</ul>
<input type="Submit" name="submit" value="submit"/>
</form>
</div>
{% endblock %}
If any one can help it would be greatly appreciated.
HttpResponseRedirect('account/input')
you need to add one more '/' to the beginning like
HttpResponseRedirect('/account/input')
Another way to do it is to use reverse() so if you change the URL you don't have to change your code and you avoid mistakes entering the URL.
Instead of
HttpResponseRedirect('/account/input')
use
HttpResponseRedirect(reverse('view_input'))
remember to add the import
from django.urls import reverse

data is not inserting in database when I click submit button

I have created my first app in Django (1.10.5) / Python 3.4. I have a login page and a register page. Which is working fine.
I can create new user and login with that id. Now after the login I want user to fill a form with some information and click on submit. And the information should get stored in the database.
So I created a model first : Model.py
class UserInformation(models.Model):
firstName = models.CharField(max_length=128)
lastName = models.CharField(max_length=128)
institution = models.CharField(max_length=128)
institutionNumber = models.CharField(max_length=128)
cstaPI = models.CharField(max_length=128)
orchidNumber = models.CharField(max_length=128)
This has created a table in the DB.
forms.py
class UserInformationForm(ModelForm):
class Meta:
model = UserInformation
fields = '__all__'
views.py
def home(request):
form = UserInformationForm()
variables = { 'form': form, 'user': request.user }
return render(request,'home.html',variables)
home.html
{% extends "base.html" %}
{% block title %}Welcome to Django{% endblock %}
{% block head %}Welcome to Django{% endblock %}
{% block content %}
<p> Welcome {{ user.username }} !!! Logout<br /><br /> </p>
<form method="post" action=".">{% csrf_token %}
<table border="0">
{{ form.as_table }}
</table>
<input type="submit" value="Submit" style="position:absolute"/>
</form>
{% endblock %}
But when I click on submit button, It does not insert data into my table.
here is the answer, we need to use the request.POST
def home(request):
if request.method == 'POST':
form = UserInformationForm(request.POST)
form.save()
return HttpResponseRedirect('/home/')
else:
form = UserInformationForm()
variables = { 'form': form, 'user': request.user }
return render(request,'home.html',variables)
the first: you need add urls.py to you app
the second: you need to change your views.py to lool like this
`
info = UserInformation()
lastName = request.POST.get('lastName')
...
info.save()
`

django inline formset to upload multiple files not rendering form

I have model:
class MediaInfo(models.Model):
title = models.CharField(max_length=50,blank=True)
description = models.CharField(max_length=255,blank=True)
media_file = models.FileField(upload_to=get_upload_file_name)
def __unicode__(self):
return self.title
class Media(models.Model):
media_files = models.ForeignKey(MediaInfo)
def __unicode__(self):
return self.media_files
What I want is to render a template where I get a simple browse button and I can select and upload multiple 'media_file'.
I came to know that it can be performed from inline formset so used it in my view. My view looks like
def MediaAddView(request):
#med = MediaInfo.objects.al()
MediaInlineFormset = inlineformset_factory(MediaInfo, Media)
if request.method == "POST":
formset = MediaInlineFormset(request.POST, request.FILES)
if formset.is_valid():
formset.save()
return HttpResponseRedirect("some url")
else:
return render_to_response("media_add.html",
{"formset":formset,},
context_instance=RequestContext(request))
else:
formset = MediaInlineFormset()
return render_to_response("media_add.html",
{"formset":formset,}, context_instance=RequestContext(request))
and my template is :
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{{form.media_file}}
{% endfor %}
<input type="submit" value="Submit" />
</form>
When I do this instead of getting a browse button to upload file I am getting only submit button.
How can I get just a browse button and add multiple files or images ?
Whats wrong in my code ?
Need help

Categories

Resources