Custom Field view in inline admin form - python

I am using inline model admin and many to many relation. I have two model classes User and Videodata and i linked them with many to many relation. Below is my models
class User(models.Model):
user_id = models.CharField(max_length=40,unique=True)
user_name = models.CharField(max_length=40)
user_email = models.EmailField()
user_city = models.CharField(max_length=40)
videos_watched = models.ManyToManyField('VideoData', through='WatchedVideo')
class Meta:
ordering = ['user_id']
verbose_name = 'User MetaData'
verbose_name_plural = 'Users MetaData'
def __unicode__(self):
return self.user_id
class VideoData(models.Model):
video_id = models.CharField(max_length=40,unique=True)
video_name = models.CharField(max_length=40)
class Meta:
verbose_name = 'User_Video MetaData'
verbose_name_plural = 'Users_Video MetaData'
def __unicode__(self):
return self.video_id
class WatchedVideo(models.Model):
user = models.ForeignKey(User, to_field = 'user_id')
videoData = models.ForeignKey(VideoData, to_field = 'video_id')
time = models.PositiveIntegerField(null = True)
In User table i see video data but with video_id but i want video_name to be displayed there. I am attaching a link of current output.
https://drive.google.com/open?id=0B0JOKpp3abpzOFN3LVg0WEs3a0k
You can see in above pic video id is there but i want video name. How can i do that??

You can display the name changing the method __unicode__ of VideoData to:
def __unicode__(self):
return self.video_name
EDIT: Add method __str__ to VideoData:
def __unicode__(self):
return self.video_id
def __str__(self):
return self.video_name

I displayed names with following change:
def __unicode__(self):
return self.video_name
def __str__(self):
return self.video_id

Related

How can i fix "too many values to unpack" value error while file uploading in model serializer

I'm facing below issue in ModelSerializer file upload.
Issue 1) I'm trying to upload files using ModelSerializer. I have two models BlogFilesSerializer and BlogSerializer. when trying to upload a file it shows too many values to unpack error and I know its meaning why is this occurring but don't know how to handle these exceptions.
serializers.py
class BlogFilesSerializer(ModelSerializer):
created_at = serializers.SerializerMethodField()
updated_at = serializers.SerializerMethodField()
class Meta:
model = BlogFilesModel
fields = ('blog_files_id', 'blog', 'path',
'created_at', 'updated_at')
class BlogSerializer(ModelSerializer):
blog_files = serializers.SerializerMethodField()
uploaded_files = serializers.FileField(required=True, source='*')
blog_created_at = serializers.SerializerMethodField()
def get_blog_files(self, obj):
info = BlogFilesSerializer(BlogFilesModel.objects.filter(
blog=obj).order_by('-pk'), many=True)
if info.data:
for i in info.data:
user_detail = User.objects.get(pk=obj.user.id)
i.__setitem__('user_detail', UserSerializer(user_detail).data)
if i.get('user_detail'):
try:
del i['user_detail']['password']
except expression as identifier:
pass
return info.data
def get_blog_created_at(self, obj):
formatted_date = obj.created_at.strftime("%d-%m-%Y")
return formatted_date
class Meta:
model = BlogModel
fields = ('blog_id', 'user', 'title', 'content',
'status',
'blog_files', 'blog_created_at',
'uploaded_files'
)
def create(self, validated_data):
instance = BlogModel.objects.create(**validated_data)
return instance
views.py
class BlogViewSet(viewsets.ModelViewSet):
queryset = BlogModel.objects.all()
lookup_field = 'blog_id'
serializer_class = BlogSerializer
parser_classes = (MultiPartParser, FormParser,FileUploadParser)
models.py
class BlogModel(models.Model):
BLOG_STATUS = (
('PUBLISH', 'Publish'),
('DRAFT', 'Draft'),
)
blog_id = models.AutoField(primary_key=True)
user = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='blogs')
title = models.CharField(max_length=255)
content = models.TextField(blank=True, null=True)
status = models.CharField(max_length=7, choices=BLOG_STATUS)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta():
db_table = 'blogs'
verbose_name = 'Blog'
verbose_name_plural = 'Blogs'
def __str__(self):
return self.title
#property
def files(self):
return 'something'
def blog_directory_path(instance, filename):
return 'uploads/blogs/{}'.format(filename+str(datetime.now()))
class BlogFilesModel(models.Model):
blog_files_id = models.AutoField(primary_key=True)
blog = models.ForeignKey(
BlogModel, on_delete=models.CASCADE, related_name='blogs',blank=True)
path = models.FileField(blank=False, null=False,upload_to=blog_directory_path)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta():
db_table = 'blog_files'
verbose_name = 'Blog'
verbose_name_plural = 'Blogs'
def __str__(self):
return str(self.path)
Issue 2) i'm also unable to select multiple files for upload in BlogSerializer and in field uploaded_files = serializers.FileField(required=True, source='*') and their is no detailed explanation is DRF documentation. How can i add multple attribute to file field.
EDIT 1: I tried and got till here in def to_internal_value(self, data): the field.source_attrs = [] their is no key so i'm getting this error.
in my ModelSerializer i tried this uploaded_files = serializers.FileField(required=True, source='files') added files as property to BlogModel now i'm getting 'Error = files' is an invalid keyword argument for this function can someone guide me here.
Hope is have explained my problem well.
Thank you.

