I am new to web devolopment and django. Currently I am developing a simple dashboard web application for our computational cluster and have configured a custom user model, which looks like this:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
processor_hours = models.FloatField(null=True, blank=True)
All of the default user fields are taken from our ldap server, and authentication works. However, I want to add data to the custom field for each user. I have a text file with the information in columns,
username1 hours
username2 hours
I tried using the manage.py shell to run a python script and add the data to the corresponding fields but it doesn't seem to be saving it to the database. What am I missing?
Edit: I wasn't saving the user with .save(). The issue is resolved, thanks for the help.
Related
I am trying to create a django project and I created a simple model and ran the django server, entered the fields. I can see all the data on the django server. I was wondering if there is any other way to see the data entered.
This is the data I entered. Can I view it anywhere else in tabular form or database form?
This is what I do in command window:
sqlite3 db.sqlite3
followed by
.tables
Where db.sqlite3 is the file that was created when I migrated. I am not sure if the data I entered on django server is in this file.
Thanks in advance.
EDIT
This is my models.py:
class Site(models.Model):
# Site ID
siteID = models.CharField(max_length=255, null=False)
# End Device ID
edevID = models.CharField(max_length=255, null=False)
After running python
manage.py runserver
I am directed to the django page where I enter the following data
And I save this. My question is how can I access this saved data in a database. I tried what you recommended Satya, it only shows me the superuser id.
I hope the question is clear now.
You can install this software. After installation, select your sqlite and see your complete database.
DB Browser for SQLite
Download from here: DB Browser
The question doesn't give enough information as to what you're trying to look for. I am assuming that you want more information out of the tables you've created and that you are using the default sqlite3 database. In your models.py file, you can use the special __str__ method to make your objects more descriptive
def __str__(self):
return self.title #if your using 'title' as the attribute to identify your objects
Also,
enter this command in cmd
python manage.py shell
and then in the shell, import the Model whose database you want to view
for e.g.
>>> from django.contrib.auth.models import User
>>> User.objects.all()
This will display all the data associated with your table. Unfortunately, not in tabular form. You can aso use the command python manage.py inspectdb to view all the classes associated with all tables. To view in proper tabular form, you might need phpmyadmin.
I have Django project for recording personal expenses and keeping personal budget.
I have created required models for the project and authorization using Django. However the idea is that each authentic user shall keep own expenses records, therefore needs likely separate database. I have researched Django documentation and it seems doest not provide answer to this. Probably there is no need to set up another database but to create unique model fields inherited from default admin user fields and store the data for each user in the single database.
Please advice correct approach for this task.
You can always extend the auth user model to include additional data. You can create a new model that has all the additional fields plus a one-to-one relationship with the django user model.
eg:
from django.db import models
from django.conf import settings
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
date_of_birth = models.DateField(blank=True, null=True)
...
Here, you should be able to use the default auth user fields plus the custom fields you need.
I am working on a project and I have decided to use Google App Engine for hosting (Django-nonrel). The website will have multiple types of users (inheriting from AbstractUser), and I want to be able to create permissions to control what a user can see/do. Since the native Django permissions do not work on Nonrel, I tried using permission_backend_nonrel, however it only works if you use the standard User model.
I have spent lots of time searching for how others have gotten permissions to work on Nonrel and AbstractUser, but have not found anything. It seems like I should give up on getting permissions to work and just create fields within the user models to replicate permissions. For example, if I want only some users to have the ability to change their email address, then I could do:
accounts\models.py
class UserProfile(AbstractUser):
address = models.CharField(max_length=40)
can_change_email = models.BooleanField(default=True)
customers\models.py
class CustomerProfile(UserProfile):
company = models.BooleanField(max_length=40)
In this scenario I could set 'can_change_email' and control this behavior in the views for UserProfile.
I would prefer to use the built-in permission system, but running out of ideas. Any suggestions?
I'd say you might have better luck creating separate one-to-one models to signify the difference between your users. Django expects you to have a single user model.
Another option is to use the normal User model and create proxy models that reflect the changes you want to have between users.
The first way:
class CustomerProfile(models.Model):
user = models.OneToOneField(User)
The second way:
class CustomerProfile(User):
class Meta:
proxy = True
I have a requirement of two types of login in my django project where one login is for students and one login is for teachers.
I have gone through the Django documentation and other internet resources, and I have come up with a simple design solution but I am not sure about the pros and cons as I am still quiet new to Django.
Solution I thought to solve this Problem:
1) For student login, I have succesfully integrated django-allauth and it is working fine.
2) Now for the teacher login, I am thinking to build a model as follows:
class Teacher(models.Model):
teacher = models.OneToOneField(User,unique=True)
identifier = models.CharField(max_length=128)
#other fields
3) Then two forms over this model - Signup and Login for teachers and email verification form: Here I thought that I will create teacher object and student object on successful signup but I will set is_active=False and ask for email verification.On successful verification, I will set is_active=True so that a teacher can successfully login.
4) Avoid students from logging in the teachers section and teachers can login in the students section: Here I though of an identifier field to avoid authenticated students to login in the teachers section.
Please can anyone help me by providing your opinion on this solution or by suggesting some better alternative as I am still reading up more and more Django Documentation on this.
Thanks in Advance!
You could create a single model 'user' and define there permissions by adding them to a group.
And have your Django application for teachers check if there in the group teacher.
You could create separate forms or check based on email (name.student# or name# ) and
before saving the model adding the group.
Keeping is_active on False is alway a good idea if you want to verify that a 'user' has given a correct email.
I did an application which needed different permissions levels for Students, Teachers and a few different other User categories. I'm not sure if it's the best way to do it, but I did it by creating one UserProfile, as Eagllus mentioned, which had several categories for what kind of user profile it was. Something like:
PROFILE_CHOICES = (
('TE', 'Teacher'),
('ST', 'Student'),
)
class UserProfile(models.Model):
user = models.ForeignKey(User)
profile_type = models.CharField(max_length=2, choices=PROFILE_CHOICES)
'''other attributes'''
You can then decorate your views so only users of a certain type can access them.
Its not clear to me what you are trying to do in #3. It sounds like you want the user to be added as a teacher and student but only make them active by email verification?
I'm not familiar with django-auth but django-registration provides user registration where user account are activated via email. This may save you a significant amount of work.
I'm working on an online store in Django (just a basic shopping cart right now), and I'm planning to add functionality for users to mark items as favorite (just like in stackoverflow). Models for the cart look something like this:
class Cart(models.Model):
user = models.OneToOneField(User)
class CartItem(models.Model):
cart = models.ForeignKey(Cart)
product = models.ForeignKey(Product, verbose_name="produs")
The favorites model would be just a table with two rows: user and product.
The problem is that this would only work for registered users, as I need a user object. How can I also let unregistered users use these features, saving the data in cookies/sessions, and when and if they decides to register, moving the data to their user?
I guess one option would be some kind of generic relations, but I think that's a little to complicated. Maybe having an extra row after user that's a session object (I haven't really used sessions in django until now), and if the User is set to None, use that?
So basically, what I want to ask, is if you've had this problem before, how did you solve it, what would be the best approach?
I haven't done this before but from reading your description I would simply create a user object when someone needs to do something that requires it. You then send the user a cookie which links to this user object, so if someone comes back (without clearing their cookies) they get the same skeleton user object.
This means that you can use your current code with minimal changes and when they want to migrate to a full registered user you can just populate the skeleton user object with their details.
If you wanted to keep your DB tidy-ish you could add a task that deletes all skeleton Users that haven't been used in say the last 30 days.
Seems to me that the easiest way to do this would be to store both the user id or the session id:
class Cart(models.Model):
user = models.ForeignKey(User, null=True)
session = models.CharField(max_length=32, null=True)
Then, when a user registers, you can take their request.session.session_key and update all rows with their new user id.
Better yet, you could define a "UserProxy" model:
class Cart(models.Model):
user = models.ForeignKey(UserProxy)
class UserProxy(models.Model):
user = models.ForeignKey(User, unique=True, null=True)
session = models.CharField(max_length=32, null=True)
So then you just have to update the UserProxy table when they register, and nothing about the cart has to change.
Just save the user data the user table and don't populate then userid/password tables.
if a user registers then you just have to populate those fields.
You will have to have some "cleanup" script run periodically to clear out any users who haven't visited in some arbitrary period. I'd make this cleanup optional. and have a script that can be run serverside (or via a web admin interface) to clear out in case your client wants to do it manually.
remember to deleted all related entries as well as the user entry.
I think you were on the right track thinking about using sessions. I would store a list of Product id's in the users session and then when the user registers, create a cart as you have defined and then add the items. Check out the session docs.
You could allow people that are either not logged in or don't have an account to add items to a 'temp' cart. When the person logs in to either account or creates a new account, add those items to their 'real' cart. Then by just adding a few lines to your 'add item to cart' and login functions, you can use your existing models.