开发者

Django forms: show ChoiceField for some users, put same value for other users

开发者 https://www.devze.com 2023-03-26 17:44 出处:网络
General I have two kind of users, and one field (\"cluster\") that I want to use differently: Senior users - will choose a cluster from a list.

General

I have two kind of users, and one field ("cluster") that I want to use differently:

Senior users - will choose a cluster from a list.

Junior users - the field will be hidden from them and will always input the same value to the field form + model + database cell.

My Problem

For the senior everything works fine - the field is shown and they can choose.

The problem is, that with junior users the field is hidden (as should be) but then I get an "This field is required" error.

I tried to add to models.py the parameters blank=True,null=True but it did not help.

My Code

Forms.py:

class myModelForm(ModelForm):
    class Meta:
        model = myModel
    def __init__(self, *args, **kwargs):
        super(myModelForm, self).__init__(*args, **kwargs)
        self.fields['cluster'] = forms.ChoiceField(choices=[(x,x) for x in myModel.objects.get(f_id=USER_FAMIL开发者_Go百科Y).supportedClustersInFamily.split(',')])

Models.py:

class myModel(models.Model):
    cluster = models.CharField(max_length=20, blank=True)

Views.py:

def proccessMyModel(request):
    form = myModelForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        result = form.save(commit=False)
        if not request.user.has_perm('my_webapp.senior_permission'):
            result.cluster= "DEFAULT CLUSTER"
        result.save()
        return HttpResponseRedirect(reverse('my_webapp.views.index'))
    return render_to_response("my_webapp/myModelForm.html", {
        "form": form,
    }, context_instance=RequestContext(request))

myForm.html:

<form action="/my_webapp/myModelForm" method="post">{% csrf_token %}
    {% if perms.my_webapp.senior_permission %}
    <div class="fieldWrapper">
        <label for="id_cluster">Cluster:</label>
        {{ form.cluster }}
    </div>
    {% endif %}
    <p><input type="submit" value="submit" /></p>
</form>

Desperate Text...

I searched a-lot, and can't find an answer anywhere! Thank you for your time!!


I think you are supposed to put a required=False in your forms .

Something like this :

forms.ChoiceField(choices=somechoices)

Have a look at this

https://docs.djangoproject.com/en/dev/ref/forms/fields/#required

0

精彩评论

暂无评论...
验证码 换一张
取 消