Using value from URL in Form Wizard for Django - python

I'm trying to use this Form Wizard to design a multipage form in Django.
I need to catch a value from the URL, which is a client's ID, and pass it to one of the Forms instance, as the form will be built dynamically with specific values for that client.
I have tried redefining the method get_form_kwargs based on this thread, but this isn't working for me.
I have the following code in my views.py:
class NewScanWizard(CookieWizardView):
def done(self, form_list, **kwargs):
#some code
def get_form_kwargs(self, step):
kwargs = super(NewScanWizard, self).get_form_kwargs(step)
if step == '1': #I just need client_id for step 1
kwargs['client_id'] = self.kwargs['client_id']
return kwargs
Then, this is the code in forms.py:
from django import forms
from clients.models import KnownHosts
from bson import ObjectId
class SetNameForm(forms.Form): #Form for step 0
name = forms.CharField()
class SetScopeForm(forms.Form): #Form for step 1, this is where I need to get client_id
def __init__(self, *args, **kwargs):
super(SetScopeForm, self).__init__(*args, **kwargs)
client_id = kwargs['client_id']
clientHosts = KnownHosts.objects.filter(_id=ObjectId(client_id))
if clientHosts:
for h in clientHosts.hosts:
#some code to build the form
When running this code, step 0 works perfectly. However, when submitting part 0 and getting part 1, I get the following error:
_init_() got an unexpected keyword argument 'client_id'
I've done some debugging and I can see that the value for client_id is binding correctly to kwargs, but I have no clue on how to solve this problem. I think this might not be difficult to fix, but I'm quite new to Python and don't get which the problem is.

You should delete cliend_id from kwargs before calling super(SetScopeForm, self).__init__(*args, **kwargs).
To delete client_id you can use kwargs.pop('client_id', None):
class SetScopeForm(forms.Form): #Form for step 1, this is where I need to get client_id
def __init__(self, *args, **kwargs):
# POP CLIENT_ID BEFORE calling super SetScopeForm
client_id = kwargs.pop('client_id', None)
# call super
super(SetScopeForm, self).__init__(*args, **kwargs)
clientHosts = KnownHosts.objects.filter(_id=ObjectId(client_id))
if clientHosts:
for h in clientHosts.hosts:
#some code to build the form

Related

How to use variables in ModelChoiceField queryset in Django