Django show only the values in the selected field

So in my models.py I have this:
class Profesie(models.Model):
titlu = models.CharField(max_length=100)
def __str__(self):
return self.titlu
class Domeniu(models.Model):
profesie = models.ForeignKey(Profesie)
titlu = models.CharField(max_length=100)
def __str__(self):
return self.titlu
class Anunt(models.Model):
titlu = models.CharField(max_length=150)
user = models.ForeignKey('auth.User', related_name='anunturi')
profesie = models.ForeignKey(Profesie)
domeniu = models.ForeignKey(Domeniu)
In the form when the user selects the field profesie, and then domeniu, for the domeniu field it should only display the values that are in the Profesie table. How can I accomplish that?

how to access auto increment id of any model using form in django?

models.py
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author, blank=True)
publisher = models.ForeignKey(Publisher, blank=True, null=True)
def __unicode__(self):
return self.title
forms.py
class Books(forms.ModelForm):
class Meta:
model = Book
fields = ('title', 'authors', 'publisher',)
class Authors(forms.ModelForm):
class Meta:
model = Author
fields = ('first_name', 'last_name', 'email',)
class Publishers(forms.ModelForm):
class Meta:
model = Publisher
fields = ("id","name", 'address', 'city', 'state_province', 'country',)
views.py
def demo(request):
form1 = Books(request.POST)
form2 = Authors(request.POST)
form3 = Publishers(request.POST)
if (form1.is_valid() & form2.is_valid() & form3.is_valid()):
form3.save()
form2.save()
// Here I want to access id of just saved data of Model Publisher and Model Authors
form1.cleaned_data['publisher'] = form3.data['id']
return render(request, 'files/demo.html', {'form1': form1, 'form2': form2, 'form3': form3})
In Above code I want to save all data of all models in single view But errro is that Book model has ForenignKey relation with Publisher and Publisher doens't not have any unique data to identify the ID of just saved data. So My real question is that how can I access the Publisher and Author ID that data is saved using `
form3.save() and form2.save()
`I'm very confused to save multiple model data with same time with handle forenignkey relation between them.
save() returns the object, so you just need to do
publisher_obj = form3.save()
author_obj = form2.save()
book_obj = form1.save(commit=False)
book_obj.publisher = publisher_obj
book_obj.save()
book_obj.authors.add(author_obj)
and remove the 'id' from the form. You don't need it.

Invalid literal for int() with base 10: 'marlm'

I have to create a view which returns me the posts of a particular owner/author
This error in coming from view bellow. I know this is a simple thing that I am missing. Please help me on this: (marlm is the ID I created to test)
def view_by_owner(request):
user = request.user.username
posts_owner = Post.objects.filter(owner=user)
return render_to_response('view_post.html',{'view_owner':posts_owner})
Models:
from django.db import models
from django.db.models import permalink
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
datposted = models.DateTimeField('date posted')
category = models.ForeignKey('Category')
owner = models.ForeignKey('UserProfile')
def __str__(self):
return '%s' % self.title
class Category(models.Model):
title = models.CharField(max_length=100)
def __str__(self):
return self.title
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User)
# The additional attributes we wish to include.
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', null=True)
# Override the __unicode__() method to return out something
def __unicode__(self):
return self.user.username
class Logout(User):
force_logout_date = models.DateTimeField(null=True, blank=True)
The problem is that owner is a foreign key to User, not the value of the user name. To lookup by that, you will need to span that relationship, like so:
posts_owner = Post.objects.filter(owner__user__username=user)
Or, more simply, you could do this:
posts_owner = Post.objects.filter(owner__user=request.user)

Django: Product attributes and custom fields form in product page

I just start to learn Django and I want to create a Product model with attributes, custom fields and custom field options. Custom field options exemple:
Line 1: [YOUR TEXT] | Custom field options: [FONT] [FONT SIZE] [...]
Line 2: [YOUR TEXT] | Custom field options: [FONT] [FONT SIZE] [...]
So I've created this models:
from django.db import models
from django.utils import timezone
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
sku = models.CharField(max_length=100)
slug = models.CharField(max_length=100)
price = models.DecimalField(max_digits=6, decimal_places=2)
active = models.BooleanField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
class ProductMeta(models.Model):
product = models.OneToOneField('Product')
title = models.CharField(max_length=100)
description = models.TextField(max_length=250)
class ProductImage(models.Model):
def upload_path(self, filename):
return 'static/uploads/images/%s%s' % (timezone.now().strftime('%Y/%m/%d/%Y%m%d_'), filename)
product = models.ForeignKey('Product')
name = models.CharField(max_length=100)
default = models.BooleanField()
image = models.ImageField(upload_to=upload_path)
def __unicode__(self):
return self.name
class ProductCharacteristic(models.Model):
product = models.ForeignKey('Product', related_name="characteristics")
name = models.CharField(max_length=100)
value = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductAttribute(models.Model):
category = models.ForeignKey('ProductAttributeCategory')
products = models.ManyToManyField('Product', related_name="attributes")
name = models.CharField(max_length=100)
ordering = ['-category']
def __unicode__(self):
return u'%s : %s' % (self.category, self.name)
class ProductAttributeCategory(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductAttributeValue(models.Model):
attribute = models.ForeignKey('ProductAttribute', related_name="values")
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductCustomField(models.Model):
product = models.ForeignKey('Product', related_name="custom_fields")
name = models.CharField(max_length=100)
description = models.TextField(max_length=250)
def __unicode__(self):
return self.name
class ProductCustomFieldOption(models.Model):
fields = models.ManyToManyField('ProductCustomField', related_name="options")
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductCustomFieldOptionValue(models.Model):
option = models.ForeignKey('ProductCustomFieldOption', related_name="values")
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
But now I don't know how to create the form in product details page in which the user can choose the product attributes (color, size...) and the product custom fields (and custom fields options). I've tried a lot of things but no results.
Can you help me please? :)
your question is unclear to me and your even more confusing. However see this if it helps
In your models.py
from django.db import models
from model_utils import Choices
colour_choices = ('Blue', 'Green')
class Product(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
reuturn self.name
class ProductAttributes(models.Model):
product = models.Foreignkey(Product, related_name='products')
colour = models.CharField(choices=Choices(*colour_choices))
In your forms.py
from django import forms
from .models import Product, ProductAttributes
class ProductForm(forms.ModelForm):
class Meta:
model = Product
class ProdductAttributesForm(forms.ModelForm):
class Meta:
model = ProductAttributes
Write your views.py, urls.py and template accordingly
this method will give you a text box to enter products and drop-down for choosing color.
Hope it helped!

Categories

Resources