So , i have a django project with 2 apps
├───Blog
post
comment
└───User
profile
user (basic authentification and profile dashboards)
blog (having basic blog models : post,comment)
I need to give the users the possbility to create one or more blogs within the same project, but i don't see how i can treat an app like a model.
The only solution i figured out , is to add a foreign key to user id for every model withn the blog app.but is there a better way ?
I think you should do that:
# blog/models.py
class Blog(Model):
owner = ForeignKey(User, related_name="blogs")
name = Charfield()
class Post(Model):
blog = ForeignKey(Blog, related_name="posts")
#Other fields ...
class Comment(Model):
post = ForeignKey(Post, related_name="comments")
#Other fields ...
Related
we can submit foriegnkey data to models
through ModelForm
class BooksForm(forms.ModelForm):
class Meta:
model = Books
fields = "__all__"
where in templates we can add
{{form.author}} (author is foriegnkey field in books model)
Im aware that we can submit foriegnkey data using forms like this
but my question is.is there any way where we can submit a foriegnkey object which we have fetched using some other method (with or without form )
to a model(in my case its book)
Let me explain it in detail
lets say for instance there is a Search bar
when users search for author,
then the function fetches list of authors (choice field) to the user
where user can select and submit
which should get populated in the books model
there isnt any proper info related to this on web
all i could see is information on how to save data with Foriegnnkey using model form
any kind of insights is appreciated
I'm not 100% sure what your desired outcome is - this is how I understand your issue:
If you want to create a Book entry while passing an Author instance along you could set it as follows:
# models.py
class Author(models.Model):
name = models.CharField(max_length=50)
class Book(models.Model):
author = models.ForeignKey('Author', on_delete=models.CASCADE)
title = models.CharField(max_length=50)
# views.py
def example_view(request):
selected_author_instance = Author.objects.get(pk=1) # example query, adjust to your needs
# Create Book instance and pass author instance along
book_instance = Book.objects.create(
author=selected_author_instance,
title='example'
)
book_instance.save()
return render(...)
In the default Django Admin Site, if a model is registered with ForegingKey fields and those are included in readonly_fields (using the model property or the get_readonly_fields method) the value of the field is rendered with a link to the Change View, but this Doesn't work on a custom Django Admin Site.
E.g.: I have this two models:
class ModelA(models.Model):
field_a = models.CharField(max_length=50)
class ModelB(models.Model):
model_a = models.ForeignKey(ModelA, on_delete=models.PROTECT)
I registered in the default Django Admin Site:
admin.register(ModelA)
#register(ModelB)
class ModelBAdmin(admin.ModelAdmin):
model = ModelB
readonly_fields = ["model_a"]
So I get in the Change View of ModelB in the Admin the value of the field (str of the model) with a link to the Change View of the related model:
Link pointing to Chang View
But if I register the models in a Custom Admin Site, the link is not generated.
How can I extends my Custom Admin Site in order to generate those links?
PD1: I know I can code custom methods to build the links, but this is not a DRY way of do it and doesn't work well with get_readonly_fields method
PD2: If I register the related model (ModelA in the example) in the default Admin Site the link is genereted, but point to the default Admin Site, brokening the purpose of the Custom Admin Site.
I posted the same question in the official Django forum:
forum.djangoproject.com/t/9472/5
It has generated a ticket because is a missing line in the method get_admin_url in the helper class AdminReadOnlyField, The temporal solution is in the ticket: code.djangoproject.com/ticket/33077
PD: Why someone marks this post like a bad question? It has generates a ticket for a patch so it was a fair problem, this is my first question in StackOverflow and this is discouraging.
In Django, how would a database schema look like for a social media site like Instagram? For example, how would you make it so that one user can post multiple posts, and they can only have 1 profile?
I want to know what different tables I should have
I want to know how I would connect the tables
I want to know what I should write to link profile to posts(i.e. Foreign Key)
Any help is appreciated.
for profiles you add the user as a OneToOneField :
class Profile(models.model):
User=models.OneToOneField ()
Phone = models.CharField(default='', max_length=20)
Zip_code=models.IntegerField(default='')
image = models.ImageField(blank=True,upload_to='users_photos',)
and for post you add the user as a foreign key:
class Post(models.Model):
User=models.ForeignKey(
User,
on_delete=models.CASCADE,
)
....and some other fields you want to add
So I have been searching all around the internet for a full example of how to user AbstractUser when u have at least 2 different models. Didn't find anything conclusive.. at least that would work on latest version of Django (2.0.1).
I have 2 models, teacher and student, and registration needs to be different. Besides username, email, name and surname, I need for example, for the student, to upload a profile picture, email, phone, student_ID. And for teacher, bio, academic title and website. Did I start good ? What is the right approach ?
class Profile(AbstractUser):
photo = models.ImageField(upload_to='students_images')
email = models.EmailField()
phone = models.CharField(max_length=15, )
class Student(Profile):
student_ID = models.CharField(unique=True, max_length=14,
validators=[RegexValidator(regex='^.{14}$',
message='The ID needs to be 14 characters long.')])
def __str__(self):
return self.name
class Teacher(Profile):
academic_title = models.CharField(max_length=30)
bio = models.TextField()
website = models.URLField(help_text="E.g.: https://www.example.com", blank=True)
Your goals can be accomplished using a 'Profile' pattern. You don't necessarily need to use a custom user model for this. But you need to have a single common model to for authentication; you can use the builtin django user for this or a custom class... Your Student and Teacher models should be OnetoOne relationships. This is the recommended solution per the documentation.
If you wish to store information related to User, you can use a OneToOneField to a model containing the fields for additional information. This one-to-one model is often called a profile model, as it might store non-auth related information about a site user.
In your case, you may do something like this:
class StudentProfile(models.Model):
user = models.OneToOneField('User', related_name='student_profile')
# additional fields for students
class TeacherProfile(models.Model):
user = models.OneToOneField('User', related_name='teacher_profile')
# additional fields for teachers
Then you can create your registration forms based on these profile models.
class StudentResistrationForm(forms.ModelForm):
class Meta:
model = StudentProfile
fields = (...)
class TeacherRegistrationForm(forms.ModelForm):
class Meta:
model = TeacherProfile
fields = (...)
You can create the user instance to which the profile is related to at the same time you create the profile. You might do this with formsets, for example.
add
class Meta:
abstract = True
to profile model
and change AbstractUser to models.Model
I have 2 models, one is fk of another. I want when creating model filter fk on username creating. I know how to do this in sql, but don't understand how to do in django. I thought about api, am I right? Or I can do it in models or admin interface?
class Post_links( models.Model):
post_id = ParentalKey('Post')
username_can_see=models.CharField(max_length=30, default='')
class Post( models.Model):
some_link =models.CharField(max_length=50, default='')
now on creating new post when I ll check links I want to see only the links can see current user. How can I write this&
Check out the docs, they are quite helpful an easy to read. Here the Django queryset docs https://docs.djangoproject.com/en/1.11/topics/db/queries/
The queryset is the way to query the DB using the Django ORM