django -- Display foreign key relation value in django template - django-models

I have a ForeignKey relation between two models and I would like to show the related value in the web page
models.py
class ndcc_template(models.Model):
created_by = models.ForeignKey(to=myperso_user, related_name='created_by_user', verbose_name='Créé par', on_delete=models.PROTECT, blank=False, null=True)
class myperso_user(AbstractUser):
location = models.TextField(blank=False, null=True)
template.html
<h4>--- {{ ctx_form.created_by.value }} ---</h4>
At this point I would like to view the user_name and not the user_ID
Thanks a lot for your help

Related

How to link Wagtail and Django models together such that Wagtail field can be display in Django model admin

I am working on job application form functionality.
I have a Wagtail job description page with a link to application form.
So far I have built JobDetailPage model in Wagtail and JobAppliction Django model (as below):
class JobDetailPage(Page):
...
apply_form = models.ForeignKey(
JobAppliction,
on_delete=models.SET_NULL,
null=True)
job_title = models.CharField(max_length=100, blank=False, null=True)
...
class JobAppliction(models.Model):
# job_id = models.ForeignKey(
# 'careers.JobDetailPage',
# blank=False, null=True,
# on_delete=models.SET_NULL,
# related_name='position', )
name = models.CharField(
max_length=255, blank=False, null=True)
email = models.EmailField(blank=False, null=True)
...
The same application form can be used by a number of job offers.
How do I link these two models together such that in the admin I can tell which instance of job application was submitted which position?
My admin model is as below:
class JobApplictionAdmin(ModelAdmin):
model = JobAppliction
menu_label = "Applications"
list_display = ('title', 'email')

Got AttributeError when attempting to get a value for field `people` on serializer `commentsSerializer`

I am building a blog website and I am using Django rest framework
I want to fetch top 2 comments for a particular post along with their related data such as user details.
Now I have user details in two models
User
People
and the comments model is related to the user model using foreign key relationship
Models ->
Comments
class Comment(models.Model):
comment = models.TextField(null=True)
Created_date = models.DateTimeField(auto_now_add=True)
Updated_date = models.DateTimeField(auto_now=True)
post = models.ForeignKey(Post, on_delete=models.CASCADE,
related_name='comments_post')
user = models.ForeignKey(User, on_delete=models.CASCADE,
related_name='comments_user')
The People model is also connected to the user model with a foreign key relationship
People Model ->
class People(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='people')
Name = models.CharField(max_length=255,null=True)
following = models.ManyToManyField(to=User, related_name='following', blank=True)
photo = models.ImageField(upload_to='profile_pics', blank=True,null=True)
Phone_number = models.CharField(max_length=255,null=True,blank=True)
Birth_Date = models.DateField(null=True,blank=True)
Created_date = models.DateTimeField(auto_now_add=True)
Updated_date = models.DateTimeField(auto_now=True)
for fetching the comments I am using rest-framework and the serializers look like this
class UserSerializer(serializers.Serializer):
username = serializers.CharField(max_length=255)
class peopleSerializer(serializers.Serializer):
Name = serializers.CharField(max_length=255)
class commentsSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
comment = serializers.CharField(max_length=255)
Created_date = serializers.DateTimeField()
user = UserSerializer()
people = peopleSerializer()
The query to fetch the comments look like this ->
post_id = request.GET.get('post_id')
comments = Comment.objects.filter(post_id=post_id).select_related('user').prefetch_related('user__people').order_by('-Created_date')[:2]
serializer = commentsSerializer(comments, many=True)
return Response(serializer.data)
I am getting this error ->
Got AttributeError when attempting to get a value for field `people` on serializer `commentsSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Comment` instance. Original exception text was: 'Comment' object has no attribute 'people'.
Unable to find a way out.
The source is user.people, not people, so:
class commentsSerializer(serializers.Serializer):
# …
people = peopleSerializer(source='user.people')
In the .select_related(…) [Django-doc] to can specify user__people: this will imply selecting user and will fetch the data in the same query, not in an extra query as is the case for .prefetch_related(…) [Django-doc]:
post_id = request.GET.get('post_id')
comments = Comment.objects.filter(
post_id=post_id
).select_related('user__people').order_by('-Created_date')[:2]
serializer = commentsSerializer(comments, many=True)
return Response(serializer.data)
Note: normally a Django model is given a singular name, so Person instead of People.
Note: It is normally better 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. For more information you can see the referencing the User model section of the documentation.
Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be: created_date instead of Created_date.

Model needs to have a value for field "id" before this many-to-many relationship can be used

