In my project i am using Django 1.11.10 and postgresql for database. When someone enters data to 'order_id' field i want to send it a item_barcode column whether its first 2 character is letters. How can I do that?
models.py
from django.db import models
class Customer(models.Model):
item_barcode = models.TextField(max_length=50,unique=True,null=True)
order_id = models.TextField(max_length=50,unique=True,null=True)
full_name = models.TextField(max_length=50)
company = models.TextField(max_length=60,blank=True)
email = models.EmailField(max_length=40)
phone_number = models.TextField(max_length=17)
note = models.TextField(max_length=256,blank=True)
def __str__(self):
return self.order_id
forms.py
class CustomerForm(forms.ModelForm):
class Meta:
model = Customer
fields = (
'order_id','full_name','company','email',
'phone_number','note')
views.py
def guaform(request):
form = CustomerForm()
if request.method == "POST":
form = CustomerForm(request.POST)
if form.is_valid():
form.save(commit=True)
else:
HttpResponse("Error from invalid")
return render(request,'customer_form.html',{'form':form})
*My database columns is same of the models.py
You can do some work after validating the form.
if form.is_valid():
#test to see if first two characters are letters
first_two_characters = form.cleaned_data['order_id'][0:2]
if first_two_characters.isAlpha():
#get an instance of the object without saving to db
form_uncommitted = form.save(commit=False)
#set the item_barcode field and only then save to db
form.uncommitted.item_barcode = form.cleaned_data['order_id'] #or what you want it to be
form_uncommitted.order_id = None
form_uncommitted.save
else:
#it's not a barcode so we can just save
form.save()
I'm doing a edit form for some data. I'm having problem to pass information to . As you can see in my view, I pass the data to form using "initial" dictionary.
VIEWS.PY
#login_required
def project_detail(request, project_id):
if request.method == 'POST':
project = get_object_or_404(Project, pk=project_id)
form = ProjectDetailForm(project_id, request.POST, instance = project)
if form.is_valid():
instance = form.save(commit=False)
instance.client = Project.objects.get(pk=project_id).client
form.save()
messages.success(request,'Projeto modificado')
return redirect('projects')
else:
messages.error(request,'Ocorreu um erro!')
else:
project = get_object_or_404(Project, pk=project_id)
form = ProjectDetailForm(project_id, initial={'modal':project.modal,
'culture':project.culture,
'owner':project.owner,
'value':project.value,
'final_date':project.final_date,
'text':project.text,
'status':project.status,
'farm':project.farm.values()})
return render(request,'project_detail.html',{'form':form})
But doing this, the data is not displaied in . Thinking here, ManyToManyField saves data in lists. I tried iterate this field but still not working and I guess thats not the best way to do this.
MODELS.PY
class Project(models.Model):
modal_types = [('CUSTEIO AGRÍCOLA','Custeio Agrícola'),('CUSTEIO PECUÁRIO','Custeio Pecuário'),('INVESTIMENTO AGRÍCOLA','Investimento Agrícola'),('INVESTIMENTO PECUÁRIO','Investimento Pecuário'),('FGPP','FGPP')]
status_opts = [('Análise','Análise'),('Desenvolvimento','Desenvolvimento'),('Processamento','Processamento'),('Liberação','Liberação'),('Finalizado','Finalizado'),('Cancelado','Cancelado'),('Suspenso','Suspenso')]
farm = models.ManyToManyField(Farm, related_name='farm_name',verbose_name='Propriedade beneficiada')
client = models.ForeignKey(Clients, on_delete=models.CASCADE, related_name='project_client',default=None,null=True, verbose_name='Cliente')
owner = models.ForeignKey(Owner, on_delete=models.CASCADE, related_name='project_bidder',default=None,null=True, verbose_name='Proponente')
warranty = models.ManyToManyField(Farm, related_name='project_warranty',default=None, verbose_name='Propriedade de garantia')
modal = models.CharField(max_length=100,default=None,choices=modal_types, null=True, verbose_name='Tipo')
culture = models.CharField(max_length=50,null=True, verbose_name='Cultura')
status = models.CharField(max_length=50,null=True, verbose_name='Status', choices=status_opts)
created_date = models.DateField(null=True, verbose_name='Data de criação')
value = models.FloatField(max_length=10,null=True, verbose_name='Valor financiado')
final_date = models.DateField(default=None,null=True, verbose_name='Fim do contrato')
text = models.TextField(default=None,null=True, verbose_name='Observações')
forms.py
class ProjectDetailForm(ModelForm):
class Meta:
model = Project
fields = ['status','owner', 'farm', 'warranty', 'modal', 'culture', 'value','final_date','text']
def __init__(self, project_id, *args, **kwargs):
client_id = Project.objects.get(pk=project_id).client
super(ProjectDetailForm,self).__init__(*args,**kwargs)
self.fields['value'].required = False
self.fields['final_date'].required = False
self.fields['text'].required = False
self.fields['farm'].queryset = Farm.objects.filter(client=client_id)
self.fields['warranty'].queryset = Farm.objects.filter(client=client_id)
for field_name, field in self.fields.items():
field.widget.attrs['class'] = 'form-control'
Here all the fields with information, but in "select" nothing is selected, despite having data in the database
Someone can help me?
Why are you passing 'project_id' into your form class instance? Try changing this:
form = ProjectDetailForm(project_id, request.POST, instance = project)
to this:
form = ProjectDetailForm(request.POST, instance = project)
and see if it helps. Also in your form initialization, I'm not sure you're using the "initial=" values dictionary correctly. Initial values are typically defaults applicable to the "create" view, not database records that it sounds like you want to see in an update view. I think you want to pass in the instance of your database record there, something like:
else:
project = get_object_or_404(Project, pk=project_id)
form = ProjectDetailForm(instance=project)
Also, you really don't need to write project object query twice in this view. You can do something like:
def project_detail(request, project_id):
project = get_object_or_404(Project, pk=project_id) # query this once here
if request.method == 'POST':
form = ProjectDetailForm(request.POST, instance=project)
if form.is_valid():
instance = form.save(commit=False)
instance.client = Project.objects.get(pk=project_id).client
form.save()
messages.success(request,'Projeto modificado')
return redirect('projects')
else:
messages.error(request,'Ocorreu um erro!')
# you probably want a redirect here as well
else:
form = ProjectDetailForm(instance=project)
return render(request,'project_detail.html',{'form':form})
Finally, if you're trying to limit the choices from your ManyToMany field in the user's form, you can do so with something like this:
class ProjectDetailForm(forms.ModelForm):
class Meta:
model = YourModelName
fields = ['farm']
farm = forms.ModelMultipleChoiceField(
queryset=Farm.objects.filter(some_field=some_criteria).order_by('some_field'),
widget=forms.CheckboxSelectMultiple)
More info about widgets on form classes here in Django docs.
I'm building a small web service for inventory control. As part of this, I want to populate a detail view for any of the inventory items. This is what I have so far for that:
class Product_Update(forms.Form):
Product_Code = forms.CharField(
max_length=10,
attrs={"placeholder = <ID here> Readonly = True"
)
Name = forms.CharField(max_length=100)
Description = forms.Textarea(attrs={"Rows": 3})
price = forms.DecimalField()
mini = forms.IntegerField()
Max = forms.IntegerField()
How do I pass the form the parameters?
You should use a ModelForm instead:
class ProductUpdate(forms.Form):
class Meta:
model = Product
fields = ('product_code', 'name', 'description', 'price', 'mini', 'max')
Now you can easily pass a model instance to your form:
def some_view(request):
instance = Product.objects.first()
form = ProductUpdate(request.POST or None, instance=instance)
context = {'form':form}
return render(request, 'some_template.html', context)
If you want to show multiple products in the same form, you will need to use modelformset_factory:
from django import forms
ProductFormSet = forms.modelformset_factory(Product, form=ProductUpdate, extra=0)
Now in your views.py, you can pass a QuerySet to your form:
def some_view(request):
queryset = Product.objects.all()
form = ProductFormSet(request.POST or None, queryset=queryset)
if request.method == 'POST' and form.is_valid():
form.save()
context = {'form':form}
return render(request, 'some_template.html', context)
You can access the form's data in the view by accessing request.POST
def actionView(request, product_id):
product = Product.objects.get(id=product_id)
form = ProductUpdate(request.POST, instance=product_id)
form.save(commit=False) #Do this if you want to make changes to some value
form.price = 112233
updated_form = form.save()
It sound simple but I want my page to display the database of my model.
I use ModelForm for user to input and it would save into my model. Now I want to render the whole table, not just each separately.
forms.py
class My_Folio(forms.ModelForm):
class Meta:
model = my_data
fields = ['symbol','buy_price','quantity']
views.py
def blockfolio(request):
if request.method == 'POST':
my_folio = My_Folio(request.POST)
if my_folio.is_valid():
symbol = my_folio.cleaned_data['symbol']
buy_price = my_folio.cleaned_data['buy_price']
quantity = my_folio.cleaned_data['quantity']
instance = my_folio.save(commit=False)
instance.save()
return render(request, 'blockfolio/blockfolio.html', {'symbol':symbol, 'buy_price':buy_price, 'quantity':quantity, 'instance':instance})
template:
{{instance}} This give me the user input after submit, but I want to show all of the inputs saved in database.
Maybe your post is invalid. Try this code in views.py.
def blockfolio(request):
if request.method == 'POST':
my_folio = My_Folio(request.POST)
if my_folio.is_valid():
symbol = my_folio.cleaned_data['symbol']
buy_price = my_folio.cleaned_data['buy_price']
quantity = my_folio.cleaned_data['quantity']
instance = my_folio.save(commit=False)
instance.save()
return render(request, 'blockfolio/blockfolio.html', {'symbol':symbol, 'buy_price':buy_price, 'quantity':quantity, 'instance':instance})
else:
print("request is invalid: {}".format(request.POST))
return "bad request!", 500
hallo i want to create data with checkbox field but data cannot save in database when i use widget RadioSelect
this is forms.py
class VehicleAttribute(forms.ModelForm):
OPERATION = [('production','Production Vehicle'),('supporting','Supporting Vehicle')]
PAYLOAD_METER = [('yes','Yes'),('no','No')]
NUMBER_STRUT = [('0','0'),('3','3'),('4','4')]
operation = forms.ChoiceField(widget=forms.RadioSelect, choices = OPERATION)
payload_meter = forms.ChoiceField(widget=forms.RadioSelect, choices = PAYLOAD_METER)
number_of_strut_pressure = forms.ChoiceField(widget=forms.RadioSelect, choices = NUMBER_STRUT)
class Meta:
model = Vehicle_attribute
fields = ['operation','payload_meter','number_of_strut_pressure']
this is views.py
def data_vehicle_add(request):
if request.method == "POST":
form = VehicleAttribute(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('data_vehicle_add.html', pk=post.pk)
else:
form = VehicleAttribute()
return render(request,'data_vehicle_add.html', {'form':form}, context_instance=RequestContext(request))
can you help me solve this problem?