Django: Fields of DeclarativeFieldsMetaclass (without instance) - python

I try to discover the fields which a django form class has.
I only have a class, not an instance.
The form-class is of type DeclarativeFieldsMetaclass.
If I try this:
class FooForm(forms.Form):
spreadsheet = forms.FileField()
for field in FooForm:
print(field)
I get this exception:
TypeError: 'DeclarativeFieldsMetaclass' object is not iterable
I know that I could do FooForm() instead of FooForm, but in my real use case I only have a class.

You can access FooForm.base_fields.

Related

Check if record exists in Django Rest Framework API LIST/DATABASE

I want to create a viewset/apiview with a path like this: list/<slug:entry>/ that once I provide the entry it will check if that entry exists in the database.
*Note: on list/ I have a path to a ViewSet. I wonder if I could change the id with the specific field that I want to check, so I could see if the entry exists or not, but I want to keep the id as it is, so
I tried:
class CheckCouponAPIView(APIView):
def get(self, request, format=None):
try:
Coupon.objects.get(coupon=self.kwargs.get('coupon'))
except Coupon.DoesNotExist:
return Response(data={'message': False})
else:
return Response(data={'message': True})
But I got an error: get() got an unexpected keyword argument 'coupon'.
Here's the path: path('check/<slug:coupon>/', CheckCouponAPIView.as_view()),
Is there any good practice that I could apply in my situation?
What about trying something like this,
class CheckCouponAPIView(viewsets.ModelViewSet):
# other fields
lookup_field = 'slug'
From the official DRF Doc,
lookup_field - The model field that should be used to for performing
object lookup of individual model instances. Defaults to pk

django rest get instance of validator field of serializer

I need to get the instance of the serializer field validator. I have not found such information on the Internet...
If i have a model:
class MyModel(models.Model):
file = FileField(max_length=200, storage=Storage(), upload_to=get_file_path, validators=FileValidator(max_size=10*1024*1024))
I can get the instance of validator somehow this way
MyModel._meta.get_field('file').validators[0]
I need it for an example to mock max_size attribute in tests
with mock.patch.object(target=Mymodel._meta.get_field('file').validators[0], attribute='max_size, new=1)
Now I have another model for which validation occurs on the serializer
class TextItemFileSerializer(serializers.Serializer):
attachments = SomeCustomField(validators=[ArrayMaxLengthValidator(limit_value=30)])
and I need to mock limit_value in the same way as for the model via the validator instance
But the problem is that I do not know how to access to the instance of validator.
Are there any ideas?
obj = None # TextItem Instance
serializer = TextItemFileSerializer(obj)
validators = serializer.get_fields()['attachments'].validators
validators[0]
$ <class 'app.models.UniqueValidator'>]

How to change a foreignkey field back to null?

Pretty new to Django. I am trying to switch the ForeignKey field student_information.project back to a null value. As well my student_remove object doesn't seem to be defining properly as 'Remove' should be an object.
Error Code
AttributeError at /project_list/projects/1/
type object 'Student_Information' has no attribute 'student_remove'
Request Method: GET
Request URL: http://127.0.0.1:8000/project_list/projects/1/?Remove=sathya
Django Version: 1.10.5
Exception Type: AttributeError
Exception Value:
type object 'Student_Information' has no attribute 'student_remove'
Exception Location: /media/rms/Sathya's Dr/mysite/projects/views.py in post_detail, line 27
Python Executable: /usr/bin/python
Python Version: 2.7.12
My views.py
def post_detail(request, pk):
post = get_object_or_404(Project, pk=pk)
students = Student_Information.objects.filter(project=post)
if request.GET.get('Remove'):
Remove = request.GET.get('Remove')
obj = Student_Information.objects.get(RCSID=Remove)
#obj.project = None
return render(request, 'projects/post_detail.html', {'post': post, 'students': students})
obj = Student_Information.objects.get(RCSID=Remove)
is throwing an, should specify that RCSID is a foreignkey, it seems like it's trying to find a primary key of 'sathya' where it should just get a string. How do I make it match the string? As if RCSID is automatically RCSID_id.
invalid literal for int() with base 10: 'sathya'
The error message is pretty clear. Student_Information model doesn't have any field named student_remove.
Apart from that, there are so many things wrong with your code.
In Django, you don't update the Model class. You update an instance of Model class. Records are saved as instances of Model class. So line Student_Information.student_remove.project = "---------", needs to be fixed.
student_information.project can be set to null by simply calling student_information.project = None. But here student_information is an instance of Student_Information model.
filter returns a Queryset, not an instance.
You need to call save on the Model instance to update it in the database.
I would recommend you to go through official polls app tutorial.
I made it work by passing id instead of RCSID so that they matched. Easy fix.