I am unable to save a model in Django with a ManyToManyField while inside Django Admin because I don't know how to create the ID in the database first, and then save the data. It's trying to do both at the same time, but I have to separate the two processes, and I don't know how.
I've gone five full pages deep on Google, and there are tons of answers, but nothing that I can relate to my specific use case.
The error message I get when submitting the form that has the ManyToManyField in it:
ValueError: "<Clients: Lowe, Robb>" needs to have a value for field "id" before this many-to-many relationship can be used.
Here's the model I'm using:
class BusinessInfo(models.Model):
id = models.IntegerField(primary_key=True, editable=False)
business_name = models.CharField(blank=True, null=True, max_length=50)
business_address = models.CharField(blank=True, null=True, max_length=50)
business_city = models.CharField(blank=True, null=True, max_length=50)
business_state = models.CharField(choices=STATE_SELECT, null=True, blank=True, max_length=50)
related_person = models.ManyToManyField('Clients', related_name='related_person', null=True, blank=True)
business_zip = models.IntegerField(blank=True, null=True)
business_contact_name = models.CharField(blank=True, null=True, max_length=50)
business_phone = PhoneField(null=True, help_text='Phone Number | <span style="color: red;">Required</span>')
business_email = models.CharField(blank=True, null=True, max_length=50)
And specifically the field I created:
related_person = models.ManyToManyField('Clients', related_name='related_person', null=True, blank=True)
I've also attempted to use django-modelcluster to no avail.
I'm pretty new to Django so if anyone can help me out and use explicit code that would help me a great deal. Thank you!

How to reference a Autofield from one model to another

I need some input about referring an Autofield into another model.
I tried making a foreign key, but I am not sure if the syntax is right
I have a main model class with id as Autofield
class Metadataform(models.Model):
id = models.AutoField(primary_key=True)
Authors_Name = models.CharField(max_length=500, blank=True, null=True)
Then I have a upload class
(I basically want to fetch the same id from the main model into the Meta_id in the uploadmeta model)
class uploadmeta(models.Model):
Meta_id = models.ForeignKey('Metadataform',on_delete=models.CASCADE, null=True)
Authors_Name = models.CharField(max_length=500, blank=True, null=True)
tar_gif = models.FileField(upload_to='mnt/storage/DB-Data/')
def __str__(self):
return self.Meta_id
Your approach is indeed correct, although you do not need to add a primary key yourself. Django does that. Furthermore your code does not really follows the naming conventions.
You can implement this as:
class MetadataForm(models.Model):
author_name = models.CharField(max_length=500, blank=True, null=True)
class UploadMeta(models.Model):
metadata_form = models.ForeignKey('MetadataForm', on_delete=models.CASCADE, null=True)
tar_gif = models.FileField(upload_to='mnt/storage/DB-Data/')
Furthermore it might not make much sense to set blank=True. This means that by default that field will not show up in forms. null=True not be necessary as well, since that means you can add None (in the database NULL) to that field.
The __str__ of a model typically includes some field value(s) of that model. Since by only using values from a ForeignKey relation, it means two or more UploadMetas that have different values, have the same textual representation if these refer to the same MetaDataForm?
It is not very clear to me eather why you defined a field named Authors_Name in the UploadMeta as well. If that is the same as the metadata_form's author_name, then you better do not include an extra one since that creates data duplication.
Perhaps it is better to make an Author model as well, and let MetadataForm refer through a ForeignKey to the author of that MetadataForm model.

Place players only on one team with relational table

After going through several stackoverflows I still have yet to find something that solves this. I'm hoping it's just syntax as I'm a novice.
Admin:
from django.contrib import admin
from team_editor.models import Player, Team, TeamMembers
class PlayerInline(admin.StackedInline):
model = Player
class TMAdmin(admin.ModelAdmin):
inlines = (PlayerInline,)
# Register your models here.
admin.site.register(Team)
admin.site.register(Player)
admin.site.register(TeamMembers, TMAdmin)
Models:
class Player(models.Model):
firstName = models.CharField(max_length=30)
lastName = models.CharField(max_length=30)
class Team(models.Model):
teamName = models.CharField(max_length=30, unique=True)
class TeamMembers(models.Model):
team = models.ForeignKey(Team)
player = models.ForeignKey(Player, unique=True)
Error: class has no foreign key to class
I am using this setup since I want to view players on a team easily and change teams from one team to another (never on multiple)
Moved to many to many relation in team and dropped teammember table:
players = models.ManyToManyField(Player, blank=True, null=True)

Resources