I have a situation where I want to remove items from a list. I only have part of the list item, so the typical remove from list isn't working for me since it's not a complete match.
I want to delete all instances of the match, and not just the first match.
I know exactly how many indexes are in the list item; however my search will only contain 3 of the 6 index items.
I'm using Python 3.6
Name of list is DV
This is what I'm trying so far:
c = Brian,Eats,Dinner
if c in DV:
DV.remove(str(Brian,Eats,Dinner))
Sample of the list:
OrderedDict([('Category', 'Random'), ('Date Added', '03-03-2017'), ('Location', ''), ('Name', 'Brian'), ('Activity', 'Eats'), ('Meal', 'Dinner')])
OrderedDict([('Category', 'Random'), ('Date Added', '03-03-2017'), ('Location', ''), ('Name', 'Joe'), ('Activity', 'Runs'), ('Meal', 'Breakfast')])
OrderedDict([('Category', 'Random'), ('Date Added', '03-03-2017'), ('Location', ''), ('Name', 'Brian'), ('Activity', 'Eats'), ('Meal', 'Dinner')])
OrderedDict([('Category', 'Random'), ('Date Added', '03-03-2017'), ('Location', ''), ('Name', 'Brian'), ('Activity', 'Eats'), ('Meal', 'Dinner')])
This doesn't work, because I don't have the complete part, I think.
If I try it with the complete value, it removes it from the list. The problem is that I only know for a fact the value of 3 of the items. The other 3 are irrelevant.
Thanks in advance!
You can create a new list containing only those that don't match all of the specified values.
from collections import OrderedDict
data = [
OrderedDict([('Category', 'Random'), ('Date Added', '03-03-2017'), ('Location', ''),
('Name', 'Brian'), ('Activity', 'Eats'), ('Meal', 'Dinner')]),
OrderedDict([('Category', 'Random'), ('Date Added', '03-03-2017'), ('Location', ''),
('Name', 'Joe'), ('Activity', 'Runs'), ('Meal', 'Breakfast')]),
OrderedDict([('Category', 'Random'), ('Date Added', '03-03-2017'), ('Location', ''),
('Name', 'Brian'), ('Activity', 'Eats'), ('Meal', 'Dinner')]),
OrderedDict([('Category', 'Random'), ('Date Added', '03-03-2017'), ('Location', ''),
('Name', 'Brian'), ('Activity', 'Eats'), ('Meal', 'Dinner')])
]
# tuple of key, value pairs to check
key_values = ('Name', 'Brian'), ('Activity', 'Eats'), ('Meal', 'Dinner')
res = [d for d in data if not all(d.get(k) == v for k, v in key_values)]
If you want to have multiple groups of checks then you can do.
key_values_lst = [
(('Name', 'Brian'), ('Activity', 'Eats'), ('Meal', 'Dinner')),
(('Name', 'Joe'), ('Activity', 'Eats'), ('Meal', 'Breakfast'))
]
res = [d for d in data if not any(all(d.get(k) == v for k, v in key_values)
for key_values in key_values_lst)]
You can also trim down the list using the following instead if you will always use the same keys and want to reduce typing if you have lots of groups.
keys = 'Name', 'Activity', 'Meal'
key_values_lst = [
list(zip(keys, ('Brian', 'Eats', 'Dinner'))),
list(zip(keys, ('Joe', 'Eats', 'Breakfast')))
]
Output
[OrderedDict([('Category', 'Random'),
('Date Added', '03-03-2017'),
('Location', ''),
('Name', 'Joe'),
('Activity', 'Runs'),
('Meal', 'Breakfast')])]
Related
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)
I am trying to add classes to my forms but the classes are not being applied. I cannot find what I'm doing wrong. Any help would be greatly appreciated.
I'm hoping to set bootstrap classes, so I'd like , if possible.
class PersonalInformation(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=200, default='')
surname = models.CharField(max_length=200, default='')
dob = models.DateTimeField('Date of birth (mm/dd/yyyy)', null=True, default=now)
preferred_subjects = models.CharField('Are there subjects you would prefer doing?', max_length=200, default='')
class PersonalInformationForm(forms.ModelForm):
OPTIONS = (
("ANI", "Animals"),
("ART", "Art"),
("COM", "Communication"),
)
preferred_subjects = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(
attrs={
'class' : 'not working',
'id' : 'not working'
}
), choices=OPTIONS)
class Meta:
model = PersonalInformation
fields = ['first_name', 'surname', 'dob', 'preferred_subjects']
widgets = {
'dob': DatePickerInput(
options={
"format": "MM/DD/YYYY",
"showClose": False,
"showClear": False,
"showTodayButton": False,
}
),
}
Thank you.
You can try Updating the form field attributes on initiallization.
class PersonalInformationForm(forms.ModelForm):
OPTIONS = (
("ANI", "Animals"),
("ART", "Art"),
("COM", "Communication"),
)
preferred_subjects = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), choices=OPTIONS)
class Meta:
model = PersonalInformation
fields = ['first_name', 'surname', 'dob', 'preferred_subjects']
widgets = {
'dob': DatePickerInput(
options={
"format": "MM/DD/YYYY",
"showClose": False,
"showClear": False,
"showTodayButton": False,
}
),
}
def __init__(self, request, *args, **kwargs):
super(PersonalInformationForm, self).__init__(*args, **kwargs)
self.fields['preferred_subjects'].widget.attrs.update({'class': 'form-control', 'placeholder': 'First Name'})
EDIT:
preferred_subjects = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), choices=OPTIONS)
preferred_subjects.widget.attrs.update({'class': 'form-control'})
class Meta:
model = PersonalInformation
fields = ['first_name', 'surname', 'dob', 'preferred_subjects']
widgets = {
'dob': DatePickerInput(
options={
"format": "MM/DD/YYYY",
"showClose": False,
"showClear": False,
"showTodayButton": False,
}
),
}
if this doesnt work, consider using 'SelectMultiple' instead of 'CheckboxSelectMultiple'
forms.MultipleChoiceField(widget=forms.SelectMultiple(), choices=OPTIONS)
I want to create multiple forms using single model. Is it possible?
First I made a model including all the fields I need.
models.py
class AcademicsUpto10(models.Model):
PRE_PRIMARY_SUBJECT_CHOICES = (
('Abacus', 'Abacus'),
('Handwriting Basic', 'Handwriting Basic'),
('English Phonetics', 'English Phonetics'),
('English', 'English'),
('KG Academic Class', 'KG Academic Class'),
)
SUBJECT_1TO5_CHOICES = (
('All subjects', 'All subjects'),
('Vedic Maths', 'Vedic Maths'),
('Mathematics', 'Mathematics'),
('Science', 'Science'),
('English', 'English'),
('Hindi', 'Hindi'),
('Environmental Studies', 'Environmental Studies'),
('Mathematics - Science (Combo)', 'Mathematics - Science (Combo)'),
('Handwriting English/Hindi', 'Handwriting English/Hindi'),
)
SUBJECT_6TO10_CHOICES = (
('Mathematics', 'Mathematics'),
('Science', 'Science'),
('Computer Science', 'Computer Science'),
('English', 'English'),
('Social Science', 'Social Science'),
('Sanskrit', 'Sanskrit'),
('Environmental Studies', 'Environmental Studies'),
('French', 'French'),
('German', 'German'),
('Spanish', 'Spanish'),
('Mathematics - Science (Combo)', 'Mathematics - Science (Combo)'),
('Olympiad Maths/Science', 'Olympiad Maths/Science'),
)
BOARD_CHOICES = (
('CBSE', 'CBSE'),
('ICSE', 'ICSE'),
('State Board', 'State Board'),
('International Board', 'International Board'),
)
GENDER_CHOICES = (
('Male', 'Male'),
('Female', 'Female'),
('Flexible to get the best tutor', 'Flexible to get the best tutor'),
)
DAY_CHOICES = (
('Monday', 'Monday'),
('Tuesday', 'Tuesday'),
('Wednesday', 'Wednesday'),
('Thursday', 'Thursday'),
('Friday', 'Friday'),
('Saturday', 'Saturday'),
('Flexible on days to get the best tutor', 'Flexible on days to get the best tutor'),
)
SLOT_CHOICES = (
('Early Morning (6AM-8AM)', 'Early Morning (6AM-8AM)'),
('Morning (8AM-12AM)', 'Morning (8AM-12AM)'),
('Early Afternoon (12PM-3PM)', 'Early Afternoon (12PM-3PM)'),
('Late Afternoon (3PM-5PM)', 'Late Afternoon (3PM-5PM)'),
('Early Evening (5PM-7PM)', 'Early Evening (5PM-7PM)'),
('Late Evening (7PM-10PM)', 'Late Evening (7PM-10PM)'),
)
unique_id = models.UUIDField(default=uuid.uuid4, unique=True)
id = models.AutoField(primary_key=True)
created_at = models.DateTimeField(default=timezone.now)
ticket_size = models.CharField(max_length=30, default=1000, blank=True)
field = models.CharField(max_length=30, blank=True)
standard = models.CharField(max_length=30, blank=True)
pre_primary_subject = MultiSelectField(choices=PRE_PRIMARY_SUBJECT_CHOICES, default='Abacus', blank=False)
subject_1to5 = MultiSelectField(choices=SUBJECT_1TO5_CHOICES, default='All subjects', blank=False)
subject_6to10 = MultiSelectField(choices=SUBJECT_6TO10_CHOICES, default='Mathematics', blank=False)
subject_final = models.CharField(max_length=300, blank = True)
board = models.CharField(max_length=30, choices=BOARD_CHOICES, default='CBSE', blank=True)
day = MultiSelectField(choices=DAY_CHOICES, default='Flexible on days to get the best tutor', blank=False)
slot = MultiSelectField(choices=SLOT_CHOICES, default='Early Morning (6AM-8AM)', blank=False)
gender_preference = models.CharField(max_length=35, choices=GENDER_CHOICES, default='Flexible to get the best tutor', blank=False)
address = models.CharField(max_length=300, blank=True)
plot = models.CharField(max_length=150, blank=False)
street = models.CharField(max_length=150, blank=False)
landmark = models.CharField(max_length=150, blank=True)
name = models.CharField(max_length=150, blank=False)
contact = models.IntegerField(validators=[
MaxValueValidator(9999999999),
MinValueValidator(7000000000)],
blank=False)
email = models.EmailField(max_length=150, blank=False)
def __unicode__(self):
return (self.name)
Then I wrote some forms.py
class AcademicsPrePrimaryForm(forms.ModelForm):
class Meta:
model = AcademicsUpto10
fields = [
'pre_primary_subject', 'day', 'slot', 'gender_preference',
'plot', 'street', 'landmark', 'name', 'contact', 'email'
]
widgets = {
'pre_primary_subject': forms.CheckboxSelectMultiple(attrs={'class': 'for-check-box'}),
'day': forms.CheckboxSelectMultiple(attrs={'class': 'for-check-box'}),
'slot': forms.CheckboxSelectMultiple(attrs={'class': 'for-checkbox'}),
'gender_preference': forms.RadioSelect(),
'plot': forms.TextInput(attrs={'placeholder': 'Plot Number', 'class':'for-field-before'}),
'street': forms.TextInput(attrs={'placeholder': 'Street', 'class': 'for-field-before'}),
'landmark': forms.TextInput(attrs={'placeholder': 'Landmark', 'class': 'for-field-before'}),
'name': forms.TextInput(attrs={'placeholder': 'Name', 'class': 'for-field-before'}),
'contact': forms.TextInput(attrs={'type': 'number', 'placeholder': 'Mobile Number', 'class':'for-field-before'}),
'email': forms.TextInput(attrs={'placeholder': 'Email ID', 'class': 'for-field-before'})
}
class Academics1to5Form(forms.ModelForm):
class Meta:
model = AcademicsUpto10
fields = [
'subject_1to5', 'board', 'day', 'slot', 'gender_preference',
'plot', 'street', 'landmark', 'name', 'contact', 'email'
]
widgets = {
'subject_1to5': forms.CheckboxSelectMultiple(attrs={'class': 'for-check-box'}),
'board': forms.RadioSelect(),
'day': forms.CheckboxSelectMultiple(attrs={'class': 'for-check-box'}),
'slot': forms.CheckboxSelectMultiple(attrs={'class': 'for-checkbox'}),
'gender_preference': forms.RadioSelect(),
'plot': forms.TextInput(attrs={'placeholder': 'Plot Number', 'class':'for-field-before'}),
'street': forms.TextInput(attrs={'placeholder': 'Street', 'class': 'for-field-before'}),
'landmark': forms.TextInput(attrs={'placeholder': 'Landmark', 'class': 'for-field-before'}),
'name': forms.TextInput(attrs={'placeholder': 'Name', 'class': 'for-field-before'}),
'contact': forms.TextInput(attrs={'type': 'number', 'placeholder': 'Mobile Number', 'class':'for-field-before'}),
'email': forms.TextInput(attrs={'placeholder': 'Email ID', 'class': 'for-field-before'})
}
class Academics6to10Form(forms.ModelForm):
class Meta:
model = AcademicsUpto10
fields = [
'subject_6to10', 'board', 'day', 'slot', 'gender_preference',
'plot', 'street', 'landmark', 'name', 'contact', 'email'
]
widgets = {
'subject_6to10': forms.CheckboxSelectMultiple(attrs={'class': 'for-check-box'}),
'board': forms.RadioSelect(),
'day': forms.CheckboxSelectMultiple(attrs={'class': 'for-check-box'}),
'slot': forms.CheckboxSelectMultiple(attrs={'class': 'for-checkbox'}),
'gender_preference': forms.RadioSelect(),
'plot': forms.TextInput(attrs={'placeholder': 'Plot Number', 'class':'for-field-before'}),
'street': forms.TextInput(attrs={'placeholder': 'Street', 'class': 'for-field-before'}),
'landmark': forms.TextInput(attrs={'placeholder': 'Landmark', 'class': 'for-field-before'}),
'name': forms.TextInput(attrs={'placeholder': 'Name', 'class': 'for-field-before'}),
'contact': forms.TextInput(attrs={'type': 'number', 'placeholder': 'Mobile Number', 'class':'for-field-before'}),
'email': forms.TextInput(attrs={'placeholder': 'Email ID', 'class': 'for-field-before'})
}
From here I want to save the subjects in three forms at same place (this subject is to displayed in admin panel), I am not able to figure this out.
Sample view - views.py
def standard8(request):
form = Academics6to10Form(request.POST or None)
if form.is_valid():
form.save(commit=False)
form.save(commit=False).address = request.POST['location']
form.save(commit=False).standard = 'Standard 8'
form.save(commit=False).field = 'Academics'
form.save()
message = "A new query has been added in " + str(form.standard)
message += "Name: " + str(form.name)
message += "Mobile Number: " + str(form.contact)
send_mail(emailSubject, message, emailFrom, emailList, fail_silently=False)
return render(request, 'thanks.html')
else:
return render(request, 'allForms/acadsstandard8.html', {'form': form})
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.
I'm trying to change the default ManyToManyField widget into a TextInput and make it readonly. At the same time I'm trying to display the value(s) that the ManyToManyField used to have within the TextInput, but I can't seem to manage...these are my models:
Form
class ParticipantInlineForm(forms.ModelForm):
class Meta:
model = Participant
widgets = {
'persons': forms.TextInput
}
def __init__(self, *args, **kwargs):
super(ParticipantInlineForm, self).__init__(*args,**kwargs)
instance = kwargs.get('instance')
string = ''
if instance:
for person in instance.persons.all():
string = string + str(person)
self.fields['persons'].initial = string
Inline
class SimpleParticipantInline(admin.TabularInline):
model = Participant
extra = 0
fields = ( 'persons',)
form = ParticipantInlineForm
def has_delete_permission(self, request, obj=None):
return False
def has_add_permission(self, request, obj=None):
return False
Models
class Person(models.Model):
name = models.CharField(max_length=25, default='', verbose_name='Nombre')
lastname = models.CharField(max_length=25, default='', verbose_name='Apellido')
phone = models.CharField(max_length=30, default='', verbose_name='Telefono')
email = models.CharField(max_length=30, default='', verbose_name='Email')
def __str__(self):
return self.name + ' ' + self.lastname
class Meta:
verbose_name = "Persona"
verbose_name_plural = "Personas"
class Participant(models.Model):
persons = models.ManyToManyField(Person)
tournament = models.ForeignKey(Tournament, default='', verbose_name='Torneo')
TEAM_NUMBER_CHOICES = (
('1', 'Equipo 1'),
('2', 'Equipo 2'),
('3', 'Equipo 3'),
('4', 'Equipo 4'),
('5', 'Equipo 5'),
('6', 'Equipo 6'),
('7', 'Equipo 7'),
('8', 'Equipo 8'),
('9', 'Equipo 9'),
)
team_number = models.CharField(max_length=2, verbose_name='Numero de Equipo', choices=TEAM_NUMBER_CHOICES, default='', blank=True)
TEAM_FORMAT_CHOICES = (
('Singles 1', 'Singles 1'),
('Doubles 1', 'Doubles 1'),
('Singles 2', 'Singles 2'),
('Doubles 2', 'Doubles 2'),
('Singles 3', 'Singles 3'),
('Doubles 3', 'Doubles 3'),
('Singles 4', 'Singles 4'),
('Doubles 4', 'Doubles 4'),
('Singles 5', 'Singles 5'),
('Doubles 5', 'Doubles 5'),
('Singles 6', 'Singles 6'),
('Doubles 6', 'Doubles 6'),
)
team_format = models.CharField(max_length=9, verbose_name='Formato de Equipo', choices=TEAM_FORMAT_CHOICES, default='', blank=True)
def __str__(self):
string = ''
if self.team_number and self.team_format:
string = 'Equipo ' + self.team_number + ' ' + self.team_format
else:
for person in self.persons.all():
string = string + person.__str__() + ' '
return string
class Meta:
verbose_name = "Participante"
verbose_name_plural = "Participantes"
I changed the widget using this code, but the values are wrong.
It's showing integers like 1L, 2L, 3L. I think they might be the id's...
I have also tried redefining the widget, but old ManyToManyField objects won't get there and I can't set the initial values, any help?
I just want to show the string representation of each object in the ManyToManyField as a readonly field within the Inline.
Thanks in advance!
I know the question is 2 years old but trying to answer for others who are looking for something similar.
You can use a widget similar to ManyToManyField, SelectMultiple but just mark it as readonly and disabled. Marking these as disabled or readonly within __init__ in forms may not work. It should be done as part of Meta widgets sections.
class ParticipantInlineForm(forms.ModelForm):
class Meta:
model = Participant
widgets = {
'persons': forms.SelectMultiple(attrs={'readonly': 'True', 'disabled': 'True'})
}
Make sure __str__ has been implemented to a meaningful text in Persons class
Since it is disabled and marked as readonly, the value cannot be changed but it displays proper string values.