views.py
def when(request):
user = request.user
report = Report.objects.get(user=request.user)
reportform = ReportForm(instance=report)
settings = Settings.objects.get(user=request.user)
settingsForm = SettingsForm(instance=settings)
# settings=Settings.objects.get(user=2)
if settings.date_format == '0':
date = report.manual_date.strftime('%d/%m/%Y')
else:
date = report.manual_date.strftime('%m/%d/%Y')
if settings.time_format == '0':
time = report.manual_time.strftime('%I:%M%p')
else:
time = report.manual_time.strftime('%H:%M')
if request.method == 'POST':
reportform = ReportForm(instance=report,data=request.POST,initial={'manual_date': date,'manual_time': time})
if reportform.is_valid():
report = reportform.save(commit=False)
report.user = request.user
report.save()
return redirect('/member/media/')
return render_to_response('incident/when.html',{
'newreport_menu': True,
'form': reportform,
'date':date,
'time':time,
},
context_instance=RequestContext(request))
forms.py
class ReportForm(forms.ModelForm):
class Meta:
model = Report
fields = ['incident_description','manual_date','manual_time', 'location_description',
'incident_followup', 'incident_followup_name_1', 'incident_followup_email_1',
'incident_followup_name_2', 'incident_followup_email_2', 'phone_call_log',
'notes_other','notes_firstaid','notes_risk']
# manual_date = forms.DateField(input_formats=['%d/%m/%Y', '%d-%m-%Y'],
# widget=forms.DateInput(format="%-d/%-m/%Y"))
widgets = {'manual_date': forms.DateInput(attrs={'size':'15','id':'datepicker',
},format='%d/%m/%Y'),'manual_time': forms.TimeInput(attrs={'size':'8','class':'time_field', },format='%H:%M')
}
How to pass the converted date and time format i.e,date and time variable to form.The format what i specified in form is displaying now,but depend on the condition on views,the time and date format should change in form field.
Thanks
Try to create the form with this line:
reportform = ReportForm(instance=report,initial={'manual_date':date, 'manual_time':time})
where date variable is the date formatted. You will have to move down the instantiation of the form. This would be your code:
def when(request):
user = request.user
report = Report.objects.get(user=request.user)
settings = Settings.objects.get(user=request.user)
settingsForm = SettingsForm(instance=settings)
# settings=Settings.objects.get(user=2)
if settings.date_format == '0':
date = report.manual_date.strftime('%d/%m/%Y')
else:
date = report.manual_date.strftime('%m/%d/%Y')
if settings.time_format == '0':
time = report.manual_time.strftime('%I:%M%p')
else:
time = report.manual_time.strftime('%H:%M')
if request.method == 'POST':
reportform = ReportForm(instance=report,data=request.POST,initial={'manual_date': date,'manual_time': time})
if reportform.is_valid():
report = reportform.save(commit=False)
report.user = request.user
report.save()
return redirect('/member/media/')
reportform = ReportForm(instance=report,initial={'manual_date':date, 'manual_time':time})
return render_to_response('incident/when.html',{
'newreport_menu': True,
'form': reportform,
'date':date,
'time':time,
},
context_instance=RequestContext(request))
That tries to set manually the initial value of the form already formatted when you instantiate it.
Hope it helps!
You can use template tag/filter date. Define it on the view level and pass to the template:
if settings.date_format == '0':
date_filter = 'd/m/Y'
else:
date_filter = 'm/d/Y'
if settings.time_format == '0':
time_filter = 'I:Mp'
else:
time_filter = 'H:M'
In the template:
{{ form.manual_date|date:date_filter }}
{{ form.manual_time|date:time_filter }}
I'm not sure about the current format but you can always check the reference to get what you want.
PS. Perhaps the view is not the best place to put this code. It's much better to create separate function(s) to handle this.
Related
I want to save the data of the textfiled that take the location name and other filed from the html and save it in pgadmin4 by using the def in my view when I enter the value in html it is add but it shows me null in pgAdmin
this is my view
def location(request):
if request.method == 'POST':
form = request.POST
location_id = form.get(' location_id')
location_name = form.get('location_name')
location_address = form.get('location_address')
lat = form.get('lat')
lag_y = form.get('lag_y')
user_id = request.session['user_id']
print(form)
data_insert = MapModel.objects.create(location_id=location_id,
location_name=location_name,
location_address=location_address,
lat_x=lat,
lag_y=lag_y,)
if data_insert:
json_data = {'msg': " data added succssfully",
'id': data_insert.location_id
}
return JsonResponse(json_data)
else:
json_data = {'msg': " try agine",
'id': '',
}
return JsonResponse(json_data)
else:
return render(request, 'new_file.html')
This is my model :
class Card(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
imp_id = models.TextField(null = True)
And here is my view :
def Add(request):
if request.method == 'POST':
form = Add_card(request.POST)
if form.is_valid():
save = form.save(commit = False)
save.user = request.user
save.imp_id = "asd" # I tried to change it here but I failed
save.save()
else:
form = Add_card()
cards = Card.objects.all()
return render(request, 'addcard.html', {'form': form, 'cards' : cards})
How can I change that textfield before save?
you can do it like this
def Add(request):
if request.method == 'POST':
request.POST.imp_id="asd"
form = Add_card(request.POST)
if form.is_valid():
save = form.save(commit = False)
save.user = request.user
save.save()
else:
form = Add_card()
cards = Card.objects.all()
return render(request, 'addcard.html', {'form': form, 'cards' : cards})
The problem could be solved by using default='asd'.
Here are my lines dealing with the two forms :
user = request.user
user_liked = user_liked_form.save(commit = False)
user_liked.user = user
user_liked.save()
user_disliked = user_disliked_form.save(commit = False)
user_disliked.user = user
user_disliked.save()
The data submitted in second form is being saved in both liked and disliked.
I have used User foreignkey in both the liked and disliked models.
Here is the complete function :
def collect(request):
context = RequestContext(request)
submitted = False
if request.method == 'POST':
data = request.POST
user_liked_form = UserLikedForm(data = request.POST)
user_disliked_form = UserDislikedForm(data = request.POST)
# user_id = data["user_id"]
user = request.user
if user_liked_form.is_valid() and user_disliked_form.is_valid():
# user_liked_form.save(commit = True)
# user_disliked_form.save(commit = True)
user_liked = user_liked_form.save(commit = False)
user_liked.user = user
user_liked.save()
user_disliked = user_disliked_form.save(commit = False)
user_disliked.user = user
user_disliked.save()
submitted = True
else:
print user_liked_form.errors, user_disliked_form.errors
else:
user_liked_form = UserLikedForm()
user_disliked_form = UserDislikedForm()
return render_to_response(
'collect.html',
{'user_liked_form': user_liked_form, 'user_disliked_form': user_disliked_form, 'submitted': submitted},
context)
It sounds like your UserLikedForm and UserDislikedForm have the same field names and when the form is submitted, only the second value comes through in request.POST. To fix this, you will need to add a prefix to the forms:
user_liked_form = UserLikedForm(prefix='liked')
user_disliked_form = UserDislikedForm(prefix='disliked')
That way when the forms are rendered, each form will have unique field names.
In the view below, I prevent creation of a meeting with the same date and time. But anyhow, this code results in creating a recurrent meeting.
def new_meeting_board(request):
if User.is_authenticated:
username = request.user.username
else:
return HttpResponseRedirect('/login/board/')
if request.method == 'POST':
form = new_meetingForm(request.POST)
now = datetime.datetime.now()
if form.is_valid():
clash = 1
user = User.objects.get(username = username)
try:
meet_check = meeting.objects.get(date = form.cleaned_data['date'], time = form.cleaned_data['time'])
except meeting.DoesNotExist:
clash = 0
if clash == 1:
form = new_meetingForm()
variables = RequestContext(request, {
'username': username,
'form': form,
})
return render_to_response('new_meeting_board.html', variables)
else:
mem = memo(
snd_username = user,
rcv_username = form.cleaned_data['reciever'],
subject = 'Meeting',
date = str(now.year) + '-' + str(now.month) + '-' + str(now.day),
time = str(now.hour) + ':' + str(now.minute),
)
mem.save()
mee = mem.meeting_set.create(
snd_username = username,
rcv_username = mem.rcv_username,
status_username = '0',
date = form.cleaned_data['date'],
time = form.cleaned_data['time'],
venue = form.cleaned_data['venue'],
)
mee.save()
return HttpResponseRedirect('/dashboard/board/' + username)
else:
form = new_meetingForm()
variables = RequestContext(request, {
'username': username,
'form': form,
})
return render_to_response('new_meeting_board.html', variables)
The except portion of the try/except block does not seem to work for some reason. Please help.
meeting.objects should probably be Meeting.objects
There are multiple reformatting and optimization can be done in your code. Rather than using get(), you can use get_or_create to optimize code. You can write the code like this:
def new_meeting_board(request):
if not request.user.is_authenticated(): # there is a mistake in your code, its not User.is_authenticated.
return HttpResponseRedirect('/login/board/')
if request.method == 'POST':
form = new_meetingForm(request.POST)
now = datetime.datetime.now()
if form.is_valid():
user = request.user
meet_obj, meet_check = meeting.objects.get_or_create(
date = form.cleaned_data['date'],
time = form.cleaned_data['time'],
subject = 'Meeting',
snd_username=user,
rcv_username = form.cleaned_data['reciever']
)
if meet_check is True:
form = new_meetingForm()
variables = RequestContext(request, {
'form': form,
})
return render_to_response('new_meeting_board.html', variables)
else:
mee = meet_obj.meeting_set.create(
snd_username = username,
rcv_username = meet_obj.rcv_username,
status_username = '0',
date = form.cleaned_data['date'],
time = form.cleaned_data['time'],
venue = form.cleaned_data['venue'],
)
mee.save()
return HttpResponseRedirect('/dashboard/board/' + username)
else:
form = new_meetingForm()
variables = RequestContext(request, {
'form': form, # no need to send username, You can access it in the template by putting {{ request.user.username }}
})
return render_to_response('new_meeting_board.html', variables)
I'm trying write a small app while I'm learning django.However, when I try to save the form data in database, some problems happen to me.I use python3.4 and django 1.8.4, my database is MySql
The first problem I met is that the database doesn't have any data
this is my model code:
SUBJECT_CHOICES = (
('computerscience', '计算机科学导论'),
('C-sharp', 'C#'),
('cplusplus', 'C++'),
('CCNA', 'CCNA'),
('ACM', 'ACM'),
('linux', 'linux'),
('java', 'java'),
('python', 'python')
)
class Homework(models.Model):
handin_date = models.DateTimeField('交作业时间')
subject = models.CharField(verbose_name = '课程', default = '计算机科学导论', max_length = 20, choices = SUBJECT_CHOICES)
code = models.TextField(verbose_name = '代码', default = '')
xuehao = models.CharField(verbose_name = '学号', default = '', max_length = 9)
name = models.CharField(verbose_name = '姓名', default = '', max_length = 10)
this is my view code:
def cshomework(request):
if request.method == 'POST':
form = HomeworkForm(request.POST)
if form.is_valid():
return render(request, 'blog/success.html', { 'title': '交作业成功' })
else:
form = HomeworkForm(initial = { 'xuehao': '学号', 'name': '姓名', 'subject': '计算机科学导论', 'handin_date': dt.now(), 'code': '你的代码' })
return render(request, 'blog/cshomework.html', { 'title': '交作业', 'form': form })
In this way there's nothing in my database
The seconde question is when I tried another way, I get a None value in my datebase
The same model code as before
Here is my view code:
def cshomework(request):
if request.method == 'POST':
form = HomeworkForm(request.POST)
if form.is_valid():
return render(request, 'blog/success.html', { 'title': '交作业成功' })
else:
homework = Homework.objects.create(xuehao = '学号', name = '姓名', subject = '计算机科学导论', handin_date = dt.now(), code = '你的代码')
form = HomeworkForm(instance = homework)
return render(request, 'blog/cshomework.html', { 'title': '交作业', 'form': form })
the '课程' means 'subject'
How can I deal with these problems?
I' really appriciate your help!
After all check if form.is_valid(), you need save the form.
def cshomework(request):
if request.method == 'POST':
form = HomeworkForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'blog/success.html', { 'title': '交作业成功' })
else:
form = HomeworkForm(initial = { 'xuehao': '学号', 'name': '姓名', 'subject': '计算机科学导论', 'handin_date': dt.now(), 'code': '你的代码' })
return render(request, 'blog/cshomework.html', { 'title': '交作业', 'form': form })
At the second way, you are creating a new HomeWork everytime a URL is accessed, without submit any post data.