I'm trying to create a simple cropping utility using jQuery and Jcrop (would be inside a modelform).
Initially I had this in my models:
photo = CustomImageField(null=True, allowed_types=['type:image'],
width=960, height=340)
However now I have Jcrop data (that I would like to insert for 'width' and 'height' parameters) in my main.js and would have to be sent to Django.
To do that, I created a hidden form field in my modelform and I populate it with jQuery after the user has created a selection (a default is also provided, in case the user does not select anything).
I was thinking that maybe I could add the extra keyword arguments when I override the form save() method, but
a) does it pass the kwargs to the CustomImageField?
b) I have no idea (syntax-wise) how to get/add/edit the kwargs of photo.
I've tried self.fields['photo'].kwargs, self.fields['photo'].getattr('width') and many other similar constructions that I've used in the past, but none provided any results.
After some googling I stumbled upon x = kwargs.pop('y', None) (it's not the same as list.pop(), is it?), but was unable to find any documentation on that and overall I get the feeling, that when I call kwargs.pop(x, y) in the save() method, then it handles the kwargs of the save() method, no matter what I set for x and y.
A little help or a hint in the right direction would be much appreciated guys, been stuck with this for days now. :)
PS. I am well aware of django-image-cropping and also well aware of that it fails to function with some specific generic Django views.
Related
I am new to DJango and DRF and have been asked to manage some DJango/DRF related code. After a lot of search I am still unable to find a complete example on how filter_queryset works and how can it be used with different arguments.
At some places I see it used like the following,
self.filter_queryset(queryset)
and at other places it is used with some arguments. It would be helpful if some one can explain the fundamentals like how and when to use it, what are the dependent variables (lookup_field, filter_backends etc...) and arguments and how to set them up.
I have searched a lot and also gone through the docs. If i have missed any doc kindly let me know.
The filter_queryset()--(source code) is a method which is originally implemented in GenericAPIView -- (DRF doc) class.
def filter_queryset(self, queryset):
"""
Given a queryset, filter it with whichever filter backend is in use.
You are unlikely to want to override this method, although you may need
to call it either from a list view, or from a custom `get_object`
method if you want to apply the configured filtering backend to the
default queryset.
"""
for backend in list(self.filter_backends):
queryset = backend().filter_queryset(self.request, queryset, self)
return queryset
I think the functionality of the method is clearly visible from the doc strings.
".....and at other places it is used with some arguments"
The views's filter_queryset() method takes only one parameter, which is the queryset to be filtered.
But, filter-backends' filter_queryset() method takes three arguments which are request,queryset and the view itself.
What are FilterBackends?
Filterbackends are classes which helps us to filter the queryset with complex lookups and some other stuff.
DRF has few built-in backends which can be found here.DRF official docs recommend to use django-filter package for advanced filtering purposes.
How filter-backend working?
Take a look at the source code of DjangoFilterBackend class and it's methods...It's filter_queryset(...) method plays key role in the filtering process.
I would recommend to go through the doc of django-filter to understand the usage of the same with more examples.
By defining filterset_class, you could've more controll over the filtering process (such as providing lookup_expr etc)
I know that similar questions have been asked here in stackoverflow, but this is not just a mere question but a confirmation of my basic understanding. This is directed to those who have knowledge in Django.
My dilemma is the function admin.site.register() in admin.py in Django. My undestanding is that it accepts a number of arguments; I am playing around with it at this moment by working on the tutorials provided at the Django website. The arguments that I have at this time are Questions(model), QuestionsAdmin(admin.ModelAdmin)
and i have this admin.site.register(Question,QuestionAdmin).
the QuestionAdmin class changes the outlook of the Question Page in admin. it allows me to add, reduce the number of information that I want to be shown at the same time, edit how it looks.
However, when I tried this admin.site.register(Questions,Choice) where Choice is a model. it spits out an error.
Does this mean that admin.site.register accepts arguments:
a The Model you want to add/register
b) any classes specifically created to be of use to the model, such as functions, statements altering
the view and functionality of the model in display/view.
to add to that, when i increase the number of arguments to 3, it spits out an error saying that i have inputed 4.
is this function considering a nul value at the beginning?
Please do enlighten me O Wizards and Warlocks of Django.
For every Model (and ModelAdmin) you have, you should call register separately, for example:
admin.site.register(Question, QuestionAdmin)
admin.site.register(Choice)
The error about the 4 arguments is because register is a method of the default AdminSite instance, so the first argument is self. From the django code:
def register(self, model_or_iterable, admin_class=None, **options):
I've been going off of the documentation on the django-rest-swagger github page, more specifically the part called "How it works". It shows that you can define your own parameters for your rest api, and have those parameters show up in your swagger doc page.
The commenting example is something like:
"""
This text is the description for this API
param1 -- A first parameter
param2 -- A second parameter
"""
I can get this to work, but my issue is how to specify if the variable is required, its parameter type, and its data type. The github page shows an example image of how your swagger doc could look, and they have the information I just mentioned. But when I comment my custom parameters like the example shows, my parameters just show as parameter type: "query", data type: is blank, and it doesn't show "required".
The closest thing I have found to an answer was in this stackoverflow question. It seems like an answer provider is saying that django-rest-swagger generates its documentation by automatically inspecting your serializers (which is fine), and that modelserializers won't contain enough information for django-rest-swagger to properly derive the criteria I mentioned above. I get that it can't figure out this criteria but there must be some way for me to manually specify it then.
Am I correct that django-rest-swagger would only display what I want if I rewrote my modelserializers as just serializers? Is there no way for me to manually tell django-rest-swagger what a parameter's parameter type and data type should be, and if it's required?
I know I must be missing something here. I use class-based views and modelserializers that are almost identical to the examples in the django-rest-framework tutorials. It seems entirely possible that I'm just missing an understanding of "parameter types" in this context. My API is working great and I don't want to rewrite my modelserializers to serializers just so I can get better automatic documentation through swagger.
ModelSerializers are the right way to go with DR-Swagger. It can be a bit tricky chasing down exactly where the different Swagger fields are extracted from though, I often had to fall back to step-debugging through the page rendering process in order to figure out where things were coming from.
In turn:
Required? comes from the Field.required parameter (either set on the model or the Serializer field).
Description comes from the Field.help_text parameter.
In the new-style DRF serialization, the description text comes from the ViewSet's docstring. If you want method-specific docs, you need to override the docstring for individual methods, e.g. retrieve:
def retrieve(self, request, *args, **kwargs):
"""Retrieve a FooBar"""
return super().retrieve(request, *args, **kwargs)
One thing to note is that DR-Swagger migrated to using the new DRF schema logic in version 2.0 (with DRF version 3.5), which has a few rough edges still. I recommend sticking with DR-Swagger version 0.3.x, which (though deprecated) has more features and in my experience, more reliable serialization.
In most cases ModelSerializer is what you need, because it can be greatly customized to suit your needs. In ideal situation you should define all your constraints, like required attribute on a field, in your model class, but there are times when it's not architecturally possible, then you can override such a field in your ModelSerializer subclass:
from django.contrib.auth import get_user_model
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
first_name = serializers.CharField(required=True)
last_name = serializers.CharField(required=True)
class Meta:
model = get_user_model()
In the example above I serialize standard User model from Django and override required attributes so, that first_name and last_name are now required.
Of course, there are cases when it's hard or impossible to use ModelSerializer then you can always fallback to Serializer subclassing
In the code you have:
"""
This text is the description for this API
param1 -- A first parameter
param2 -- A second parameter
"""
Try:
""" This text is the description for this API
param1 -- A first parameter
param2 -- A second parameter
"""
I have found some python and/or Django plugins need the docstring's first line, which is the one with the opening three double-quotes to also be the line that starts the documentation. You might even want to try no space between the last double-quote and the T.
I have newfies dialer project, i would like to add a new field in Call Reports section.
I have lot of field that are unused in contact model. One of them can be used for this special id for my purpose.
How can i do that? Please help me anyone who familiar with newfies-dialer.
Newfies-Dialer is based on the Django framework, so it's good to know about Django to hack on the project.
You will notice in Newfies-Dialer that there is a template called: dialer_cdr/templates/dialer_cdr/voipcall_report.html
in which we display the data that is passed from the view.
So then in dialer_cdr/views.py, you have a view function which is in charge of rendering template and pass it some data. There, you can either modify voipcall_list object to add extra data to it, like info from the contact model, or pass an other object to data.
Here a link to the function handling this view: https://github.com/Star2Billing/newfies-dialer/blob/v2.12.2/newfies/dialer_cdr/views.py#L169
I am using the standard User model (django.contrib.auth) which comes with Django. I have made some of my own models in a Django application and created a relationship between like this:
from django.db import models
from django.contrib.auth.models import User
class GroupMembership(models.Model):
user = models.ForeignKey(User, null = True, blank = True, related_name='memberships')
#other irrelevant fields removed from example
So I can now do this to get all of a user's current memberships:
user.memberships.all()
However, I want to be able to do a more complex query, like this:
user.memberships.all().select_related('group__name')
This works fine but I want to fetch this data in a template. It seems silly to try to put this sort of logic inside a template (and I can't seem to make it work anyway), so I want to create a better way of doing it. I could sub-class User, but that doesn't seem like a great solution - I may in future want to move my application into other Django sites, and presumably if there was any another application that sub-classed User I wouldn't be able to get it to work.
Is the best to create a method inside GroupMembership called something like get_by_user(user)? Would I be able to call this from a template?
I would appreciate any advice anybody can give on structuring this - sorry if this is a bit long/vague.
First, calling select_related and passing arguments, doesn't do anything. It's a hint that cache should be populated.
You would never call select_related in a template, only a view function. And only when you knew you needed all those related objects for other processing.
"Is the best to create a method inside GroupMembership called something like get_by_user(user)?"
You have this. I'm not sure what's wrong with it.
GroupMembership.objects.filter( user="someUser" )
"Would I be able to call this from a template?"
No. That's what view functions are for.
groups = GroupMembership.objects.filter( user="someUser" )
Then you provide the groups object to the template for rendering.
Edit
This is one line of code; it doesn't seem that onerous a burden to include this in all your view functions.
If you want this to appear on every page, you have lots of choices that do not involve repeating this line of code..
A view function can call another function.
You might want to try callable objects instead of simple functions; these can subclass a common callable object that fills in this information.
You can add a template context processor to put this into the context of all templates that are rendered.
You could write your own decorator to assure that this is done in every view function that has the decorator.