Sorry i'm a beginner in django and python..i create a project and i've a models.py like this:
from django.db import models
class Shoes(models.Model):
type = models.CharField(max_length=30)
start_date = models.DateTimeField()
number = models.IntegerField()
def __unicode__(self):
return str(self.id)
class Meta:
verbose_name_plural = "Shoes"
class Bottom(models.Model):
type = models.CharField(max_length=30)
finish = models.BooleanField()
size = models.IntegerField()
def __unicode__(self):
return str(self.id)
class Meta:
verbose_name_plural = "Bottoms"
class Relation(models.Model):
shoes = models.OneToOneField(Shoes)
bottom = models.ForeignKey(Bottom)
class Meta:
verbose_name_plural = "Relations"
I want to serialize theese classes in json..sorry i need to understand where and how write the specific code to do it..
I wrote already a file views.py and a file.html to view a web page with table of theese objects, but now because i need to write a jquery function that allow to update the web page automatically when i add a new object, I think that we need to serialize the data in json before doing so.
Thanks and bear with me if I said something idiotic because i'm a really beginner in this field..
You want to serialize classes? You want to serialize objects! :) In order to serialize Django objects you can use built-in mechanisms. Read this:
https://docs.djangoproject.com/en/dev/topics/serialization/
For example you can do this like this:
from django.core import serializers
from django.http import HttpResponse
def someView(request):
shoes_from_db = Shoes.objects.all()
json = serializers.serialize(
'json', shoes_from_db, fields=('type','start_date', 'number')
)
return HttpResponse(json, content_type="application/json")
Related
I am querying select related between two models Requirements and Badge Requirement has a related badge indicated by badge_id Models are,
class Badge(models.Model):
level = models.PositiveIntegerField(blank=False, unique=True)
name = models.CharField(max_length=255, blank=False , unique=True)
description = models.TextField(blank=True)
class Meta:
verbose_name = _("Badge")
verbose_name_plural = _("Badges")
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("Badge_detail", kwargs={"pk": self.pk})
""" Requirement Model for requirements """
class Requirement(models.Model):
number = models.PositiveIntegerField(blank=False)
badge = models.ForeignKey(Badge, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
description = models.TextField(blank=True)
class Meta:
verbose_name = _("Requirement")
verbose_name_plural = _("Requirements")
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("Requirement_detail", kwargs={"pk": self.pk})
In My view I try to join both tables and retrieve. It is,
""" ajax requirements in requirements table """
def get_requirements(request):
requirements = Requirement.objects.all().select_related('badge').values()
print(requirements)
return JsonResponse(list(requirements), safe=False)
The result is,
to the frontend,
to the backend,
Why does it not give me both tables' values?
Best way to achieve that is using Serializers which are the key component to deal with transforming data from models to JSON and the inverse:
To use this approach you can create the following serializers:
yourapp.serializers.py
from rest_framework.serializers import ModelSerializer
from yourapp.models import Requirement, Badge
class BadgeSerializer(ModelSerializer):
class Meta:
model = Badge
fields = '__all__'
class RequirementSerializer(ModelSerializer):
badge = BadgeSerializer()
class Meta:
model = Requirement
fields = '__all__'
After that you should go to your views.py file and do the following changes:
from yourapp.serializers import RequirementSerializer
def get_requirements(request):
reqs = Requirement.objects.select_related('badge')
return JsonResponse(RequirementSerializer(reqs, many=True), safe=False)
In this way you will have a more flexible way to add or remove fields from the serializer, and your application is also going to be more decoupled and easy to maintain.
I am making a Blog where I want for the home page to show only the first 100 characters of each post.
My point is to make better use of space. If a person want to read a post, that person can just click to read it.
I have some ideas on how to do it, but I think they won`t work or are inefficient:
To create a subclass on blog models.py where I would inherit the Post class, save the first hundred characters of each content to a list and make a loop to save each list on the database;
To place a instruction on blog views.py 'FirstPageView' class where it would only exhibit the first hundred characters.
The 'Post' and 'FirstPageView' mentioned classes are as follows:
on 'blog/views.py':
from django.views.generic import ListView
class FirstPageView(ListView):
model = Post
template_name = 'Blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 6
on 'blog/models.py':
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, models.SET_NULL, blank=True, null=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
So what would be the most efficient way to make those previews?
You can use built-in template tags:
{{ posts.content|truncatechars:100 }}
Hi I need really very very simple example. First my models:
#This my student models
from django.db import models
SEX_CHOICES= (
('M', 'Male'),
('F', 'Female'),
)
class Students(models.Model):
student_name = models.CharField(max_length=50)
student_sex = models.CharField(max_length=8, choices=SEX_CHOICES)
student_city = models.Charfield(max_length=50)
student_bio = models.TextField()
def __unicode__(self):
return self.student_name
O.K. Let see my ClassRooms Model.
#This my ClassRooms models
from django.db import models
from myproject.students.models import *
class ClassRooms(models.Model):
class_number= models.CharField(max_length=50)
class_student_cities = models.ForeignKey(Students)
class_year = models.DateField()
def __unicode__(self):
return self.class_number
How can i show in the class_student_cities area the Students.student_city datas? I guess that about django-admin area. When i do it withclass_student_cities = models.ForeignKey(Students) i just see in that area the Students.student_name data (ex: John Smith). I want to see JUST Students.student_cities data (ex: NewYork). Can you give me a little example?
Should i use something like that:
class_student_cities = models.ForeignKey(Students.student_cities)
Many Thanks!
Try redifinition unicode method.
def __unicode__(self):
return self.student_city
So you'll see in the field student city.
Well, I tried to remake your application to set data with forms class. Something like this in admin.py in your application:
from django.contrib import admin
from django import forms
from myapp.models import *
class ClassRoomsAdminForm(forms.ModelForm):
class Meta:
model = ClassRoom
def __init__(self, *arg, **kwargs):
super(ClassRoomsAdminForm, self).__init__(*arg, **kwargs)
self.fields[' class_student_cities'].choices = [(csc.id,csc.student_city) for csc in Students.objects.all()
class ClassRoomsAdmin(admin.ModelAdmin):
form = ClassRoomsAdminForm
admin.site.register(ClassRooms,ClassRoomsAdmin)
Maybe you'll need to fix something, but I hope it will work. You will set init function to your forms, so in admin panel you set all choices to everything you keep in your Students model. csc.id you'll need to make this object iterable (cities aren't unique) and then you can choose everything from Students model to set in the field.
I'm creating a Django app where all the models can be related to each other in an order set by the user. I'm setting all this up using GenericForeignKeys. The kicker is that I need to be able to support multiple collections of these types of relationship/admin. So one object can have a more than one collection of related objects.
Does anyone know of a good GenericForeignKey widget for this situation? Preferably, it would be an autocomplete search that populates the admin form since I can end up having a large number of objects.
Here is the code for my app to get a better idea of what I mean.
from django.contrib import admin
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django import forms
# Models
class Base(models.Model):
title = models.CharField(max_length=255)
class Meta:
abstract = True
def __unicode__(self):
return self.title
class Related(Base):
""" A generic relationship model for relating resources.
"""
order = models.IntegerField(blank=True, null=True)
limit = models.Q(model = 'Apple') | models.Q(model = 'Orange') | models.Q(model = 'Pear')
content_type = models.ForeignKey(ContentType, related_name="related_%(class)s")
object_id = models.PositiveIntegerField(db_index=True)
object = generic.GenericForeignKey()
related_content_type = models.ForeignKey(ContentType, related_name="related_related_%(class)s", limit_choices_to = limit)
related_object_id = models.PositiveIntegerField(db_index=True)
related_object = generic.GenericForeignKey('related_content_type', 'related_object_id')
class Meta:
ordering = ('order',)
abstract = True
def __unicode__(self):
return self.object.title
class FreshFruit(Related):
pass
class OldFruit(Related):
pass
class Apple(Base):
pass
class Orange(Base):
pass
class Pear(Base):
pass
# Admin classes
class FreshFruitInline(generic.GenericStackedInline):
model = FreshFruit
extra = 1
# Admin classes
class OldFruitInline(generic.GenericStackedInline):
model = OldFruit
extra = 1
class AppleAdmin(admin.ModelAdmin):
inlines = [FreshFruitInline, OldFruitInline,]
admin.site.register(Apple, AppleAdmin)
class OrangeAdmin(admin.ModelAdmin):
inlines = [FreshFruitInline, OldFruitInline,]
admin.site.register(Orange, OrangeAdmin)
class PearAdmin(admin.ModelAdmin):
inlines = [FreshFruitInline, OldFruitInline,]
admin.site.register(Pear, PearAdmin)
I've searched and searched, and found widgets that do this for a ManyToMany relationship, but nothing for my situation.
Thanks for taking the time to look at this.
Have a look at Grappelli's generic foreign key widget, which works well:
django-grappelli/generic_2_2
I need to filter database by default every time that I see it (when I save changes or when I open database first time).
Can anybody tell me how to do it?
This is possible with custom custom Managers:
Say you have a class called Book:
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
And you want the admin pages for book objects to only show books by Roald Dahl, then you can add a custom manager:
class DahlBookManager(models.Manager):
def get_query_set(self):
return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl')
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
objects = models.Manager()
dahl_objects = DahlBookManager()
Then you just need to specify that your ModelAdmin should use the dahl_objects manager, which is explained here.
Here is my models.py:
from django.db import models
class DahlBookManager(models.Manager):
def get_query_set(self):
return super(DahlBookManager, self).get_query_set().filter(processed=False)
class Book(models.Model):
book_name = models.CharField('book',max_length=1000,null=True, blank=True)
url = models.CharField(max_length=1000,null=True, blank=True)
processed = models.BooleanField('Done',)
def __str__(self):
return u'%s' % (self.book_name)
def url1(self):
return '%s' % (self._url, self.url)
site_url1.allow_tags = True
class Admin:
pass
class Meta:
db_table = 'books'
objects = models.Manager()
dahl_objects = DahlBookManager()
here is my admin.py:
from django.contrib import admin
from mybooks.booksdb.models import Book
from django import forms
admin.autodiscover()
class BookAdmin(admin.ModelAdmin):
def queryset(self,request):
qs=self.model.objects.get_query_set()
ordering = self.ordering or ()
if ordering:
qs=qs.order_by(*ordering)
return qs
....
No filter by default. Where is my miss?