How do I set a field named by a string? - django

For a view that updates a model, I'd like to do something like this:
for field in ('name', 'parent', 'notes'):
if request.POST[field]:
myModel[field] = request.POST.get(field, '')
However, model's fields are accessed as properties (myModel.field), not dictionary items, and as far as I can tell there aren't get/set methods in Django models. Is there another way I can update these properties iteratively?

setattr()

Related

How to test CheckboxSelectMultiple in save

I have a form (ModelForm) in Django, where I am adding a field for users in the init method as so:
self.fields["users"] = forms.ModelMultipleChoiceField(
queryset=users, widget=forms.CheckboxSelectMultiple, required=False,label="Add Designer(s)"
)
In the save method how I can iterate over the queryset for this field, however, I do not know how I can test if the particular model has been selected/checked. Help, please.
EDIT:
Let's say that you have a form where you want to be able to add users to a certain project, I set the users field as above (also usedMultipleChoiceField) but my real question is how do you determine the state of those checkboxes (which users should be added)?
Managed to fix it using MultipleChoiceField instead of ModelMultipleChoiceField. Then populated the choices with existing event IDs and passed it to the template.
In forms:
choices = forms.MultipleChoiceField(widget = forms.CheckboxSelectMultiple())
In views:
form.fields['choices'].choices = [(x.eventID, "Event ID: " + x.eventID) for x in unapproved]
Had to change some of the logic for finding and editing Event objects too.
The Django documentation states that a ModelMultipleChoiceField normalizes to a QuerySet of model instances. That means in your example, it will only return the users that have been checked. If none have been checked, it will return an empty QuerySet.
If you are overriding your ModelForm save method, you could include something like this:
selected_users = self.cleaned_data.get('users')
for user in selected_users:
project_users.add(user)

Django: multiple different fields -> one model

I want to show different fields (a html-option-field who gets Mymodel.object.all and a textfield) and save it to one model field.
How can I build this?
MultiValueField (https://docs.djangoproject.com/en/2.1/ref/forms/fields/) doesn't help with different fields?
Has someone an example? How can I define which kind of field it is?
EDIT:
How can I determine which field I want to save in the model-field? I use a ModelForm.
You should use forms.ModelChoiceField(choices=ModelClass.objects.all()) for the choicefield, you can also set the widget to be widget=forms.CheckboxSelectMultiple.
your form can be like
class SuperForm(forms.Form):
cool_field = forms.ModelChoiceField(
choices=ModelClass.objects.all(),
widget=forms.CheckboxSelectMultiple,
)
text_area = forms.CharField(widget=forms.Textarea)

Django rest framework: how to change default widget of a ModelSerializer renderer with HTMLFormRenderer?

I want to change the default widget of a ModelSerializer field renderered with the HTMLFormRenderer. The field default representation is a ChoiceField as it is a ForeignKey field in the model. I Would like to render it as a CharField.
I have tried to redefine the field in the serializer:
myField = serializers.CharField()
It is shown correctly as a textbox in the form but when saving the form I receive an error saying that it cannot assign the value because it must be an instance of the related model.
How can I do that?
sorry for necrobumping, but I had a similar problem today and this thread jumped high in google results. it seems one can override the style property, like so:
class MySerializer(serializers.Serializer):
my_field = serializers.SlugRelatedField(
queryset = ...,
style={'base_template': 'input.html'}
)
I've looked in source code for HTMLFormRenderer and it uses similar attributes:
https://github.com/encode/django-rest-framework/blob/master/rest_framework/renderers.py#L265
One way is to override the to_native and restore_fields functions of the serializer.
restore_fields essentially lets you handle the incoming request, massage it in any manner you want and save it to models. to_native lets you take the server data and modify it in any manner to send it to the client.

access model fields and attributes in django

I'm writing a simple scaffolding app in django, however I'm still not able to access a models fields and attributes(e.g. CharField, max_length=100, null=True, etc...). I know about the _meta class of models, but as far as I know it only retrieves basic info about the model not the fields. Is there a away to achieve this?
Update:
you can find the answer in this article:
http://www.b-list.org/weblog/2007/nov/04/working-models/
You should use the get_field method to get info for a particular field:
field = ModelName._meta.get_field('field_name')
Then you may check various attributes of field, like field.blank, field.null, field.name etc.
If on the other hand you want to get a list of all fields of a Model you should use fields:
fields = ModelName._meta.fields
For example to get the name of all your model fields you can do something like:
field_names = ', '.join(f.name for f in fields)
Hm... also I just noticed that your question is a duplicate of Get model's fields in Django !

Filtering a ManyToMany field to User insida a form in Django

I've got a custom Model called Group with two ManyToMany fields called admins and members (both to the default User model). I've built a form to edit the administrators:
class AddAdminsForm(forms.ModelForm):
class Meta:
model = Group
fields = (
'admins',
)
Now I want to filter the selection options inside the admins field based on whether it is present in the members field. What would be the best way to achieve that? By entirely changing my members/admins architecture or by somehow messing with the __init__ method inside the form class?
I'm not able to check this solution right now but maybe you can:
....
in your function
form.fields['admins'].queryset = Members.objects.all()