I am kinda like stuck.
I have a BankAccountCreation() and the the form is called in a modal in Django template.
I am trying to get the same for be used for editing. but when I do that my edit button returns an empty form
My view is as below
def employee_info(request, id):
if not request.user.is_authenticated:
return redirect('/')
context = {}
banks = Bank.objects.all()
employee = get_object_or_404(Employee, id = id)
bank_instance = Bank.objects.filter(employee = employee).first()
context = {}
context['employee'] = employee
context['bank'] = bank_instance
context['banks'] = banks
context['title'] = 'profile - {0}'.format(employee.get_full_name)
if request.method == 'GET':
form = BankAccountCreation()
context['form'] = form
return render(request, 'employee/employee_info.html', context)
if request.method == 'POST':
form = BankAccountCreation(data = request.POST)
if form.is_valid():
instance = form.save(commit = False)
employee_id = request.POST.get('employee')
employee_object = employee
instance.employee = employee_object
instance.name = request.POST.get('name')
instance.branch = request.POST.get('branch')
instance.account = request.POST.get('account')
instance.code = request.POST.get('code')
instance.save()
messages.success(request, 'Bank Details Successfully Created for {0}'.format(employee_object.get_full_name), extra_tags = 'alert alert-success alert-dismissible show')
return redirect('employee_info', id=employee.id)
else:
context['form'] = form
messages.error(request, 'Error Updating details for {0}'.format(employee_object.get_full_name), extra_tags = 'alert alert-warning alert-dismissible show')
return redirect('employee_info', id=employee.id)
form = BankAccountCreation()
return render(request, 'employee/employee_info.html', context)
The Bank model has a foreign key to the Employee model
Related
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'.
I have a crud application and would like to update the items. I have checked some solutions online which explains that the .update method can't be used like this but for only a queryset. I don't know how to update the information manually. Thanks
views.py
def UpdateReservation(request, pk):
table_exists = Reservation.objects.get(id=pk)
form = ReservationForm(instance=table_exists)
if request.method == "POST":
if request.POST['table']:
request.POST = request.POST.copy()
table_exists = Reservation.objects.get(id=pk)
try:
if table_exists:
time = form['time']
people = form['people']
comment = form['comment']
date_reserved = form['date_reserved']
email = form['email']
phone = form['phone']
first_name = form['first_name']
resrv = table_exists.update(email=email, first_name=first_name, people=people, time=time, date_reserved=date_reserved, comment=comment, table=table_exists)
resrv.save()
messages.success(request, "you have successfully edited.")
return redirect(request.path)
else:
messages.error(request, "Unable to edit.")
return redirect(request.path)
except Exception as e:
messages.error(request, "Unknown error" + str(e))
return redirect(request.path)
context = {"form":form}
return render(request, "dashboard/super/admin/update_reserve.html", context)
After trying that, it returns the error, Unknown error'Reservation' object has no attribute 'update'
It is better to validate the form and update the individual fields with respective values and then save the object. The view should be as follows:
from django.shortcuts import get_object_or_404
def UpdateReservation(request, pk):
table_exists = get_object_or_404(Reservation, id=pk)
form = ReservationForm(instance=table_exists)
if request.method == "POST":
form = ReservationForm(request.POST, instance=table_exists)
if form.is_valid():
time = form['time']
people = form['people']
comment = form['comment']
date_reserved = form['date_reserved']
email = form['email']
phone = form['phone']
first_name = form['first_name']
table_exists.email = email
table_exists.first_name = first_name
table_exists.people = people
table_exists.time = time
table_exists.date_reserved = date_reserved
table_exists.comment = comment
table_exists.save()
messages.success(request, "you have successfully edited.")
return redirect(request.path)
else:
messages.error(request, "Unable to edit.")
return redirect(request.path)
context = {"form": form}
return render(request, "dashboard/super/admin/update_reserve.html", context)
You should use model like this:
table_exists = Reservation.objects.get(id=pk)
table_exists.email = email
table_exists.first_name = first_name
table_exists.people = people
table_exists.time = time
table_exists.date_reserved = date_reserved
table_exists.comment = comment
table_exists.table = table_exists
table_exists.save()
I am trying to get data from child model through the parent model, I don't know if it possible or there is a way of doing it, and I want to know how to implement the formset concept in this context , I would be grateful for any solution
models.py
class Client_Data(models.Model):
RC = models.CharField(max_length=50)
Raison_social = models.CharField(max_length=254)
NIF = models.CharField(max_length=50,unique=True)
AI = models.CharField(max_length=50,unique=True)
NIS = models.CharField(max_length=50,unique=True)
Banque = models.CharField(max_length=50,unique=True)
CB = models.CharField(max_length=50)
adresse = models.CharField(max_length=50)
slug = models.SlugField(blank=True, unique=True)
active = models.BooleanField(default=True)
class Contact(models.Model):
client = models.ForeignKey(Client_Data,blank=True,on_delete=models.CASCADE)
Nom = models.CharField(max_length=50)
post = models.CharField(max_length=50)
Tel = models.CharField(max_length=50)
email = models.EmailField(max_length=255,unique=True)
contact_type = models.CharField(default='Client_contact',max_length=50)
views.py
def save_client_form(request, form,Contact_form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid() and Contact_form.is_valid():
client = form.save()
contact = Contact_form.save(commit=False)
contact.client = client
contact.save()
form.save()
Contact_form.save()
data['form_is_valid'] = True
books = Client_Data.objects.all()
data['html_book_list'] = render_to_string('Client_Section/partial_client_c.html', {
'client': books
})
else:
print(form.errors)
print(Contact_form.errors)
data['form_is_valid'] = False
context = {'form': form,'contact_form':Contact_form}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)
def client_update(request,slug):
book = get_object_or_404(Client_Data, slug=slug)
contact = Contact.objects.select_related().filter(client=book.id)
print(contact)
if request.method == 'POST':
form = ClientForm(request.POST, instance=book)
contact_form = Contact_Form(request.POST, instance=contact)
else:
form = ClientForm(instance=book)
contact_form = Contact_Form(instance=contact)
return save_client_form(request, form,contact_form ,'Client_Section/partial_client_update.html')
If I understand you correctly, you may simply do it this way:
contact = Contact.objects.select_related().filter(client=book.id)
addresse = contact.client.addresse
in you view.py
from django.forms import inlineformset_factory
from django.shortcuts import render, get_object_or_404
def client_update(request, slug):
context = {}
book = get_object_or_404(Client_Data, slug=slug)
formset = inlineformset_factory(Client_Data, Contact, form=Contact_Form )
if request.method == 'POST':
form = ClientForm(request.POST, instance=book)
contactforms = formset(request.POST, prefix='contactformset', instance=book)
context['form'] = form
context['contactforms'] = contactforms
if contactforms.is_valid() and form.is_valid():
form.save()
contactforms.save()
return HttpResponse("your data saved")
else:
return render(request, 'Client_Section/partial_client_update.html', context)
else:
form = ClientForm(instance=book)
contactforms = formset(prefix='contactformset', instance=book)
context['form'] = form
context['contactforms'] = contactforms
return render(request, 'Client_Section/partial_client_update.html', context)
in partial_client_update.html
<form method="POST">
{% csrf_token %}
{{form}}
<hr>
{% formset in contactforms %}
{{formset }}
<hr>
{% endfor %}
<button type="submit ">update</button>
</form>
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.
My View code is this:
#login_required
def DadosUserView(request):
template_name = 'users_c2p/dados.html'
usercpf = request.user.username
profile = UserProfileInfo.objects.filter(cpf_cnpj=usercpf)
contrato_dividas = Contrato.objects.filter(cpf_cnpj=usercpf)
empresa = Empresa.objects.all()
if profile:
person = get_object_or_404(UserProfileInfo, cpf_cnpj=usercpf)
profile_form = UserProfileInfoForm(request.POST or None, instance=person)
flag = 1
else:
profile_form = UserProfileInfoForm(initial={"cpf_cnpj": usercpf,
})
flag = 0
if request.method == 'POST':
profile_form = UserProfileInfoForm(data=request.POST)
print(request.method)
print(profile_form.errors)
if profile_form.is_valid():
# Create new profile
if flag == 0:
profile_form_cpf = profile_form.cleaned_data['cpf_cnpj']
print(profile_form_cpf)
if usercpf == profile_form_cpf:
profile_form.save()
log = LogUsuario.objects.create(cpf_cnpj=profile_form_cpf, movimentacao="FIRST UPDATE")
return redirect(reverse_lazy('users_c2p:dadosuser'))
else:
return profile_form.errors
#Update profile
elif flag == 1:
profile_form_cpf = profile_form.cleaned_data['cpf_cnpj']
if usercpf == profile_form_cpf:
profile_form.save()
log = LogUsuario.objects.create(cpf_cnpj=profile_form_cpf, movimentacao="UPDATE")
return redirect(reverse_lazy('users_c2p:sucesso_cadastro'))
else:
return profile_form.errors
else:
return redirect(reverse_lazy('users_c2p:dadosuser'))
context = {
"UserData" : profile,
"profile_form": profile_form,
"Contrato": contrato_dividas,
"Empresa": empresa,
#'media_url': settings.MEDIA_URL,
}
return render(request, template_name, context)
I want to user the #Update profile part..
The #Create profile is working well, but when I try to update it, it says that user already exists and do nothing.
What should I do, so it recognizes this is the idea and then update the info that I desire?
This piece of code worked out:
def DadosUserView(request):
template_name = 'users_c2p/dados.html'
usercpf = request.user.username
profile = UserProfileInfo.objects.filter(cpf_cnpj=usercpf)
contrato_dividas = Contrato.objects.filter(cpf_cnpj=usercpf)
empresa = Empresa.objects.all()
if profile:
person = get_object_or_404(UserProfileInfo, cpf_cnpj=usercpf)
profile_form = UserProfileInfoForm(request.POST or None, instance=person)
flag = 1
else:
profile_form = UserProfileInfoForm(initial={"cpf_cnpj": usercpf,
}, )
flag = 0
if request.method == 'POST':
# Create new profile
if flag == 0:
profile_form = UserProfileInfoForm(data=request.POST)
print(request.method)
if profile_form.is_valid():
profile_form_cpf = profile_form.cleaned_data['cpf_cnpj']
if usercpf == profile_form_cpf:
profile_form.save()
log = LogUsuario.objects.create(cpf_cnpj=profile_form_cpf, movimentacao="FIRST UPDATE")
return redirect(reverse_lazy('users_c2p:dadosuser'))
else:
return profile_form.errors
#Update profile
elif flag == 1:
print("chegou!")
print(profile_form.errors)
if profile_form.is_valid():
profile_form_cpf = profile_form.cleaned_data['cpf_cnpj']
if usercpf == profile_form_cpf:
profile_form.save()
log = LogUsuario.objects.create(cpf_cnpj=profile_form_cpf, movimentacao="UPDATE")
return redirect(reverse_lazy('users_c2p:sucesso_cadastro'))
else:
return profile_form.errors
else:
return redirect(reverse_lazy('users_c2p:dadosuser'))
context = {
"UserData" : profile,
"profile_form": profile_form,
"Contrato": contrato_dividas,
"Empresa": empresa,
#'media_url': settings.MEDIA_URL,
}
return render(request, template_name, context)
When I was trying to update the database and used this code:
profile_form = UserProfileInfoForm(data=request.POST)
It wouldn't work, I realized that this is when you want to create a new entry, in order to update only, I only had take the data from the form.