how to display the data from the database in a template

i have following model:
class comment(models.Model):
userid=models.CharField(max_length=140)
apparelid=models.IntegerField(blank=True)
desc=models.TextField(blank=True)
def __unicode__(self):
return self.userid
form :
class commentForm(ModelForm):
class Meta:
model=comment
exclude=('userid','apparelid',)
and view as follows:
def comment(request,title_id):
if request.method=='POST':
form=commentForm(request.POST)
if form.is_valid():
new=form.save(commit=False)
new.userid=request.user.username
new.apparelid=title_id
new.save()
return HttpResponseRedirect('/')
else:
form=commentForm()
template=loader.get_template('apple3/comment.html')
context=RequestContext(request,{
'form':form,
}
)
return HttpResponse(template.render(context))
whenever i open my page containg above form it show an error as follows:
Exception Type: AttributeError
Exception Value: 'function' object has no attribute 'objects'
You probably import comment model from inside your view and then use comment again as view name. That's why the error gets thrown.
Please use different name for your view and model if you use them in the same module.
Problem at hand seems to be solved by #mariodev. Additionaly, I'd recommend two following steps as a mean of avoiding similar problems in future:
Read PEP8, the Style Guide for Python Code thoroughly
Use only packages and modules import.
Following those two links will make your code more pythonic and less error-prone.
The name of the model class and the view function is same which is resulting in the error:
Exception Value: 'function' object has no attribute 'objects'
You may use a different naming conventions for your classes and functions. As per PEP8, first letter of the class name should be capital/uppercase and the function's name should be lowercase.
So in your case, if you have to keep the names exactly same, you may rename your Model Class to Comment and let your view function's name be comment and that should solve the problem.

Accessing form fields as properties in a django view

According to the Django tutorial, you should access form fields using cleaned_data dictionary. I'm wondering why I can't access the properties of the form directly? My form validates just fine, but when I try to access it, Django complains that the object does not have the attribute. I added some code below that I hope will help diagnose the problem.
Form:
class CustomForm(forms.Form):
description = forms.CharField(widget = forms.TextInput(attrs = {'placeholder' : 'enter some text'}), label = "My form")
View:
def process_form(request):
if request.method != 'POST':
raise Http404
myForm = CustomForm(request.POST)
if not myForm.is_valid():
c = RequestContext(request)
return render_to_response('home/index.html', {'form' : myForm }, c)
# debug
print 'Description: ' + myForm.description # this does NOT work
# print 'Description: ' + myForm.cleaned_data['description'] # this does work
I get the following error: 'CustomForm' object has no attribute 'description'. Did I miss something in the docs that says I can't do that?
If your form is validated then you can access myForm cleaned_data:
print myForm.cleaned_data.get('description')
If you want to see why you cannot access myForm.description then you can see the data dictionary of your myForm:
print myForm.__dict__
The way you define fields using django.forms is just a convenient, declarative syntax; it's not really representative of what the final Form class, or an instance of it, looks like in terms of attributes.
Forms have a metaclass (without getting too deep into it, a metaclass is to declaring a class using the class keyword as an __init__ method is to creating an instance of a class using parentheses -- a hook to customise the object being created, which in the case of a metaclass, is a class!) which picks off Fields from the form class at definition time and adds them to a base_fields dict. When you instantiate a form, its base_fields are deep-copied to a fields attribute on the instance.
One point of confusion might be that you use . to access fields for display in templates -- what's actually happening there is that Django's template engine first attempts to use dictionary-style [] access to resolve property lookups and the base form class defines a __getitem__ method to take advantage of this, looking up the appropriate field from the form instance's fields dict and wrapping it with a BoundField, a wrapper which knows how to use the field and data from the form for displaying the field.
You can access the fields of a Form instance from its fields attribute.
myForm.fields['description']
And some property like label can be accessed like this:
myForm.fields['description'].label
Not sure how to display the value corresponding. Anybody having idea?
here is my reference
https://docs.djangoproject.com/en/dev/ref/forms/api/#accessing-the-fields-from-the-form
You can access your field trought dict.
form.__dict__["fields"]["description"]

Categories

Resources