Django Can't save form data on database - django

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.

Related

the pgAdmin4 save null value

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')

how to upload an image in comments?

i have a small form in my blog detail view and it has a name,last name,email and an image field. the first three work fine but when i add the imagefield in the form, the form wont save from the page but it works from admin page.
this is my views.py:
def campaign_detail_view(request, id):
template_name = 'gngo/campaign-detail.html'
campaign = get_object_or_404(Campaign, id = id)
comments = CampaignForm.objects.filter(campaign=campaign).order_by('-id')
form = FormCamp(request.POST)
if request.method == 'POST':
if form.is_valid():
name = request.POST.get('name')
last = request.POST.get('last')
email = request.POST.get('email')
comment = CampaignForm.objects.create(campaign=campaign,name=name,last=last,email=email)
comment.save()
return redirect('campaign-detail',id=id)
else:
form = FormCamp()
context = {
'campaign':campaign,
'comments':comments,
'form':form,
}
context["object"] = Campaign.objects.get(id = id)
return render(request, template_name, context)
and this is my comment model:
class CampaignForm(models.Model):
campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
last = models.CharField(max_length=100)
email = models.EmailField()
image = models.ImageField(upload_to='images')
this is a non user form, so everyone can fill it. please help me understand how to add the ability to upload an image in this form
oh and this the form:
class FormCamp(forms.ModelForm):
class Meta:
model = CampaignForm
fields = ('name','last','email', 'image',)
THANKS ALOT FOR THE ANSWERS AND SUPPORTS
Instead of using the form to validate and then manually extracting the fields again, you should use the save method of your ModelForm and pass request.FILES to your form when creating it.
And as the campaign is not an editable field, it shall be added after creating the object.
def campaign_detail_view(request, id):
template_name = 'gngo/campaign-detail.html'
campaign = get_object_or_404(Campaign, id = id)
comments = CampaignForm.objects.filter(campaign=campaign).order_by('-id')
if request.method == 'POST':
form = FormCamp(request.POST, request.FILES)
if form.is_valid():
campaign_form = form.save(commit=False)
campaign_form.campaign = campaign
campaign_form.save()
return redirect('campaign-detail',id=id)
else:
form = FormCamp()
context = {
'campaign':campaign,
'comments':comments,
'form':form,
}
context["object"] = Campaign.objects.get(id = id)
return render(request, template_name, context)
https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/#the-save-method
https://docs.djangoproject.com/en/2.2/topics/forms/#the-view
Try this:
def campaign_detail_view(request, id):
template_name = 'gngo/campaign-detail.html'
campaign = get_object_or_404(Campaign, id = id)
comments = CampaignForm.objects.filter(campaign=campaign).order_by('-id')
form = FormCamp(request.POST, request.FILES)
if request.method == 'POST':
if form.is_valid():
comment = form.save(commit=False)
comment = CampaignForm.objects.create(campaign=campaign,name=name,last=last,email=email)
comment = request.FILES['image']
comment.save()
return redirect('campaign-detail',id=id)
else:
form = FormCamp()
context = {
'campaign':campaign,
'comments':comments,
'form':form,
}
context["object"] = Campaign.objects.get(id = id)
return render(request, template_name, context)
class FormCamp(forms.ModelForm): to this;
class FormCamp(forms.Form):
Don't forget to add enctype=multipart/form-data in your form in template.

How to convert Django model that has FileField into JSON

I tried to get the last inserted data from the following method
latest = AudioContentModel.objects.latest('id').id
object = model_to_dict(AudioContentModel.objects.get(pk=latest))
but I get the following error
TypeError: Object of type 'FieldFile' is not JSON serializable
How can I get the data from the table that was last inserted?
This is my model.py
class AudioContentModel(models.Model):
background_music = models.FileField(upload_to='documents/')
tts = models.FileField(upload_to='documents/')
final_audio = models.FileField(upload_to='documents/')
created = models.DateField(auto_now_add=True)
This is my view.py
def index(request):
if request.method == 'POST':
if request.is_ajax():
audiouploadform = AudioUploadForm(request.POST, request.FILES)
if audiouploadform.is_valid():
audiouploadform.save()
latest = AudioContentModel.objects.latest('id').id
print('Need to get the all the data from the latest and resturn as a JsonResponse')
data{
'background_music':
'tts':
'id':
}
return JsonResponse({'error': False, 'data': data})
else:
return JsonResponse({'error': True, 'errors': audiouploadform.errors})
else:
error = {
'message': 'Error! Must be an Ajax call'
}
return JsonResponse(error, content_type="application/json")
else:
audiouploadform = AudioUploadForm()
all_audio_files = AudioContentModel.objects.all()
data = {
'audio_file_list': all_audio_files,
'audiouploadform': audiouploadform,
}
return render(request, template_name='index.html', context=data)
I figure it out.
latest = AudioContentModel.objects.latest('id').id
print(latest)
instance = AudioContentModel.objects.get(pk=latest)
data = {
'id': instance.id,
'background_music': instance.background_music.url,
'tts': instance.tts.url,
'created':instance.created,
}

Django Views: DoesNotExist isn't working

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)

Passing variable to a form for display in django

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.