Tastypie ModelResource fields based on methods - django-models

So Tastypie automatically generates the fields based on the fields of your Django Model (if you use ModelResource). I would like to use some methods from my Model as fields in the Resource. Is there a good way to do this in Tastypie? I know it's possible to do it using hydrate but that seems a bit hackish.

Try this:
class UserCharField(ModelResource):
stuff = fields.CharField(attribute='get_stuff_method', readonly=True)
class Meta:
queryset = User.objects.all()

Related

Is there a way to show images in a Wagtail Model Admin Record Listing page?

I have reviewed the question on Is there any way to show a field on a listing page in Wagtail admin? but my situation seems to similar but also different enough that that particular solution won't work for me. Instead of on the Page listing I wish to achieve a similar thing on the Model Admin listing and I would think this should be such a common requirement that I am picking that someone must have done this before I have attempted it.
I haven't really figured out how to even try anything to get started but what I have looked at is the modeladmin template tags under wagtail.contrib.modeladmin on GitHub but I am completely guessing.
Can anyone point me to which templates I need to modify and whether I need to modify any of the template tags and how to override anything I need to override?
There's no need to override templates for this - this is standard functionality in ModelAdmin. Adding extra fields to the listing is done by setting list_display on the ModelAdmin class:
class BookAdmin(ModelAdmin):
model = Book
list_display = ('title', 'author')
For displaying images, ModelAdmin provides ThumbnailMixin:
from wagtail.contrib.modeladmin.mixins import ThumbnailMixin
from wagtail.contrib.modeladmin.options import ModelAdmin
class BookAdmin(ThumbnailMixin, ModelAdmin):
model = Book
thumb_image_field_name = 'cover_image'
list_display = ('title', 'author', 'admin_thumb')
('admin_thumb' is a special-purpose field name provided by ThumbnailMixin, and should be used rather than the actual image field on your model - cover_image in this example.)

Parsing JSON and save values to database in django

Am getting a post request from a ussd gateway. The post has a body in JSON format["phone":"07xxxxxx":"shortCode":"*100#":"text":"1"]
I need to parse this JSON,get individual values and save in django as a record. How do I go about this?
next time please provide some code with what you tried so far. It shows other guys, that you at least tried to figure it out yourself. The problem you have is well documented in the DRF Tutorial and pretty straight forward. As you are new here on SO I will show it to you, but next time please put some more effort in it before writing a question.
You need four things:
-model
-serializer
-url
-view
The model represents the way your database table is built up. Based on your json data it could look like this:
models.py
from django.db import models
class ExampleModel(models.Model):
phone = models.CharField(max_length=10) # There are third party fields like django-phonenumber-field
shortCode = models.CharField(max_length=10)
text = models.CharField(max_length=50)
Then you need a serializer to handle your incoming json data and validate them. Create a serialzers.py file. In this example we use modelserializer, but there are some more like hyperlinkedmodelserializer or the serializer baseclass to create a fully custom serializer. For your purpose the modelserializer is a good way to go.
serializers.py
from rest_framework import serializers
from .models import ExampleModel
class ExampleModelSerializer(serializers.Modelserializer):
class Meta:
model = ExampleModel
fields = '__all__'
Now we need a view. For your use case you need a view that handles the post request. I will use the generics.CreateAPIView. There is a lot that goes under the hood. You should do the tutorial to understand how you get from the APIView to the generic Views. Keep in mind that the CreateAPIView only handles the creation of new items. There are more generic views to handle list, retrieve, update and so on.
views.py
from rest_framework import generics
from .serializers import ExampleModelSerializer
class MyCreateView(generics.CreateAPIView):
serializer_class = ExampleModelSerializer
The last thing you have to do is to define a url path.
urls.py
from django.urls import path
from yourappname import views
urlpatterns = [
path('example/', views.MyCreateView.as_view()),
]
All of the things I wrote are covered in the tutorial.In the future, if something is not working and you could not solve it, provide a short example and you will find people to help you. But they won't write the entire code for you like I did this time. The reason I did it was that you are new and it was pretty straight forward to write it down. Good luck for you project.

Non-model based serialization in Wagtail API response

I'm retrieving a list of pages via a custom API endpoint called sitemap. The goal of this endpoint is to return just the URL and last_updated flag so that I can generate a sitemap.xml file for my website. I can't apply a custom serializer to the model as I don't want to affect the normal pages API endpoint we're using.
Is it possible to apply a serializer to an API queryset rather than serializing it at the model level?
I could probably do this with a list comprehension, but a custom serializer feels like a better solution.
So it turns out that it's much easier than I thought. I created a custom serializer:
class SitemapSerializer(serializers.Serializer):
page_name = serializers.CharField()
url_slug = serializers.CharField()
Then applied that serializer to my APIEndpoint class:
class SitemapPagesAPIEndpoint(PagesAPIEndpoint):
base_serializer_class = SitemapSerializer
I think the thing that threw me off was that the property wasn't called serializer_class.

Django ModelForm save using db_alias param "using"

Is it possible to save ModelForm object data with db_alias different than "default"
my_form = MyModelForm(request.POST)
my_form.save(commit=True,using="db_alias")
as well as saving data with model instance?
Thank you.
Short Answer: Unfortunately ,you can't save the form that way. If you form doesn't contain ForeignKey or m2m fields (or you are controlling them yourself, for example using an autocompletefield, etc.), you can handle the object after the form:
_obj = _form.save(commit=False)
_obj.save(using=_db_alias)
Long answer: If you want the modelform to behave like a normal one with ForeignKeys and m2m-fields, something like:
# The form's foreign_keys and m2m-fields get the data from the db_alias database
# and evertyhing is sdisplayed correctly on the template.
_form = myModelForm(request, db_alias=_db_alias)
# The form saves to the correct DB and foreigns & M2ms are matched correctly in this DB
# _form.save()
Although this would be ideal, you just can't use this behaviour. There are many DB hooks that you need to alter in Django code to get this working. What I have done is to create a new modelform class from the base modelform, and get the (partial) functionality described before.
Hope this helps, and also hopping a better solution comes soon.

Django model defining list of URLFields

I'm pretty new to relational databases and this may be why I'm having this problem but I have a model - Post.
I want it to have variable number of URLs, however Django only seems to have the OneToManyField which requires a model (not a field - which URLField is).
In relational database design, the fields in a table are always scalar values. in your case, such a field would 'a url'. The way you get a collection to apply to a row, you join that row with the rows of another table. In django parlance, that would mean that you need two models, one for the Post objects, and another that links multiple urls with that post.
class Post(models.Model):
pass
class Url(models.Model):
url = models.URLField()
post = models.ForeignKey(Post)
myPost = Post.objects.all().get()
for url in myPost.url_set.all():
doSomething(url.url)
Now you can access urls through a urls member
But if you want to get the admin page for Post to also let you add urls, you need to do some tricks with InlineModelAdmin.
from django.db import models
from django.contrib import admin
class Post(models.Model):
pass
class Url(models.Model):
url = models.URLField()
post = models.ForeignKey(Post)
class UrlAdmin(admin.TabularInline):
model = Url
class PostAdmin(admin.ModelAdmin):
inlines = [UrlAdmin]
admin.site.register(Post, PostAdmin)

Resources