I am trying to use a specific list of data in my form with Django. I am using ModelChoiceField to retrieve from the model the data I need to display in the form (to let the users select from a scolldown menu).
My query is complicate because need two filters based on variables passed by views
I've tried to use the sessions but in form is not possible to import the session (based to my knowledge).
form.py
def __init__(self, pass_variables, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['initiative'] = forms.ModelChoiceField(queryset=raid_User_Initiative.objects.filter(company=pass_variables[1], username=pass_variables[0]).values_list('initiative', flat=True))
view.py
pass_variables = ((str(request.user), companyname))
f = Issue_form(pass_variables)
If I don't pass the variable the process works. The problem is with the code above as the form don't provide any error but it doesn't pass the if f.is_valid():
Thanks
I solved myself! Anyway if anyone interested the solution is using the sessions:
form.py
Before I declare the queryset as:
initiative = forms.ModelChoiceField(queryset=raid_User_Initiative.objects.all(), to_field_name="initiative")
And it is very important to use the , to_field_name="initiative"
After I amend the queryset as:
def __init__(self, user, company, *args, **kwargs):
super(raid_Issue_form, self).__init__(*args, **kwargs)
self.fields['initiative'].queryset = raid_User_Initiative.objects.filter(company=company, username=user).values_list('initiative', flat=True)
view.py
f = raid_Issue_form(request.user, request.session['company'])
Hope this help!

Can I set a StringField's default value outside the field constructor?

If I set the default value during construction of the field, all works as expected:
my_field = StringField("My Field: ", default="default value", validators=[Optional(), Length(0, 255)])
However, if I try to set it programmatically, it has no effect. I've tried by modifying the __init__ method like so:
class MyForm(FlaskForm):
my_field = StringField("My Field: ", validators=[Optional(), Length(0, 255)])
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.my_field.default = "set default from init" # doesn't work
This does not set the default value. How can I do this programatically (because the value is dynamic based on a database query, and if I do this outside of __init__ then it does not get the most current value)?
Relevant versions from my requirements.txt:
Flask==0.12
Flask-WTF==0.14.2
WTForms==2.1
Also, I'm running Python 3.6 if that matters.
Alternatively, I'm fine with a solution that enables me to set the value data for this field on initial form load when adding a new record (same behavior as default value being specified in constructor) but this same form is also used for editing so I would not want it changing object data that is already saved/stored on edit.
You can set initial values for fields by passing a MultiDict as FlaskForm's formdata argument.
from werkzeug.datastructures import MultiDict
class MyForm(FlaskForm):
my_field = StringField("My Field: ", validators=[Optional(), Length(0, 255)])
form = MyForm(formdata=MultiDict({'my_field': 'Foo}))
This will set the value of the my_field input to 'Foo' when the form is rendered, overriding the default value for the field. However you don't want to override the values when the form is posted back to the server, so you need to check the request method in your handler:
from flask import render_template, request
from werkzeug.datastructures import MultiDict
#app.route('/', methods=['GET', 'POST'])
def test():
if request.method == 'GET':
form = MyForm(formdata=MultiDict({'my_field': 'Foo'}))
else:
form = MyForm()
if form.validate_on_submit():
# do stuff
return render_template(template, form=form)
You can access your fields in __init__ as a dictionary:
class MyForm(FlaskForm):
def __init__(self, *args, **kwargs):
default_value = kwargs.pop('default_value')
super(MyForm, self).__init__(*args, **kwargs)
self['my_field'] = StringField("My Field: ", default=default_value,
validators=[Optional(), Length(0, 255)])
You would then call it like this:
form = MyForm(default_value='Foo')
See the documentation for the wtforms.form.Form class for more information and other details.
its to late to reply on this question but I saw a simple way to do this which is not mentioned in answers above. Simplest way to asign a value is
#app.route('/xyz', methods=['GET', 'POST'])
def methodName():
form = MyForm()
form.field.data = <default_value>
.....
return render_template('abc.html', form=form)
The field of the form will display asigned default_value when page load.

How to filter model choice field options based on user in django?

Here is my form:
class RecipeForm(forms.Form):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(RecipeForm, self).__init__(*args, **kwargs)
Recipebase_id = forms.ModelChoiceField(queryset=Recipebase.objects.filter(user = self.user))
title = forms.CharField(max_length=500)
instructions = forms.CharField(max_length=500)
I want to filter model choice field based on user as you can see from the filter. But it gives the following error:
name 'self' is not defined
Any suggestions would be highly appreciated.
The self. would work only for objects created from a class. In this case you are not creating one, so it would not work as you would expect.
Instead, you need to override the queryset in the __init__ like this:
class RecipeForm(forms.Form):
Recipebase_id = forms.ModelChoiceField(queryset=Recipebase.objects.none())
def __init__(self, *args, **kwargs):
user = kwargs.pop('user') #Throws an error if user is not present
super(RecipeForm, self).__init__(*args, **kwargs)
qs = Recipebase.objects.filter(user=user)
self.fields['Recipebase_id'].queryset = qs
Another way to achieve the same is to make user a required argument in the form
class RecipeForm(forms.Form):
Recipebase_id = forms.ModelChoiceField(queryset=Recipebase.objects.none())
def __init__(self, user, *args, **kwargs):
super(RecipeForm, self).__init__(*args, **kwargs)
qs = Recipebase.objects.filter(user=user)
self.fields['Recipebase_id'].queryset = qs
And the view code would look like this:
form = RecipeForm(request.POST, user=request.user) #user would be passed in as a kwarg to the form class.
Putting your code starting at "Recipebase_id" at the indentation level you have it causes python to execute it at the time the file is parsed/imported. Self is passed into a method when the class is instantiated and the instance method is called, so at parse time self does not exist.
It's unclear to me if you want the Recipebase_id, title and instructions set in the init method. If you do, indent them to the same level as the lines above it. If not, then you'll need to get the value of user from somewhere other than self.

How to support all REST operations for an endpoint in django rest framework

I have a subscription model that looks like this
class Subscription(models.Model):
name = models.CharField(max_length=100)
quantity = models.IntegerField(max_length=20)
stripe_id = models.CharField(max_length=100)
user = models.ForeignKey(User)
I would like to create an endpoint that allows POST, PATCH, DELETE, GET
So I did the following things
views.py
class SubscriptionDetail(viewsets.ModelViewSet):
serializer_class = SubscriptionSerializer
permission_classes = (IsAuthenticated,)
queryset = Subscription.objects.all()
serializers.py
class SubscriptionSerializer(serializers.ModelSerializer):
class Meta:
model = Subscription
fields = ('name','quantity', 'stripe_id')
def update(self, instance, validated_data):
print "In update"
#how do I write create and delete?
urls.py
subscription = SubscriptionDetail.as_view({
'patch': 'update'
})
url(r'^rest-auth/subscription/$', subscription, name='something'),
Questions
Using the above when I send a PATCH request, I get an error. How can I fix this?
Expected view SubscriptionDetail to be called with a URL keyword
argument named "pk". Fix your URL conf, or set the .lookup_field
attribute on the view correctly.
While sending the patch request I would also like to send an 'email' field which is not on the subscription model. Is this possible to do? I need the email field in the POST (create) operation so that I know which user the subscription belongs to.
The easiest way is to do it this way.
keep the models class the same
views.py
from rest_framework import viewsets
#impost serializer and model class for subscription
class SubscriptionViewSet(viewsets.ModelViewSet):
serializer_class = SubscriptionSerializer
def get_queryset(self):
queryset = Subscription.objects.all()
#if you need to get subscription by name
name = self.request.QUERY_PARAMS.get('name', None)
if name is not None:
queryset = queryset.filter(name=name)
return queryset
serializers.py
class SubscriptionSerializer(serializers.ModelSerializer):
class Meta:
model = Subscription
fields = ('name','quantity', 'stripe_id')
# django will handle get, delete,patch, update for you ....
# for customization you can use def update or def create ... to do whatever you need
# def create(self, validated_data):
# you can handle the email here
# and something like subscription= Subscription (name=validated_data['name'],vendor=validated_data['quantity']...)
# subscription.save()
# it will save whatever you want
urls.py
#use the router to handle everything for you
from django.conf.urls import patterns, include, url
from rest_framework import routers
#import your classes
router = routers.DefaultRouter()
router.register(r'subscription', views.SubscriptionViewSet,base_name='subscription')
urlpatterns = patterns('',
url(r'^', include(router.urls)),
)
For the creation of an Object you must implement the create function as described in the official documentation, found here. For patching you could use the partial argument from within you view class:
SubscriptionSerializer(subscription, data={'something': u'another', partial=True)
For deletion of the a Subscription, that could be done when you get the delete call as so in your view class:
if request.METHOD == 'DELETE':
subscription = Subscription.objects.get(pk=pk)
subscription.delete()
See this tutorial for complete example
Further more I think that you should include the "id" field in the SubscriptionSerialiser Meta class, otherwise it will be difficult to do the updates/deletions. I hope this helped a little.
Cheers,
Tobbe
When you want to use a method that allow make these operations you have to use a #detail_route() where you can say as well which methods will you use, like in the docs is said:
#detail_route(methods=['post'])
def set_password(self, request, pk=None):
user = self.get_object()
serializer = PasswordSerializer(data=request.data)
...
So to be able to use them you should add the next decorator
#detail_route(methods=['post', 'patch'])
To add another parameters you can do it for the .save() parameter. You just have to indicate the name of this and them just override your .save() model to check if that email belongs or not to the user that is trying to do the subscription. Here I paste you what the Django Rest docs says:
" Passing additional attributes to .save()
...
You can do so by including additional keyword arguments when calling .save(). For example:
serializer.save(owner=request.user)
Here I leave you the link for more information:
http://www.django-rest-framework.org/api-guide/serializers/#passing-additional-attributes-to-save
Using the above when I send a PATCH request, I get an error. How can I fix this?
Expected view SubscriptionDetail to be called with a URL keyword
argument named "pk". Fix your URL conf, or set the .lookup_field
attribute on the view correctly.
The error is caused because unlike create request, patch/update require a pk to know which object to update. That is why you have to supply the pk value for it. So, your url for PUT, DELETE andPATCH must have at least named parameter like this -
subscription = SubscriptionDetail.as_view({
'patch': 'update'
})
url(r'^rest-auth/subscription/(?<pk>(\d+))$', subscription, name='something'),
an example url will be - rest-auth/subscription/10 where 10 is the pk or id of the object. Django Rest Framework will then load the object internally to be updated.
While sending the patch request I would also like to send an 'email' field which is not on the subscription model. Is this possible to do? I need the email field in the POST (create) operation so that I know which user the subscription belongs to.
To add custom parameters, first declare the property in serializer, it is better to keep it required=False, so that other request does not throw error -
class SubscriptionSerializer(serializers.ModelSerializer):
custom_field = serialiers.BooleanField(required=False)
class Meta:
model = Subscription
fields = ('name','quantity', 'stripe_id')
def update(self, instance, validated_data):
print "In update"
so far this is enough for the django rest framework to accept the field custom_field and you will find the value in update method. To get the value pop it from the attributes supplied by the framework like this -
def update(self, instance, validated_data):
custom_field = validated_data.pop('custom_field', None)
if custom_field is not None:
# do whatever you like with the field
return super().update(instance, validated_data)
# for python < 3.0 super(SubscriptionSerializer, self).update(instance, validated_data)
When you overrided (I don't know if that's the proper conjugation of overriding a method) the update method, you stopped the ability to PUT or PATCH and object. Your new method only prints out "In update" but doesn't save the instance. Look at the update method from the serializer.ModelSerializer object:
def update(self, instance, validated_data):
raise_errors_on_nested_writes('update', self, validated_data)
for attr, value in validated_data.items():
setattr(instance, attr, value)
instance.save()
return instance
Notice the last few lines where the instance is saved with the values and then returned. Remove your update method on the SubscriptionSerializer object. This let's your parent object's create, update, retrieve, and delete methods do their magic which supports PATCH and PUT updates. The next problem is that your urls.py is using the Django rather than the REST framework router. Change it to this:
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'subscription', SubscriptionDetail)
That should solve the patch update problem.
I don't think you can add an email field in your patch method without the attribute on the subscription model. That's just a guess on my part, and I may be wrong. Does the email field map to anything on any object? Can you use a ForeignKey to map it?
I hope that works for you, good luck!
In view.py you just need set the class with:
class SubscriptionDetail(mixins.CreateModelMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
generics.GenericAPIView):
and add this to fix .lookup_field :
def update(self, request, *args, **kwargs):
log.error("OBJ update kwargs= %s , data = %s" % (kwargs, str(request.data)))
pk = request.data.get('id')
if (kwargs.get('pk') is not None):
kwargs['pk'] = request.data.get('id')
self.kwargs['pk'] = request.data.get('id')
return super().update(request, *args, **kwargs)
and add support to methods do you want :
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
# def get(self, request, *args, **kwargs):
# return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
# def patch(self, request, *args, **kwargs):
# return self.partial_update(request, *args, **kwargs)
#
# def delete(self, request, *args, **kwargs):
# return self.destroy(request, *args, **kwargs)
only tweak that remains is get for list or get for retrieve on element but should be easy now add something if we have one pk we may call self.retrieve else we may call self.list

Passing values into django forms

I have googled around trying to figure out and understand how this works, yet I still haven't grasped this quite right. What I want to do is pass a value into a form to then use for a query. I have a session variable called menu_term, which determines the choices in the form.
from views.py
def manage_groups(request):
form = CourseGroupForm(request,current_term=request.session.get('menu_term'))
return render_to_response("accounts/group_management.html", {'form':form}, context_instance=RequestContext(request))
from forms.py
class CourseGroupForm(ModelForm):
def __init__(self, current_term, *args, **kwargs):
super(CourseGroupForm, self).__init__(*args, **kwargs)
courseslist = Course.objects.filter(term=current_term, num_in=settings.LAB_COURSES).order_by('description').distinct();
print(courseslist)
self.fields['courses'].queryset = forms.ChoiceField(label='Select Course', choices=courseslist)
class Meta:
model = CourseGroup
fields = ['name','courses'];
The error I am getting is:
__init__() got multiple values for keyword argument 'current_term'
For the benefit of anyone else coming across this, what are the proper ways of defining a form that takes a value passed in from outside?
Thanks,
Good Day
MJ
Its important to pop the kwarg you instantiate your form with before calling the forms super __init__
class CourseGroupForm(ModelForm):
def __init__(self, current_term, *args, **kwargs):
current_term = kwargs.pop('current_term')
super(CourseGroupForm, self).__init__(*args, **kwargs)
The above assumes current_term is always present.
as #vishen pointed out, check your arguments, you are initializing your form with request as the value for current_term
The error is happening because in your model form init decleration
class CourseGroupForm(ModelForm):
def __init__(self, current_term, *args, **kwargs)
current_term is the first argument that the form is expecting to find, but because you are passing through the request object first and then the current_term after that, your effiectely passing the following
form = CourseGroupForm(current_term=request,current_term=request.session.get('menu_term'))
Hence the multiple values for keyword argument 'current_term' error message.

Categories