using CreateView class, I want to save multiple data entries.
example inputs:
item is "apple,banana,carrots"
location is "location 1"
I want to save them to database like this:
[apple, location 1]
[banana, location 1]
[carrots, location 1]
#model.py
class Inventory(models.Model):
item = models.CharField(max_length=14)
location = models.CharField(max_length=10)
#forms.py
class InventoryCreateForm(forms.ModelForm):
item = forms.CharField(widget=forms.Textarea(attrs={'rows': 8,
'cols': 14}))
class Meta:
model = Inventory
#views.py
class InventoryCreateView(CreateView):
model = Inventory
form_class = InventoryCreateForm
Thank you
You need to override the "form_valid()" method used by the createview.
You then need to read in the form data
def form_valid(self,form):
self.object = form.save(commit=False)
foo = self.object.bar #your data is in the object
Then because you are using a textfield you need to somehow split the data passed into the form and loop over those values. Ideally you will want a list of items ['apple', 'banana', 'pear']
then take the location out of the list and store that into a variable that can be used later on location_variable.
Once you have the data in the form you want you then need to instantiate the Inventory model
from foo.models import Inventory #import at the top of your file
for item is list:
inventory = Inventory()
inventory.item = item
inventory.location = location_variable
inventory.save()
I hope this answer can help you in some way, if you would like further details on Class based view, visit ccbv where all of the information for each view is listed.
Otherwise you can look in the django Form docs for a more suitable form to use.
hopefully this helps anyone else who comes to this page.
Here is what I did:
class TrainingBulkCreateForm(ModelForm):
# todo: could we make the original user object a multiple choice field instead?
extra_user = forms.ModelMultipleChoiceField(queryset=User.objects.filter(is_active=True), required=True)
class Meta(object):
model = Training
fields = '__all__'
def post(self, request, *args, **kwargs):
result = super().post(request, *args, **kwargs)
users = request.POST.getlist('extra_user')
if users:
# modify request.POST data then re-save the additional users
for user in users:
# Need to copy the data because the initial QueryDict is immutable data
postdata_copy = request.POST.copy()
postdata_copy['user'] = user
form2 = TrainingBulkCreateForm(postdata_copy)
form2.save()
return result
I have my item field (mine is user) split into two form fields - the original item which is 1 object like apple.
Then I also have extra_user as a second form field. This takes multiple objects like [banana, carrots]
In the view I invoke the super().post(...) to save the initial apple object.
Then I check for the extra_user field to see if there are multiple foods. If there are extras, I copy the immutable QueryDict object request.POST as postdata_copy.
Then I modify postdata_copy so instead of having apple we replace with banana. (This basically just duplicates the apple form into a new copy with banana and re-saves the form). Then we loop again and replace apple with carrots.
Note that my Form object uses ModelMultipleChoiceField for extra_user object. This has better data integrity than typing in raw text.
Related
I want delete serializer's content to show.I am using Django Rest Framework.I am making a system return Json of serializers.Furthermore,I did not want to show user_id data. I wrote in views.py
class InfoViews(viewsets.ModelViewSet):
queryset = Info.objects.all()
serializer_class = InfoSerializer
lookup_field = 'id'
def update(self,request, *args, **kwargs):
obj = UserInfo.objects.get(pk=kwargs['id'])
data = request.data
info_serializers = InfoSerializer(obj, data = data)
if info_serializers.is_valid(raise_exception=True):
info_serializers.save()
del info_serializers.data['user_id']
return JsonResponse(info_serializers.data)
Now all son data is shown.What is wrong in my code?How should I fix this?
You can specify in the serializers which fields you want to include or exclude in the response:
http://www.django-rest-framework.org/api-guide/serializers/#specifying-which-fields-to-include
look for : Specifying which fields to include
hope this helpes
First Clone the object into a new variable and then pop the key.
if info_serializers.is_valid(raise_exception=True):
info_serializers.save()
import copy
new = copy.deepcopy(info_serializers.data)
new.pop('user_id', None)
return JsonResponse(new)
As a Django newbie, I am trying to return JSON Objects from two models with each object containing the username, id, ticketID. Right now the code is simply putting the lists together without indexing. I should point out that there is a relationship between user and ticket so that can be traversed also.
{"username":"Paul","id":2}, {"username":"Paul","id":2}, {"username":"Ron","id":19}, {"id":"1c6f039c"}, {"id":"6480e439"},
{"id":"a97cf1s"}
class UsersforEvent(APIView):
def post(self, request):
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
value = body['event']
queryset = Ticket.objects.filter(event = value)
referenced_users = User.objects.filter(ticket_owner__in=queryset.values('id'))
result_list = list(itertools.chain(referenced_users.values('username', 'id'), queryset.values('id')))
return Response((result_list))
You should do a single query to get the ticket with the related user for each one, then create the list of dicts from there. Assuming your Ticket model has an "owner" field which is a FK to User:
queryset = Ticket.objects.filter(event=value).select_related('owner')
result_list = [{'ticket_id': ticket.id, 'username': ticket.owner.username, 'user_id': ticket.owner.id}
for ticket in queryset]
(Note, this shouldn't be the action of a POST though; that is for changing data in the db, not querying.)
I am trying to write a form that allows the user to select as many users from a specific group as they want. However when I try to use the list of users as an option I get an error saying that 'User' object does not support indexing.
Its a fairly standard form, the main difference is that the group is filtered based on a kwarg passed to the form. The form is passed a project_id (project object primary key) and it then finds the group associated with that project and generates the field.
From forms.py
class ModifyTeamForm(forms.Form):
action = ChoiceField(choices=[('remove', 'Remove users'), ('promote', 'Promote to lead.')])
def __init__(self, *args, **kwargs):
# The project to get the team for
project_id = kwargs.pop('project_id', None)
super(ModifyTeamForm, self).__init__(*args, **kwargs)
project = Project.objects.get(pk=project_id)
# Team for this project
team = User.objects.filter(groups__name=project.project_name)
# Create a form field to select current team members
current_team = MultipleChoiceField(required=True, choices = team, widget=CheckboxSelectMultiple)
# Add the field
self.fields['current_team'] = current_team
My views.py
#login_required
def team(request, project_id):
if request.method == "POST":
# Not yet implemented
return
else:
form = ModifyTeamForm(project_id=project_id)
template = loader.get_template('projects/team.html')
context = RequestContext(request, {
'form': form,
})
return HttpResponse(template.render(context))
It's because MultipleChoiceField.choices is expected to be a 2d Array effectively (https://docs.djangoproject.com/en/1.7/ref/forms/fields/#django.forms.ChoiceField.choices).
So you could do something like this:
team = [(u.pk, u.email) for u in User.objects.filter(groups__name=project.project_name)]
And that will return you a list continaing the combintation of
[('user1.pk', 'user1.email'), ('user2.pk', 'user2.email'),...]
which will be useable as the choices.
I am trying to generate a form in WTForms that has dynamic fields according to this documentation http://wtforms.simplecodes.com/docs/1.0.2/specific_problems.html#dynamic-form-composition
I have this subform class which allows users to pick items to purchase from a list:
class Item(Form):
itmid = SelectField('Item ID')
qty = IntegerField('Quantity')
class F(Form):
pass
There will be more than one category of shopping items, so I would like to generate a dynamic select field based on what categories the user will choose:
fld = FieldList(FormField(Item))
fld.append_entry()
but I get the following error:
AttributeError: 'UnboundField' object has no attribute 'append_entry'
Am I doing something wrong, or is there no way to accomplish this in WTForms?
I ran into this issue tonight and ended up with this. I hope this helps future people.
RecipeForm.py
class RecipeForm(Form):
category = SelectField('Category', choices=[], coerce=int)
...
views.py
#mod.route('/recipes/create', methods=['POST'])
def validateRecipe():
categories = [(c.id, c.name) for c in g.user.categories.order_by(Category.name).all()]
form = RecipeForm(request.form)
form.category.choices = categories
...
#mod.route('/recipes/create', methods=['GET'])
def createRecipe():
categories = [(c.id, c.name) for c in g.user.categories.order_by(Category.name).all()]
form = RecipeForm(request.form)
form.category.choices = categories
return render_template('recipes/createRecipe.html', form=form)
I found this post helpful as well
class BaseForm(Form):
#classmethod
def append_field(cls, name, field):
setattr(cls, name, field)
return cls
from forms import TestForm
form = TestForm.append_field("do_you_want_fries_with_that",BooleanField('fries'))(obj=db_populate_object)
I use the extended class BaseForm for all my forms and have a convenient append_field function on class.
Returns the class with the field appended, since instances (of Form fields) can't append fields.
Posting without writing full code or testing the code, but maybe it will give you some ideas. Also this could maybe only help with the filling the needed data.
You need to fill choices for SelectField to be able to see the data and be able to select it. Where you fill that? Initial fill should be in the form definition, but if you like dynamic one, I would suggest to modify it in the place where you creating this form for showing to the user. Like the view where you do some form = YourForm() and then passing it to the template.
How to fill form's select field with choices? You must have list of tuples and then something like this:
form.category_select.choices = [(key, categories[key]) for key in categories]
form.category_select.choices.insert(0, ("", "Some default value..."))
categories here must be dictionary containing your categories in format like {1:'One', 2:'Two',...}
So if you will assign something to choices when defining the form it will have that data from the beginning, and where you need to have user's categories, just overwrite it in the view.
Hope that will give you some ideas and you can move forward :)
have you tried calling append_entry() on the form instance instead of the FieldList definition?
class F(Form)
fld = FieldList(SelectField(Item))
form = F()
form.fld.append_entry()
This is how i got it to work.
class MyForm(FlaskForm):
mylist = SelectField('Select Field', choices=[])
#app.route("/test", methods=['GET', 'POST']
def testview():
form = MyForm()
form.mylist.choices = [(str(i), i) for i in range(9)]
Strangely this whole thing stops working for me if i use coerce=int. I am myself a flask beginner, so i am not really sure why coerce=int causes issue.
WTForms Documentation : class wtforms.fields.SelectField
Select fields with dynamic choice values:
class UserDetails(Form):
group_id = SelectField(u'Group', coerce=int)
def edit_user(request, id):
user = User.query.get(id)
form = UserDetails(request.POST, obj=user)
form.group_id.choices = [(g.id, g.name) for g in Group.query.order_by('name')]
First of all: I am not able to find out the proper Title of this question.
Anyhow the question is:
I have to fill a form at template and the fields of this form are user dependent. For example you passes integer (integer is not a datatype) as a parameter to the method and it should returns like this:
fileds = forms.IntegerField()
If you pass bool then it should like this:
fields = forms.BooleanField()
So that i can use them to create my form. I tried with this code but it returns into the form of string.
Some.py file:
choices = (('bool','BooleanField()'),
('integer','IntegerField()'))
def choose_field():
option = 'bool' # Here it is hardcoded but in my app it comes from database.
for x in choices:
if x[0]==option:
type = x[1]
a = 'forms'
field = [a,type]
field = ".".join(field)
return field
When i print the field it prints 'forms.BooleanField()'. I also use this return value but it didn't work. Amy solution to this problem?
The simpliest way is to create your form class and include fields for all possible choices to it. Then write a constructor in this class and hide the fields you don't want to appear. The constructor must take a parameter indicating which fields do we need. It can be useful to store this parameter in the form and use it in clean method to correct collected data accordingly to this parameter.
class Your_form(forms.ModelForm):
field_integer = forms.IntegerField()
field_boolean = forms.BooleanField()
def __init__(self, *args, **kwargs):
option = kwargs["option"]
if option == "integer":
field_boolean.widget = field_boolean.hidden_widget()
else:
field_integer.widget = field_integer.hidden_widget()
super(Your_form, self).__init__(*args, **kwargs)
In your controller:
option = 'bool'
form = Your_form(option=option)