Parsing JSON and save values to database in django - django-models

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.

Related

What does it mean "to=" when creating model field in django?

Are those tree ways giving the same result/field, is there any other way?
class Message(models.Model):
user = models.ForeignKey(to=User)
user = models.ForeignKey(User)
user = models.ForeignKey("User")
Are those tree ways giving the same result/field
Yes, although the first requires to import a model named user, and is thus vulnerable to cyclic imports.
is there any other way?
The advised way is to make use of the settings.AUTH_USER_MODELĀ [Django-doc] to refer to the user model, than to use the User modelĀ [Django-doc] directly, so:
from django.conf import settings
class Message(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
For more information you can see the referencing the User model section of the documentation.

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.)

Tastypie ModelResource fields based on methods

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()

Cakephp - can i import the model and write the query in app_helper

Hi I plan to display images in view files through out the site
so can i import the model and write the query in app_helper file???
Are its a Good format to write find query in app_helper especially in cakephp?
Thanks
You can import models anywhere like this:
App::import('Model','MyModel'); $MyModel = new MyModel();
However it goes against all CakePHP conventions to directly access models in helpers. It would be more Cake-like to write a Component to do the model imports & queries and a helper to display the results and include the component & helper in your AppController if you want to use it everywhere in your site.

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