update a field in all records of a table through a single form Django 4 - python-3.x

I have the following model 'ARTICULO', which I have created and templates to edit it individually
# MODEL
class Articulo(models.Model):
id = models.AutoField(primary_key=True, verbose_name='codigo')
nombre = models.CharField(max_length=100, verbose_name='nombre elemento')
cantidad = models.PositiveSmallIntegerField(verbose_name='cantidad total')
cantidad_disponible = models.PositiveSmallIntegerField(verbose_name='cantidad disponible', default=5)
UNIDAD = 'und'
KILO = 'kg'
LITRO = 'L'
UNIDADES_BASE = [
(UNIDAD, 'unidades'),
(KILO, 'Kilogramos'),
(LITRO, 'litros'),
]
unidades = models.CharField(max_length=3, choices=UNIDADES_BASE, default=UNIDAD, verbose_name='unidad base')
area = models.CharField(max_length=100, verbose_name='tipo inventario', default='primaria')
persona_asignada = models.CharField(max_length=100, default='almacen', verbose_name='persona asignada')
def __str__(self):
trama = "articulo: " + self.nombre
return trama
#form to edit individually
class ArticuloEditarForm(forms.ModelForm):
class Meta:
model = Articulo
fields = ['nombre', 'cantidad', 'unidades']
# view for generate form of individual article
def editar(request, id):
articulo = Articulo.objects.get(id=id)
formulario = ArticuloEditarForm(request.POST or None, instance=articulo)
if formulario.is_valid() and request.POST:
formulario.save()
return redirect('inventario_inicio')
return render(request, 'inventario/editar.html', {'formulario': formulario})
but additionally I would like to create a page where I can perform an update of all the records of the table as a whole (as in the following image)
When clicking on the button, all records with the checkbox activated are updated in the database according to the value indicated in their text box.
From what I have investigated so far, I think I understand that I should use the form.Form class and not form.ModelForm in combination with formsets, but in the attempts I have made, I tried trying to define a form in this way, but it does not work for me.
class AsignarReservasArticulos(forms.Form):
articulos = Articulo.objects.all()
for x in articulos:
print(x)
participa = forms.BooleanField(label='')
My deduction tells me that I must generate the form that I show in my image in an integral way from my FORM or I must make a part in the form and another in the view.

Related

Showing Field Data On Another View

Thank You, trying to show the created_date field to the front table but i get an error, if i don't filter and use the all() method i am able to populate all the field data, but i would like to populate created_date field of member.I Get KEY ERROR "list_id"
class ListListView(ListView):
model = HBTYList
template_name = "accounts/modals/nomodal/index.html"
paginate_by = 3
def get_queryset(self):
qs = self.model.objects.all().order_by('-id')
p_f = HbtyCustomerListFilter(self.request.GET, queryset=qs)
return p_f.qs
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['dc'] = HBTYItem.objects.filter(hbty_cust_id=self.kwargs["list_id"]) #Fix this method to show created_data
context['filter'] = HbtyCustomerListFilter(self.request.GET, queryset=self.get_queryset())
return context

How to insert data to my DB when using another model's field in my form?

I have two different models: Trainer and User. I'm pulling in the trainer_price field from Trainer into my form in User. Please note that I'm also not using a foreign key.
The problem I'm having is that the trainer_price is not getting inserted and the default value of 0 is there, which is not what I want.
The way the User form works is they fill out their name, address, email and the trainer_price is automatically populated once they selected a trainer. It's also a read-only field.
Here's what I've tried so far:
user views.py
def buyer(request):
user_form = UserForm()
trainer_listing = Trainer.objects.get(id=15).trainer_price
context = {'user_form':user_form, 'trainer_listing':trainer_listing}
if request.method == "POST":
user_form = UserForm(request.POST)
if user_form.is_valid():
user_form.save()
return redirect("/success_page")
return render(request, "user/user_form.html", context)
forms.py
class UserForm(forms.ModelForm):
Fullname = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'John Doe'}))
Email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Email'}))
Mobile = forms.CharField(widget=forms.TextInput(attrs={'placeholder': '312-222-2222'}))
Address = forms.CharField(widget=forms.TextInput(attrs={'placeholder': '1234 Main St'}))
City = forms.CharField()
State = forms.ChoiceField(choices=STATES)
zipcode = forms.CharField()
trainer_price = forms.DecimalField(label="Trainer Price", required=False, widget=forms.TextInput(attrs={'readonly':'readonly'}))
class Meta:
model = User
fields = ['Fullname','Email', 'Mobile', 'Address', 'City',
'State', 'zipcode', 'trainer_price']
Any help in the right direction would be great!
Basically, we can set default values for the form field using the initial argument.
def buyer(request):
trainer = Trainer.objects.get(id=15)
user_form = UserForm(initial={"trainer_price": trainer.trainer_price})
# etc
PS. Make sure that you do not populate the value from the trainer_price with the results from the request.POST. Smart users could use this to get very cheap deals. In stead, always re-query the actual value.

