I'm new in django. I want to create applications where users will be able to create objects and update them daily (add new days and new descriptions and photos).
So my question is:
1.
In models.py I need to create class Object(models.Model) and use ForeignKey(settings.AUTH_USER_MODEL) or OneToOneRel(settings.AUTH_USER_MODEL) to connect user which create object with this object ?
2.
I need to create an extra class day where there will be fields such as a subtitle description etc and add it to the object class?
3.
How I can create form or views to daily updating ?
1i. You need User and Objects model. You can use built in django User model
You have one to many relation one user can have many objects. Therefore you need foreign key. So make Object model like this:
class Object(models.Model)
title = models.CharField(max_length=100)
description = models.CharField(max_length=1000)
user = ForeignKey(model=User)
Don't understand
Django provides you simple admin which is suitable if you want to just add, update, delete. Otherwise you can use model forms to build your custom views and templates for edit database records. Model Forms
and Forms. Here you will find everything you need to create custom views with model forms.
Related
I am trying to build a Django website where the user is able to create custom objects known as items. Each item needs to be able to have certain properties that are stored in the database. For example an item would need properties such as
Serial Number,
Description,
Manufacture Date
However I want the user to be able to specify these fields similar to what Microsoft dynamics allows . For example a user should be able to specify they want a text field with the name Model Number, associated with a specific item type and from then on they can store those properties in the database.
I am not sure the best approach to do this because a standard database model, you already have all the fields defined for a specific table, however this essentially means i have to find a way to have user defined tables.
Does anyone know a good approach to handle this problem, at the end of the day I want to store items with custom properties as defined by the user in a database.
thanks
There are multiple ways you can go.
In non-relational databases you don't need to define all the fields for a collections ( analogous to a table of RDBMS).
But if you want to use SQL with Django, then you can define a Property Model.
class Property(models.Model):
name = CharField()
value = CharField()
item = models.ForeignKey(Item, on_delete=models.CASCADE)
class Item(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
You can render a FormSet of Property form. To add extra empty forms on the fly, render dynamic formsets.
I have the following code in my models.py:
class Application(models.Model):
team_name = models.CharField(max_length=100)
...
class Participant(models.Model):
name = models.CharField(max_length=100)
grade = models.SmallIntegerField(choices=GRADE_CHOICES, blank=True, null=True)
application = models.ForeignKey(Application, related_name="participants")
...
i.e. There are multiple Participants, and each Participant will be on a single application. (It is defined that each Application will have exactly 8 Participants).
The intended purpose of this code is that a user will be able to create a new application, on which he/she will name 8 Participants. When the Application is created, 8 new instances of Participants should also be created and linked such that each Participant has the newly created Application as its Foreign Key.
I am currently struggling to create a form/view that will handle this creation process. I want the user to be a presented a single webpage that presents input forms that allow the user to create a new Application (name, etc.), along with 8 new Participants (each having a name, grade, etc.)
My current forms.py has:
class ApplicationForm(forms.ModelForm):
"""
A form that edits an application and all of its participants.
"""
nationality = forms.CharField(disabled=True, required=False)
class Meta:
model = Application
fields = '__all__'
But I realize that this does not display to the user what is needed to create 8 new Participants with the creation of this Application. How can I modify my forms.py to include space for the user to create 8 Participants with the creation of an Application?
The only solution I can come up with is to manually list 8 Participant form calls in a single view, but I feel that there must be a better solution.
What you are looking for is django formsets
A formset is a layer of abstraction to work with multiple forms on the
same page. It can be best compared to a data grid. Let’s say you have
the following form:
There is also a ModelFormSet
Like regular formsets, Django provides a couple of enhanced formset
classes that make it easy to work with Django models.
These can be used to create several instances of a given model in a single page. The only trouble is that it has a bit of a learning curve and the user experience isn't as great as what you might get with Angular or React.
I'm new to Django and I want to create an app where artistes can post their songs and albums. Now I want artistes to have a different sign-up page from the normal users. I want artistes to be able to add their portraits, genres, and all that. Is there a way to add these fields to the User model? I've seen some questions on this but I don't think I really understood the answers.
There are basicly two ways to achive this:
1. Create a new model Artist with a OneToOneField to the django user model. This is most likely what you want. E.g. like this:
from django.contrib.auth.models import User
class Artist(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
genres = models.ManyToManyField('myapp.Genre', related_name='artists')
class Portrait(models.Model):
artist = models.ForeignKey('myapp.Artist', related_name='portraits')
class Genre(models.Model):
name = models.CharField(max_length=30)
2. Specify a custom User model that inherits from AbstractBaseUser. This is only reccomended if you want to store additional information related to authentication itself.
I suggest that you read the documentation on this carefully:
https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#extending-the-existing-user-model
To create a custom sign-up page you will need to create your own FormView with a custom template e.g. using the django built in UserCreationForm and/or ModelForm. You could extend it with whichever fields you need. There are several ways to achive this depending on your needs.
Note: I've since asked this question again given the updates to Django's user model since version 1.5.
I'm rebuilding and making improvements to an already existing Django site and moving it over from Webfaction to Heroku, and from Amazon's SimpleDB to Heroku Postgres (though testing locally on Sqllite3 when developing). A lot of what I'm doing is moving over to use built-in Django functionality, like the Django admin, user authentication, etc.
Conceptually, the site has two kinds of users: Students and Businesses. The two types of users have completely different permissions and information stored about them. This is so much the case that in the original structure of the site, we set up the data model as follows:
Users
ID (primary_key)
Business_or_Student ('B' if business, 'S' if student)
email (unique)
password (hashed, obviously)
...
Students
ID (Foreignkey on Users)
<more information>
...
Businesses
ID (Foreignkey on Users)
<more information>
...
This worked pretty well for us, and we had the bare-bones user information in the Users table, and then any more detailed information in the Students and Businesses tables. Getting a user's full profile required something along this pseudocode:
def get_user_profile(id):
if Users(id=id).Business_or_Student = 'B':
return Businesses(id=id)
else:
return Students(id=id)
In moving over, I've found that Django's built-in User object has pretty limited functionality, and I've had to extend it with a UserProfile class I've created, and then had additional Student and Business tables. Given all of the patching I'm doing with this in the Django admin, and being relatively unfamiliar with Django models since I always did it differently, I'm not sure if this is the best way to go about it, or if I should just stick all of the information for businesses and students in the UserProfile table and just differentiate the two with different groups, or if there's even some way to do this all in the built-in User object.
Since businesses and students also have different interfaces, I'm seriously considering setting up the two as different apps within my Django project, and so separating their views, models, etc. entirely. That would look something like:
MyProject/
MyProject/ (project folder, Django 1.4)
mainsite/
students/
businesses/
One of my biggest concerns is with the Django Admin. In extending User, I already had to add the following code:
class UserProfileInline(admin.StackedInline):
model = UserProfile
can_delete = False
verbose_name_plural = 'profile'
class UserAdmin(UserAdmin):
inlines = (UserProfileInline, )
However, I would like the information for the Business or Student aspects of the user to show up in the Django admin when that User is pulled up, but the ForeignKey part of the model is in the Student and Business model since every Student/Business has a User but every User has only one Student or one Business object connected with it. I'm not sure how to add a conditional Inline for the Admin.
Question: Given this structure and these concerns, what is the best way to set up this site, particularly the data model?
This is not a complete solution, but it will give you an idea of where to start.
Create a UserProfile model in mainsite. This will hold any common attributes for both types of users. Relate it to the User model with a OneToOne(...) field.
Create two more models in each app, (student/business), Business and Student, which have OneToOne relationships each with UserProfile (or inherit from UserProfile). This will hold attributes specific to that type of users. Docs: Multitable inheritance / OneToOne Relationships
You may add a field in UserProfile to distinguish whether it is a business or student's profile.
Then, for content management:
Define the save() functions to automatically check for conflicts (e.g. There is an entry for both Business and Student associated with a UserProfile, or no entries).
Define the __unicode__() representations where necessary.
I hope I understood your problem... maybe this can work? You create a abstract CommonInfo class that is inherited in into the different Sub-classes (student and businesses)
class CommonUser(models.Model):
user = models.OneToOne(User)
<any other common fields>
class Meta:
abstract = True
class Student(CommonUser):
<whatever>
class Business(CommonUser):
<whatever>
In this case the models will be created in the DB with the base class fields in each table. Thus when you are working with Students you run a
students = Students.objects.get.all()
to get all your students including the common information.
Then for each student you do:
for student in students:
print student.user.username
The same goes for Business objects.
To get the student using a user:
student = Student.objects.get(user=id)
The username will be unique thus when creating a new Student or Business it will raise an exception if an existing username is being saved.
Forgot to add the link
I saw a couple of ways extending user information of users and decided to adopt the model inheritance method.
for instance, I have :
class Parent(User):
contact_means = models.IntegerField()
is_staff = False
objects = userManager()
Now it is done, I've downloaded django_registration to help me out with sending emails to new users. The thing is, instead of using registration forms to register new user, I want to to invoke the email sending/acitvation capability of django_registration. So my workflow is:
1. add new Parent object in admin page.
2. send email
My problem is, the django-registration creates a new registration profile together with a new user in the user table. how do I tweak this such that I am able to add the user entry into the custom user table.
I have tried to create a
modelAdmin
and alter the save_model method to launch the create_inactive_user from django_registration, however I do not how to save the user object generated from django_registration into my Parent table when I have using model inheritance and I do not have a Foreign key attribute in my parent model.
It's probably something like:
p = Parent()
p.user_ptr = user
p.contact_means = ...
p.save()
(Django creates the foreign key for you when doing model inheritance, plus the attribute ending in _ptr)