Django Join in Admin View - python

I was wondering if someone could help me. I'm new to Django and python as a whole, so be nice!
I was wondering if I could make the ServerRole.name appear on the admin view of Server, code below:
Models.py
class ServerRole(models.Model):
server_role_id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=200, blank=True)
class Meta:
db_table = 'serverRole'
def __unicode__(self):
return smart_unicode(self.server_role_id)
class Server(models.Model):
server_id = models.IntegerField(primary_key=True)
server_role_id = models.IntegerField()
hostname = models.CharField(max_length=128)
ip = models.CharField(max_length=128)
is_online = models.IntegerField(blank=True, null=True)
date_added = models.DateField(blank=True, null=True)
status = models.CharField(max_length=200, blank=True)
def __unicode__(self):
return smart_unicode(self.server_id)
class Meta:
db_table = 'server'
Admin.py
class ServerAdmin(admin.ModelAdmin):
list_display = ('server_id', 'server_role_id', 'hostname', 'ip', 'is_online', 'date_added', 'status')
class ServerRoleAdmin(admin.ModelAdmin):
list_display = ('server_role_id', 'name')
admin.site.register(Server, ServerAdmin)
admin.site.register(ServerRole, ServerRoleAdmin)

Related

Error with Django fields ["'' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]

Can everyone be helpful in this situation:
I have a project in pythonanywhere host.
I created models and register in admin.But after make migrations command I write migrate and have this error:
File "/usr/lib/python3.7/site-packages/django/db/models/fields/init.py", line 1399, in to_python
params={'value': value},
django.core.exceptions.ValidationError: ["'' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
There is my code:
models.py
from django.db import models
class User(models.Model):
login = models.CharField(max_length=50)
passw = models.CharField(max_length=50)
email = models.CharField(max_length=50)
regdate = models.DateTimeField()
status = models.CharField(max_length=50)
class Category(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'Категория'
verbose_name_plural = 'Категории'
def __str__(self):
return self.name
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
admin.py
from django.contrib import admin
from .models import Category, Product
#admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = ['name', 'slug']
prepopulated_fields = {'slug': ('name',)}
#admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ['name', 'slug', 'price', 'available', 'created', 'updated']
list_filter = ['available', 'created', 'updated']
list_editable = ['price', 'available']
prepopulated_fields = {'slug': ('name',)}
please, somebody explain me my mistake.I stuck with this.....Thanks a lot!!!!!!!

Django Rest Framework requieres as not null look up field

I have two models:
class Album(models.Model):
code = models.CharField(max_length=10, primary_key=True, default=_create_access_code, verbose_name=_("Id"))
name = models.CharField(max_length=200, verbose_name=_("Name"))
description = models.TextField(null=True, blank=True, verbose_name=_("Description"))
company = models.ForeignKey(Company, on_delete=models.PROTECT, related_name='albums', verbose_name=_("Company"))
access_code = models.CharField(max_length=10, default=_create_access_code, verbose_name=_("Internal Use"))
class Meta:
verbose_name = _("Album")
verbose_name_plural = _("Albums")
def __str__(self):
return "[{}] {} ({})".format(self.pk, self.name, self.company.id)
class Photo(models.Model):
name = models.CharField(max_length=100, null=True, blank=True, verbose_name=_("Name"))
album = models.ForeignKey(Album, on_delete=models.CASCADE, related_name='photos', verbose_name=_("Album"))
photo = models.ImageField(verbose_name=_("Photo"))
class Meta:
verbose_name = _("Photo")
verbose_name_plural =_("Photos")
def __str__(self):
return "[{}] {}".format(self.pk, self.name)
I am trying to make a post to the ModelViewSet for model Albums, but I get an error indicating that field photos is required. Even the OPTIONS method indicates it es required.
How can I instruct DRF for not considering look up fields as required? Is it some serializer setting?
You can add required=False to fields in the serializer.
photos = PhotoSerializer(many=True, required=False)
Something like this. Can you post you serializers?

Issue with filter on Django

Please help to understand.
I have a django application with REST API. Everything working, but i wanna to add filter by client_id and here i received the issue.
There is a error message
invalid literal for int() with base 10: 'B123456'
And sure this is my code
api.py
class DatabaseByClientList(RetrieveUpdateDestroyAPIView):
serializer_class = DatabaseSerializer
def get_queryset(self):
client_id = self.kwargs['client_id']
return Database.objects.filter(client_id=client_id)
models.py
class Database(models.Model):
def __unicode__(self):
return unicode(self.id)
class Meta:
ordering = ['db_name']
client_id = models.ForeignKey(ClientInfo)
db_name = models.CharField(max_length=30, blank=True)
db_host = models.CharField(max_length=30, blank=True)
db_user = models.CharField(max_length=30, blank=True)
db_pass = models.CharField(max_length=30, blank=True)
db_type = models.CharField(max_length=30, blank=True)
serializer.py
class DatabaseSerializer(serializers.ModelSerializer):
client_id = serializers.SlugRelatedField(queryset=ClientInfo.objects.all(),
slug_field='access_id')
class Meta:
model = Database
fields = ('id', 'client_id', 'db_name', 'db_host', 'db_user', 'db_pass', 'db_type')
What's wrong? I made everything like in off documentation.
Thanks,
PS I tried
return Database.objects.filter(client_id=client_id)
but it doesnt help also
Added ClientInfo class
class ClientInfo(models.Model):
def __str__(self):
return self.access_id
class Meta:
ordering = ['id']
access_id = models.CharField(max_length=15, unique=True, blank=True)
username = models.CharField(max_length=15, unique=True, blank=True)
password = models.CharField(max_length=15, unique=True, blank=True)
name = models.CharField(max_length=15, unique=True, blank=True)
try to override get_queryset method this way.
class DatabaseByClientList(...):
model = Database
serializer_class = DatabaseSerializer
def get_queryset(self):
qs = super(DatabaseByClientList, self).get_queryset()
qs.filter(client_id=self.kwargs['client_id'])
return qs

django_select2, Model object is not iterable

I'm getting a "'Document' object is not iterable" error when this form is submitted. It works if 'document' is just taken from the model rather than written with the select2 package. It's extremely similar to the example code from the django_select2 package. I've tried making it Document.objects.all() instead, and that didn't work either.
models.py
class Individual(models.Model):
id = models.CharField(max_length=8, unique=True, verbose_name='ID')
first_name = models.CharField(max_length=50, null=True)
middle_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=100, null=True)
dob = models.CharField(max_length=15, blank=True)
suffix = models.CharField(max_length=25, blank=True, null=True)
time_stamp = models.DateTimeField(auto_now=True)
entered_by = models.CharField(max_length=50)
def _name(self):
return self.first_name + ' ' + self.last_name
class Meta:
db_tablespace = 'name_of_database'
def __unicode__(self):
return self.id
class Document(models.Model):
document_name = models.CharField(max_length=100)
class Meta:
db_tablespace = 'name_of_database'
def __unicode__(self):
return self.document_name
class DocLog(models.Model):
individual = models.ForeignKey('Individual', to_field='id', null=True)
fiscal = models.PositiveIntegerField(db_index=True)
document = models.ManyToManyField(Document, max_length=50,
verbose_name='Document Title')
date_received = models.DateField(editable=True, verbose_name='Date Received')
doc_notes = models.TextField(max_length=500, verbose_name='Document Notes')
time_stamp = models.DateTimeField(auto_now=True)
entered_by = models.CharField(max_length=50)
class Meta:
db_tablespace = 'name_of_database'
verbose_name = 'Document Log'
def __unicode__(self):
return self.individual.id
forms.py
from django import forms
from django_select2 import *
from .models import DocLog, Document
#Document Select2 class
class DocumentChoices(AutoModelSelect2Field):
queryset = Document.objects
search_fields = ['document_name__icontains',]
#New document form
class NewDocument(forms.ModelForm):
document = DocumentChoices()
class Meta:
model = DocLog
fields = ('individual', 'fiscal', 'document', 'date_received', 'doc_notes')
widgets = {
'individual': forms.HiddenInput(),
}
You defined ManyToManyField in your Model, in Modelform ManyToManyField is represented by django.forms.ModelMultipleChoiceField, which is a MultipleChoiceField whose choices are a model QuerySet.
So instead of using AutoModelSelect2Field you use AutoModelSelect2MultipleField
for your case
#Document Select2 class
class DocumentChoices(AutoModelSelect2MultipleField):
queryset = Document.objects
search_fields = ['document_name__icontains',]

Insert related field django rest framework

I have this simple model and I am having difficult in inserting related field of 'notes' through django rest framework.
class Student(models.Model):
firstName = models.CharField(max_length=100, blank=True, null=True)
lastName = models.CharField(max_length=100, blank=True, null=True)
prefLocation = models.ManyToManyField("Location", blank=True, null=True, related_name = 'prefLocation')
def __unicode__(self):
return self.firstName
class LocationRegion(models.Model):
regionName = models.CharField(max_length=100)
def __unicode__(self):
return self.regionName
class Location(models.Model):
locationName = models.CharField(max_length=100)
region = models.ForeignKey(LocationRegion, null=True, blank=True, related_name='locations')
def __unicode__(self):
return self.locationName
class Note(models.Model):
text = models.CharField(max_length=1000)
student = models.ForeignKey(Student, null=True, blank=True, related_name='notes')
def __unicode__(self):
return self.text
class StudentViewSet(viewsets.ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
I am unsure if I need to use ModelSerializer or generic Serializer. Validated_data doesn't return 'note' field in the deserialized data. I would appreciate any help with the serializer.
Thanks
Here are my serializers :
class StudentSerializer(serializers.ModelSerializer):
def create(self, validated_data):
def get_notes(self, obj):
return validated_data['note']
note = serializers.SerializerMethodField('get_notes')
return Candidate.objects.create(**validated_data)
class Meta:
model = Student
fields = ('id', 'firstName', 'lastName', 'note')
class NoteSerializer(serializers.ModelSerializer):
class Meta:
model = Note

Categories

Resources