Django: how to use the checkbox in the admin - django

I try to display the values of checkbox in my view but It's not working..
forms.py
class JoursForm(forms.ModelForm):
class Meta:
model = Event
JOURS = (
(1, 'L'),
(2, 'M'),
(3, 'M'),
(4, 'J'),
(5, 'V'),
)
jours = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
choices=JOURS, label= u"répéter les :")
def clean_my_field(self):
return self.cleaned_data['jours']
admin.py
class EventAdmin(admin.ModelAdmin):
form = JoursForm
save_on_top = True
save_as = True
list_per_page = 25
list_display = ('title', 'start', 'end', 'user', 'fin', 'frequency')
fieldsets = (
(None, {
'fields': ('title','start', 'end', 'is_cancelled', 'calendar', 'user', 'description', ('frequency', 'fin' ), 'activated', 'jours',)
}),
)
views.py
if request.method == 'POST':
form = JoursForm(request.POST)
if form.is_valid():
jours = form.cleaned_data.get('jours')
print 'jours', jours
else:
form = JoursForm
I would like to use the values of checkbox but when I save in admin after having tick the boxes, they remain unchecked.
What to do?

Your jours selection is not saved anywhere - there is no modelfield to save it.
To make this work you can create a model for your jours
class Jour(models.Model):
abbrev = models.CharField(length="1")
and add your weekdays in there.
Then you add a field to your Event model:
jours=models.ManyToManyField(Jour)
Then you can just change your form to:
class JoursForm(forms.ModelForm):
class Meta:
model = Event
jours = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,
queryset=Jour.objects.all(), label= u"répéter les :")
However, I am not sure if that is what you want to achieve.

Related

Create view with more models

hi everyone I have a doubt with the use of forms and models.
I have to create a code that creates records in multiple tables and I don't know how to do it.
my goal is to create a page where I can enter all the data and when I save it creates the various tables filled in with the data provided by the user.
I'm a beginner I still have to learn the mechanism well =)
forms.py
from django import forms
from .models import Schede, DatiGruppi, Gruppi
class CreaSchedaForm(forms.ModelForm):
nome_scheda = forms.CharField(
required = True,
label ='Nome scheda',
widget = forms.TextInput(
attrs = {
'class': 'form-control',
'placeholder' : 'nome scheda',
'autocomplete' : 'off'
}
)
)
data_inizio = forms.DateField(
label='Data inizio',
widget = forms.DateInput(
attrs= {
'type': 'date',
'class': 'form-control',
'placeholder' : 'data inizio'
}
)
)
data_fine = forms.DateField(
label='Data fine',
widget = forms.DateInput(
attrs= {
'type': 'date',
'class': 'form-control',
'placeholder' : 'data fine'
}
)
)
class Meta:
model = Schede
fields = ['nome_scheda','data_inizio','data_fine']
class CreaDtGruppoForm(forms.ModelForm):
giorni_settimana = forms.ChoiceField(
choices = DatiGruppi.giorni_settimana_scelta
)
dati_gruppo = forms.ModelChoiceField(
queryset = Gruppi.objects.all(),
empty_label = "-",
required = True
)
class Meta:
model = DatiGruppi
fields = ['giorni_settimana', 'dati_gruppo']
views.py
#login_required
def creaScheda(request):
if request.method == "POST":
form = CreaSchedaForm(request.POST)
if form.is_valid():
scheda = form.save(commit = False)
scheda.utente = request.user
scheda.save()
else:
form = CreaSchedaForm()
context = {"form": form}
return render(request, "crea_scheda.html", context)

how to get only the 'title' attribute value from following data in django