How to show select field with pre-selected data using django forms?

I've a django Form with 2 choices (yes and no), on my "create page" i can render the select field to save the data and it works just fine, when i try to use on the "edit page" the value is not pre-selected with the current value, how can i make the current value selected on the select input field?
The form:
class MyForm(forms.ModelForm):
choose = forms.BooleanField(
required=False,
widget=forms.Select(
choices=[(1, 'Yes'), (0, 'No')],
attrs={'class': 'form-control'}
)
)
class Meta:
model = MyModel
When i call the view to edit:
class MyUpdateView(
LoginRequiredMixin,
SuccessMessageMixin,
UpdateView,
):
model = MyModel
form_class = MyForm
template_name = "my/template.html"
success_url = reverse_lazy('my-url')
success_message = 'Updated!'
def get_object(self, queryset=None):
data = super(MyUpdateView, self).get_object()
if not data.user == self.request.user:
raise Http404
# data.choose is False
return data
The HTML input will be always "1" (Yes) even tough the current value is "0" (No)
The HTML:
{{ form.choose }}
The Model:
class MyModel(models.Model):
choose = models.BooleanField(
default=False,
verbose_name='Cumulativo'
)
add this to your MyUpdateView:
initial = { 'choose': 1 }
You are defining the custom field 'choose' in the form, which does not refer to MyModel field 'choose'. that's why you are always getting the first value 'Y' as default or the first value 'Y' in the dropdown.
If you want to refer to your model object, you can simply use self keyword in the form
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['choose'].widget.attrs['class'] = 'form-control'
class Meta:
model = MyModel
fields = ('__all__')

How to Export Foreign Key Field to Excel In Django Views.py?

Getting this Error:- 'Restaurant' object has no attribute 'menu_here__starters'
I'm using Django-Excel Lib
In My Models.py
Class Restaurant(models.Model):
name = models.CharField(max_length=20)
area = models.CharField(max_length = 30)
menu_here = models.ForeignKey(Menu)
Class Menu(models.Model):
starters = models.CharField(max_length = 50)
desserts = models.CharField(max_length = 50)
In my Views.py
def download_excel_4(request):
query_set = Restaurant.objects.all() # Foreign column is Menu
column_names = ['menu_here__starters','menu_here__desserts' ]
return excel.make_response_from_query_sets(
query_set,
column_names,
'xls',
file_name="Restaurant With Complete Menu Database"
)
The make_response_from_query_sets takes the objects returned by query_set and displays it along with column names which should correspond with the field names of the objects.
The column_names acts like a filter displaying only the field names you want but it cannot further query after the objects are got. Therefore valid names are ['name', 'area', 'menu_here'].
An alternative would be to get objects as a dict with the related fields while querying using the .values() method and then using excel.make_response_from_records.
query_record = Restaurant.objects.all().values('name', 'area', 'menu_here__starters', 'menu_here__desserts')
return excel.make_response_from_records(
query_record,
'xls',
file_name="Restaurant With Complete Menu Database"
)

Django Haystack return related insances

Hi I´m using django with haystack search. I have one model for Events. Thats the model I'm doing the search on. I have a second model to count the hits/views for the Events. I wan't to return the number of hits for every event additional to the search results.
my view:
def event_search(request):
if request.method == 'POST':
query = str(request.POST['search'])
events = SearchQuerySet().auto_query(query).models(Event).order_by('date')
return render_to_response('event_search.html', {"events": events}, context_instance=RequestContext(request))
else:
return render_to_response('event_search.html', context_instance=RequestContext(request))
my models:
class Event(models.Model):
name = models.CharField(max_length = 70)
date = models.DateTimeField()
description = models.TextField()
active = models.BooleanField(default=True, editable=False)
featured = models.BooleanField(default=False)
class EventHitcount(models.Model):
hit = models.ForeignKey(Event)
ip = models.CharField(max_length=40)
session = models.CharField(max_length=40)
created = models.DateTimeField(default=datetime.datetime.now())
By giving the ForeignKey field a related name it can call and count the related objects.
class Foo(models.Model):
fk = models.ForeignKey(Event,related_name='foofk')
some more fields...
In the template:
{{ foo.foofk.count }}

Resources