I have this view that creates a form with groups and exercises.
How can I do to be able to create more groups and exercises in the template?
views.py
#login_required
def creaScheda(request):
if request.method == "POST":
form = CreaSchedaForm(request.POST)
if form.is_valid():
schedaName = form.cleaned_data['nome_scheda']
scheda = form.save(commit = False)
scheda.utente = request.user
scheda.save()
gruppi = DatiGruppi(
giorni_settimana = form.cleaned_data['giorni_settimana'],
dati_gruppo = form.cleaned_data['dati_gruppo'],
gruppi_scheda = Schede.objects.get(nome_scheda = schedaName)
)
gruppi.save()
esercizi = DatiEsercizi(
serie = form.cleaned_data['serie'],
ripetizione = form.cleaned_data['ripetizione'],
peso = form.cleaned_data['peso'],
gruppo_single = DatiGruppi.objects.get(gruppi_scheda = scheda.id),
dati_esercizio = form.cleaned_data['dati_esercizio']
)
esercizi.save()
return redirect('/backoffice')
else:
form = CreaSchedaForm()
context = {"form": form}
return render(request, "crea_scheda.html", context)
A solution to this would be using the bulk_create method on the object manager with an array/list of the objects to be created
example
ModelName.objects.bulk_create([
ModelName(title="Model1"),
ModelName(title="Model2"),
ModelName(title="Model3"),
])
where ModelName refers to the Name of Your Model, and ModelName within the list refers to the different instances/records of the ModelName class/database to be create in a bulk
Related
hello I have a table named Exercise data where I pass data from form and save them in the db, my problem is that I have more same objects to save inside the db but I don't know how to do it.
I left you my views.py file where you can find the code I created.
I read around that I should use the create_bulk but I don't understand how I can pass it some data from my form, could someone help me please? =)
views.py
#login_required
def creaScheda(request):
if request.method == "POST":
form = CreaSchedaForm(request.POST)
if form.is_valid():
schedaName = form.cleaned_data['nome_scheda']
scheda = form.save(commit = False)
scheda.utente = request.user
scheda.save()
gruppi = DatiGruppi(
giorni_settimana = form.cleaned_data['giorni_settimana'],
dati_gruppo = form.cleaned_data['dati_gruppo'],
gruppi_scheda = Schede.objects.get(nome_scheda = schedaName)
)
gruppi.save()
esercizi = DatiEsercizi(
serie = form.cleaned_data['serie'],
ripetizione = form.cleaned_data['ripetizione'],
peso = form.cleaned_data['peso'],
gruppo_single = DatiGruppi.objects.get(gruppi_scheda = scheda.id),
dati_esercizio = form.cleaned_data['dati_esercizio']
)
#esercizi.save()
print(esercizi)
return redirect('/backoffice')
else:
form = CreaSchedaForm()
context = {"form": form}
return render(request, "crea_scheda.html", context)
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.
views.py
def patient_num(request):
if request.method == 'POST':
form = EditToBeSaveForm(request.POST)
if form.is_valid():
num = form.cleaned_data['病人编号']
new_p = Patient.objects.get(p_number=num)
if new_p:
new_p.p_name = form.cleaned_data['姓名']
new_p.p_sex = form.cleaned_data['性别']
new_p.p_age = form.cleaned_data['年龄']
new_p.p_tel_number = form.cleaned_data['电话号码']
new_p.save()
return render(request, 'polls/patient_edit.html')
else:
form = EditToBeSaveForm()
return render(request, 'polls/patient_num.html', {'form': form})
models.py
class Patient(models.Model):
sex_choice = (
('男', '男'),
('女', '女'),
)
p_name = models.CharField(max_length=100, default='template')
p_age = models.IntegerField(default=0)
p_number = models.IntegerField(default=0)
p_tel_number = models.IntegerField(default=0)
p_sex = models.CharField(choices=sex_choice, max_length=2, default='男')
forms.py
class EditForm(forms.Form):
病人编号 = forms.IntegerField()
class EditToBeSaveForm(forms.Form):
sex_choice = (
('male', '男'),
('female', '女'),
)
病人编号 = forms.IntegerField(label='你要修改的病人编号')
姓名 = forms.CharField(max_length=100)
年龄 = forms.IntegerField()
电话号码 = forms.IntegerField()
性别 = forms.ChoiceField(choices=sex_choice)
after i populate the form and submit it, the view didn't update the database instance,why?
i can do it one by one in shell as below.
new confuse!when i populate the form with invalid value,for example, an inexistent id of Patient object,it will still render the template,why?
It seems to me your problem is that you never reach the code under the if form.is_valid() of your patient_num view. Try to add some prints after the if form.is_valid() clause and make sure your form is valid. It is expected that your model will not be updated if your form is not valid.
Your problem here that you are passing request to form instead request.POST
form = EditToBeSaveForm(request.POST)
i put some 'print stuff' in my view and disvocer sth:
def patient_num(request):
print(111)
if request.method == 'POST':
print(2222)
form = EditToBeSaveForm(request.POST)
if form.is_valid():
print(3333)
num = form.cleaned_data['病人编号']
new_p = Patient.objects.get(p_number=num)
if new_p:
print(4444)
new_p.p_name = form.cleaned_data['姓名']
new_p.p_sex = form.cleaned_data['性别']
new_p.p_age = form.cleaned_data['年龄']
new_p.p_tel_number = form.cleaned_data['电话号码']
new_p.save()
return render(request, 'polls/patient_edit.html')
else:
form = EditToBeSaveForm()
return render(request, 'polls/patient_num.html', {'form': form})
i can only see 111 in the shell output.it seems that the view even didn't receive the post request.and i check my html file and find the problem.the form's destination direct to another view function…… it's so stupid, i'm sorry for waste your time !
I create several forms to edit some records. When I save the form, I can see in the database that the application update the record and insert one or two record more.
All the forms that I use to update record have this weird behavior. I don't know if the error is in the form definition or in the view definition.
Model
class DetalleRecepcion(models.Model):
id_proveedor = models.ForeignKey(Proveedor,db_column='id_proveedor',primary_key=True, verbose_name='Proveedor')
anio = models.IntegerField( null=False)
mes = models.IntegerField(verbose_name='Mes')
fecha_recepcion = models.DateField(verbose_name='Fecha Recepcion')
usuario = models.CharField(max_length=15, blank=True)
num_archivos = models.IntegerField(primary_key=True, verbose_name='No de archivos')
class Meta:
managed = False
db_table = 'mpc_detalle_recepcion'
View
#login_required(login_url='/login/')
def DetRecView(request):
idp = request.GET.get('i')
anio = request.GET.get('a')
mes = request.GET.get('m')
if request.method == 'POST':
r = DetalleRecepcion.objects.get(id_proveedor=idp,anio=anio,mes=mes)
form = DetRecForm(request.POST or None, instance =r)
if form.is_valid():
form.save()
return HttpResponse('<script type="text/javascript">window.close()</script>')
else:
r = DetalleRecepcion.objects.get(id_proveedor=idp,anio=anio,mes=mes)
r.usuario = request.user
form = DetRecForm(instance=r)
return render_to_response('detrec.html',
{'form':form},
context_instance=RequestContext(request))
Form
class DetRecForm(forms.ModelForm):
fecha_recepcion = forms.DateField(widget=DateInput(),)
def __init__(self,*args,**kwargs):
super(DetRecForm,self).__init__(*args,**kwargs)
self.helper = FormHelper(self)
self.helper.layout = Layout(
Field('id_proveedor',
'anio',
'mes',
'usuario',
readonly = True
),
Fieldset('',
'fecha_recepcion',
'num_archivos',
Submit('save','Grabar'),
HTML('<a class="btn btn-danger" id="cerrar">Cancelar</a>')
)
)
class Meta:
model = DetalleRecepcion
I am using a legacy database, I check the constrains, procedure, triggers of the database and everything look fine.
Beside the table don't use any procedure function etc.
And only when I update or insert from the application I can see this behavior.
UPDATE
urls.py
urlpatterns = patterns('',
url(r'^recepcion/$','prov.views.DetRecView',name='recepcion'),
url(r'^newdetrec/$','prov.views.NewDetRecView',name='newdetrec'),
url(r'^master/$','prov.views.NewMasterView',name='master'),
url(r'^conci/$', 'prov.views.ConciView',name='conci'),
url(r'^carga/$', 'prov.views.CargaView',name='carga'),
url(r'^gencert/$', 'prov.views.GenCertView',name='gencert'),
url(r'^entcert/$', 'prov.views.EntCertView',name='entcert'),
url(r'^aceptacert/$', 'prov.views.AceptaCertView',name='aceptacert'),
url(r'^envconci/$', 'prov.views.EnvConciView',name='envconci'),
)
My create view (for the same model)
#login_required(login_url='/login/')
#permission_required('prov.views.configView',login_url='/login/')
def NewDetRecView(request):
form = NewDetRecForm(request.POST or None)
if request.method == 'POST':
idp = request.POST['id_proveedor']
a = request.POST['anio']
m = request.POST['mes']
id = Proveedor.objects.get(id_proveedor=idp)
obj,created = DetalleRecepcion.objects.get_or_create(id_proveedor=id,anio=a,mes=m)
obj.save()
return HttpResponseRedirect('/monitor/')
if not created:
obj.id_proveedor = id
obj.anio = a
obj.mes = m
obj.save()
return HttpResponseRedirect('/monitor/')
return render_to_response('newdetrec.html',
{'form':form})
My form class to create new records:
class NewDetRecForm(forms.ModelForm):
def __init__(self,*args,**kwargs):
super(NewDetRecForm,self).__init__(*args,**kwargs)
self.helper = FormHelper(self)
self.helper.layout.append(Submit('save','Grabar'))
self.helper.layout = Layout(
Fieldset('',
'id_proveedor',
'anio',
'mes',
Submit('save','Grabar'),
)
)
def clean(self):
cleaned_data = super(NewDetRecForm, self).clean()
id_proveedor = self.cleaned_data['id_proveedor']
#num_archivos = self.cleaned_data['num_archivos']
anio = self.cleaned_data['anio']
mes = self.cleaned_data['mes']
qs = self.Meta.model.objects.filter(id_proveedor=id_proveedor, anio=anio, mes=mes)
if self.instance:
qs = qs.exclude(pk = self.instance.pk)
if qs.count() > 0:
raise forms.ValidationError(u'Registro ya existente')
return cleaned_data
class Meta:
model = DetalleRecepcion
DetRecForm is for update
DetRecView is for update
NewDetRecForm is for create
NewDetRecView is for create
UPDATE 2
javascript function to pass parameters
<script type="text/javascript">
$(document).ready ( function () {
$(document).on ("click", "#recepcion", function (event) {
event.preventDefault();
var tbl = document.getElementById("myTable");
var idpro = $(this).parents('tr:first').find('td:first').text();
var anio = $(this).closest('tr').children(":eq(1)").text();
var mes = $(this).closest('tr').children(":eq(2)").text();
var argu = "?i="+idpro+"&a="+anio+"&m="+mes;
//window.location = "/recepcion/"+argu;
var url = "/recepcion/"+argu;
window.open(url,'_blank')
});
});
</script>
I know this isn't the right way to pass parameters to the templates.
I am start learning AJAX to pass the data, but meanwhile I use this horrible function
url(r'^recepcion/add/$','prov.views.DetRecView',name='recepcion_add'), # create object
url(r'^recepcion/edit/(?P<pk>\d+)/$','prov.views.DetRecView',name='recepcion_edit'), # update object
Lets look at your condition in the view function: if request.method=='POST' better use if request.POST,
So when you have else - it means request.GET you get an instance of DetalleRecepcion (read instance as object of some class) and pass it to your ModelForm. It is update object approach (but you use this to create object), and provided query must give one object (unique).
If you want use this view to create and update you have to change your urls (smth like I did above) and you have to define condition: if request.kwargs.get('pk') you're going to update object else you're going to create object.
Main difference that if it is update case you have to provide instance to your form r = DetalleRecepcion.objects.get(pk=request.kwargs['pk']), so DetRecForm(instance=r) (whenrequest.GET) and form = DetRecForm(request.POST, instance =r) (whenrequest.POST).
If you want provide some initial data to your form (when request.GET) use DetRecForm(initial = {'id_proveedor': idp, 'anio': anio, 'mes': mes, 'usuario': request.user})
another django question. I have a edit form like this. Look at current_status in the code.
It has been updated:
def edit_item(request, client_id = 0, item_id = 0):
client = None
item = None
status = None
contact = None
status_id = request.POST.get('status_id', None)
contact_id = request.POST.get('contact_id', None)
save_item = request.POST.get('save_item', None)
save_status = request.POST.get('save_status', None)
try:
client = models.Client.objects.get(pk = client_id)
item = models.StorageItem.objects.get(pk = item_id)
except:
return HttpResponseNotFound()
try:
status = models.Status.objects.get(pk = status_id)
contact = models.Contact.objects.get(pk = contact_id)
except:
pass
if request.method == 'POST':
form = forms.ItemForm(request.POST, instance = item)
if form.is_valid() and save_item is not None:
form.save(True)
request.user.message_set.create(message = "Item {0} has been updated successfully.".format(item.tiptop_id))
return HttpResponse("<script language=\"javascript\" type=\"text/javascript\">window.opener.location = window.opener.location; window.close();</script>")
if status is not None and contact is not None and save_status is not None:
current_status = models.ItemStatusHistory(item = item, contact = contact, status = status,
user = request.user)
item.current_item_status_date = date.today()
item.save()
current_status.save()
request.user.message_set.create(message = "Item status has been updated successfully.")
else:
form = forms.ItemForm(instance = item)
title = str(client) + ' : Edit Item'
status_list = models.Status.objects.all()
return render_to_response('edit_item.html', {'form':form, 'title':title, 'status_list':status_list, 'item':item}, context_instance = RequestContext(request))
current_status save's the latest date of when the form is edited. What I ALSO want to do is to save this value into this models field.
class StorageItem(models.Model):
current_item_status_date = models.DateField()
Is ItemForm a ModelForm (see Django Model Forms)?
If so form.save() will return a model instance. Then you can edit its fields if you need to. For example.
my_obj = form.save()
my_obj.current_item_status_date = datetime.date.today()
my_obj.save()
If not, then simply create a new instance of your model and save the field value.
my_obj = StorageItem(current_item_status_date=datetime.date.today())
my_obj.save()