This is the views.py I want to get 'title' attribute from the serialize data
views.py
class CalculatView(views.APIView):
query = CartProduct.objects.latest('id')
serializer = CartProductSerializer(query)
choose_product = serializer.data.get('product')
[sell_id] = choose_product
querye = Product.objects.filter(id = sell_id)
serializere = ProductSerializers(querye, many=True)
choosee = serializere.data
print(choosee)
output :
[OrderedDict([('id', 2), ('title', 'Frock'), ('date', '2021-04-22'), ('image', '/media/products/kids2.jpg'), ('marcket_price', 1.2), ('selling_price', 1.2), ('description', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaa'), ('category', OrderedDict([('id', 2), ('title', 'Fashion'), ('date', '2021-04-22')])), ('seller', OrderedDict([('id', 2), ('seller_name', 'CIB - Piliyandala'), ('lat', 6.8018), ('lng', 79.9227), ('date', '2021-04-22')]))])]
Try this.
title = choosee[0].get('title')
print (title)

Dynamic required fields according to user's selection in Django form

I would like to make two fields (repertoire and performer) required only if the user selects and submits a type="performance". This is my model:
class Event(models.Model):
EV_TYPE = (
('performance', 'performance'),
('other', 'other'),
)
title = models.CharField(max_length=200)
type = models.CharField(max_length=15, choices=EV_TYPE, default="performance")
repertoire = models.ManyToManyField(Work, blank=True)
performer = models.ManyToManyField(Profile, limit_choices_to={'role__type__contains': 'Performer'})
My form:
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = [
'type',
'submitted_by',
'title',
'repertoire',
]
My view:
def event_create_view(request):
if request.method == 'POST':
form_event = EventForm(
request.POST,
repertoire_required=(not (active_user.id == 17)), # if the user is NMS then the repertoire field is not compulsory
initial={'submitted_by' : active_user.profile.id}
)
form_venue = AddVenueForm()
form_profile = ProfileForm()
form_work = WorkFromEventForm()
if form_event.is_valid():
this_event = form_event.save()
return redirect('event-edit', id=this_event.id)
This is what I tried. In the above 'form_event.is_valid', I did:
if form_event.is_valid():
this_event = form_event.save(commit=False)
if this_event['type'] == 'performance' and this_event['performer'] and this_event['repertoire']:
this_event.save()
return redirect('event-edit', id=this_event.id)
This doesn't work though (I still get a 'this field is required' when I submit). How can I achieve what I want to do?
Addendum
This is also not working:
if
this_event['type'] == 'performance' and not this_event['performer'] or not this_event['repertoire']:
messages.error(request, form_event.errors)
else:
this_event.save()
You do that with a clean method on the form.
For example you might do;
def clean(self):
"""
Validate the form input
"""
cleaned_data = super().clean()
type = cleaned_data.get('type')
if type == 'performance':
repertoire = cleaned_data.get('repertoire')
performer = cleaned_data.get('performer')
if not repertoire:
self.add_error('repertoire', _("This field is required"))
if not performer:
self.add_error('performer', _("This field is required"))
return cleaned_data
The docs for form validation are here; https://docs.djangoproject.com/en/3.1/ref/forms/validation/

AttributeError: 'ModelFormOptions' object has no attribute 'private_fields'

I get this error when trying to create a custom Form on the Admin view, I don't see any solution on stackoverflow (yes similar problems) so I think it's a good idea to post it:
My Models.py:
class Webhook(models.Model):
url = models.CharField('URL', max_length = 60, unique = True)
description = models.CharField('Descripcion', max_length = 255)
enabled = models.BooleanField('Enabled', default=True)
event = models.CharField('Evento', max_length=1, choices=Events.EVENTS_CHOICES)
My Forms:
class WebhookForm(forms.ModelForm):
class Meta:
model = Webhook
fields = '__all__'
def save(self, commit=True):
print('saveeeeeee')
webhook = super().save(commit=False)
webhook.code = webhook.id
# Get token
response_token = TOKEN.get()
if response_token['success']:
# Create Webhook
url = 'https://sandbox.bind.com.ar/v1/webhooks'
headers = {
'Content-type': 'application/json',
'Authorization': 'JWT ' + response_token['token']
}
data = {
'url': webhook.url, # Debera responder status_code == 200
'description': webhook.description,
'code': webhook.id,
'enabled': webhook.enabled,
'events': webhook.event
}
data_json = json.dumps(data)
response = requests.put(url, data= data_json, headers = headers)
response_json = response.json()
# Result
result = {}
if response.status_code == 409:
result['success'] = False
result['details'] = response_json
else:
result['success'] = True
result['data'] = response_json
# If ok, Save
if commit & result['success']:
webhook.save()
return result['success']
My Admin.py
class WebhookAdmin(forms.ModelForm): # Only to override a form in admin
class Meta:
model = WebhookForm
fields = '__all__'
# Style to add a new User
add_form = WebhookForm
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('url', 'description', 'code', 'enabled', 'events',)}
),
)
# Style to edit a new User
form = WebhookForm
fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('url', 'description', 'code', 'enabled', 'events',)}
),
)
admin.site.register(Webhook, WebhookAdmin)
And I get this error when I try to do python manage.py makemigrations:
AttributeError: 'ModelFormOptions' object has no attribute 'private_fields'
You have subclassed the wrong thing. The admin class needs to inherit from admin.ModelAdmin, not forms.ModelForm.
ModelAdmin classes don't have an inner Meta class. You need to remove that class altogether.
The Attribute error was because I was trying to assign a Form into the class Meta, and it needs a Model:
class Meta:
model = WebhookForm
fields = '__all__'

How do I fix an issue with django's modelform saving?

I'd like to be able to save data submitted by the form based on an argument passed via the url that references the product (instead of having the user to specify the product through a dropdown). Any thoughts on how I can accomplish this?
url(r'^products/(?P<product_id>\d+)/reviews/$', 'view_reviews'),
url(r'^products/(?P<product_id>\d+)/add_review/$', 'add_review'),
def add_review(request, product_id):
p = get_object_or_404(Productbackup, pk=product_id)
if request.method == 'POST':
form = ReviewbackupForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('reserve.views.view_reviews', kwargs={'product_id':p.id}))
else:
form = ReviewbackupForm()
variables = RequestContext(request, {'form': form, 'product_id': product_id})
return render_to_response('reserve/templates/create_review.html', variables)
RATING_OPTIONS = (
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
(5, '5'),
(6, '6'),
(7, '7'),
(8, '8'),
(9, '9'),
(10, '10'),
)
class Reviewbackup(models.Model):
review = models.CharField('Review', max_length = 2000)
date = models.DateField('date')
created_on = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
user = models.CharField('Username', max_length = 200)
rating = models.IntegerField(max_length=2, choices=RATING_OPTIONS)
product = models.ForeignKey(Productbackup)
def __unicode__(self):
return self.review
class ReviewbackupForm(ModelForm):
class Meta:
model = Reviewbackup
fields = ('review', 'rating', 'user', 'date')
widgets = {
'review': Textarea(attrs={'cols': 80, 'rows': 7}),
}
class Productbackup(models.Model):
website = models.CharField('Product name', max_length = 200)
website_url = models.URLField('Product URL')
category = models.ForeignKey(Categories)
created_on = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
def __unicode__(self):
return self.website
You can make use of form.save(commit=False), and set other attributes of your model in the instance and save it again.
In your view, when you save the form:
if form.is_valid():
review = form.save(commit=False)
review.product = p
review.save()