I have a model like
class Info(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
class Detail(models.Model):
info = models.ForeignKey(Info)
...
In admin when I add Detail I want all the fields of Info model as a form field without + sign just as normal fields.
How is this possible ?
its not possible as when you add some Detail, their info should already exist in Detail model,when parents model info have data, then Detail allow to add data with respect to parent model Detail.
Related
Actually I'm creating an employee management system project using django rest api.
Now i have created my own custom models like shown below, i want to create the register employee with the below models. But how can i set the password field for login, since I haven't included in my fields. I've attached my models and serializer. Please do help for me. I'm beginner
Class Employee (models.Model):
name = models.CharField(max_length=50, unique=True, verbose_name='None')
email = models.EmailField(verbose_name='Email')
department = models.CharField(max_length=30, unique=False, verbose_name='Departamento')
(And many more details like personal email,contact, and many)
# Function used to display the employee's name in the admin page
def __str__(self):
return self.name
My serializer class is
class Employee DetailsSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
Fields = [__all__]
My views be like, i want to create register view, since i dont have password in my model, how to create password field to my above shown register field,
Whatever maybe my register field should contain all those above details. I'm scratching my head here.please someone help
Yes, you can add a password field in your Employee model but you are requested not to do it because Django already provided this type of facility. Just you have to know How to use it. Try to extend the existing User model from django.contrib.auth.models.User.Let's organize your Employee model.
from django.contrib.auth.models import User
class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
#name = models.CharField(max_length=50, unique=True,
verbose_name='None')
#email = models.EmailField(verbose_name='Email')
department = models.CharField(max_length=30, unique=False,
verbose_name='Departamento')
#property
def name(self):
return "{0} {1}".format(self.user.first_name,
self.user.last_name)
No need to add an email field because this field already exists in the User model and the name field can be a property that retrieves data from the user model and the rest of the code will be unchanged. So you are concerned about the password field and it also exists in the User model.
Please check out this repo and it might help you.
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(...)
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 two classes in my model.py
class User(models.Model):
name = models.CharField()
phone = models.CharField()
# Other common fields
class Customer(User):
payment = models.CharField()
user__id = models.OneToOneField('User', db_column='id', primary_key=True)
class Company(User):
address = models.CharField()
user_id = models.OneToOneField('User', db_column='id', primary_key=True)
When I use the admin of Customer/Company it includes all User fields, that is perfect for me. But this form of Customer/Company also includes a dropdown list with the foreign key of an User, and I don't want to create the User first and then the Customer/Company object. I want that when I fill the Customer/Company form (with User fields) I should create the User object too.
Is there a way to solve this without create a User instance prior the Customer/Company instance?
Thanks
You can do this by adding an inline in your model registration in admin.py.
class AInline(admin.TabularInline):
model = A
class BAdmin(admin.ModelAdmin):
inlines = [AInline]
admin.register(A)
admin.register(B, BAdmin)
Django inline model admin documentation
I have scenario in which a user can have multiple books. I can create two different models for user and books and relate them using foreign keys (or one-to-many will be right way ?).
I have created a django forms for User model but when i do like this {{form.as_p}} in templates only user model fields is shown not books field.
I want that with user fields my books model filed also displayed (like book names field more then once because he can have multiple books) , Please let me know if it is possible using django forms/models or I have to user simple html forms with jquery and then save data in models.
Thanks
EDIT:
my models :
class Product(models.Model):
categories = models.CharField(max_length=5, choices = settings.CATEGORIES)
name = models.CharField(max_length=100)
description = models.TextField()
currency = models.CharField(max_length=5, choices = settings.CURRENCY)
status = models.BooleanField(default=True)
def __unicode__(self):
return self.name
class Prices(models.Model):
products = models.ForeignKey(Product)
prices = models.IntegerField()
def __unicode__(self):
return self.id
if you are creating a form for Prices, try putting this in your model form:
products = forms.ModelMultipleChoiceField(queryset=Product.objects.all())
I think you should add required fields in meta class such as
class ThreadForm(ModelForm):
class Meta:
model = Thread
fields = ('Books', 'User')
Please understand the work flow to use foreign keys in model form here.