I have been using Django for 4 5 months now and i have been implimenting users by importing the user class like this
example 1:
from django.db import models
from django.contrib.auth.models import User
class Posts(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post_name = models.CharField(max_length=150)
desription = models.CharField(max_length=200)
image = models.ImageField(upload_to="images/uploads")
def __str__(self):
return self.desription
and i have seen some people use the user model like this :
example 2:
class Recipe(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
name = models.CharField(max_length=220)
description = models.TextField(blank=True, null=True)
directions = models.TextField(blank=True, null=True)
timestamp = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
and also like this :
example 3:
author = models.ForeignKey(get_user_model())
now I have used both example 1 and example 2 for my projects and to mess around in my free time
and both seem to work fine , I am wondering what would be the use cases for these different methods and also is there any pros or cons to these methods of using the User Model?
Related
error image
I'm using the model and I keep running into problems with many to many. At first, I made it without giving an id value, but it seems that the id value is not entered, so when I put the id value directly, the same problem as above occurs. But in the Post model below, the same form of likes is used. Why?
from django.db import models
# from django.contrib.auth.models import User
from django.conf import settings
# from server.apps.user.models import Profile
# Create your models here.
class Clothes(models.Model):
CATEGORYS =[
(0, '상의'), #상의
(1, '하의'), #하의
(2, '아우터'), #아우터
(3, '신발'), #신발
(4, '악세사리'), #악세사리
]
category = models.IntegerField(default=0,choices=CATEGORYS)
id = models.IntegerField(primary_key=True)
img = models.ImageField(upload_to='main/images/clothes/%Y/%m/%d')
save = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Pickitems', blank=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
buying = models.TextField(null=True, blank=True)
def __str__(self):
return f'{self.id}: {self.category}'
#pk가 존재하지 않는것 같음.
# class SavePeople(models.Model):
class Post(models.Model):
main_img = models.ImageField(upload_to='main/images/post/%Y/%m/%d')
title = models.CharField(max_length=100)
content = models.TextField()
private = models.BooleanField(default=False)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
clothes = models.ManyToManyField(Clothes,related_name='Clothes')
likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Likes', blank=True)
def __str__(self):
return f'{self.pk}: {self.title}'
def get_absolute_url(self):
return f'/community/'
#이거 나중에 detail page로 바꿔주세요
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
content = models.TextField()
create_date = models.DateTimeField(auto_now_add=True)
update_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'({self.author}) {self.post.title} : {self.content}'
class Commu(models.Model):
COMMU_CHOICES = [
('buying', 'buying'), #공동구매
('openrun', 'openrun'), #오픈런
('question', 'question'), #고민방
]
category = models.CharField(max_length=20, choices=COMMU_CHOICES)
img = models.ImageField(upload_to='main/images/commu/%Y/%m/%d', null=True, blank=True)
title = models.CharField(max_length=100)
content = models.TextField()
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return f'{self.pk}: {self.title}'
def get_absolute_url(self):
return f'/community/commu'
I added the code saves= models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Save', blank=True) to the Clothes model to make a save of Clothes in the same way as the likes of the Post model, but an error like the attached picture is displayed. occurred. When I searched, it seemed that the pk value did not exist.
The issue is the id field that you explicitly provided, Django itself creates an id field as a primary key for each model if you don't specify one. So, it is not necessary to add it to the model. Kindly remove it through the Clothes model and run migration commands.
And it doesn't give in case of likes since there is no extra field id in Post model unlike that of Clothes.
Note: Models in Django doesn't require s to be added as suffix, as it is automatically done, so you may change Clothes to Cloth.
My site simply works like this: every Manager can have some SubManagers, those SubManagers can have some Agents (so the Agents are indirectly related to the Manager, see models.py to understand better the relations between them). I want to show in the Manager's profile page (see views.py) all the MembershipCard created by his/her related Agents. I'm trying to implement a filter to search, for example, cards created by a specific Agent, i'm able to do this but i would like to show in the dropdown only the Agents related to the Manager, the dropdown list now shows all Agents in the database
models.py
class StandardProfile(models.Model):
name = models.CharField(max_length=200, null=True)
surname = models.CharField(max_length=200, null=True)
phone_number = models.CharField(max_length=200, null=True)
class Meta:
abstract = True
class Manager(StandardProfile):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
class SubManager(StandardProfile):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
manager = models.ForeignKey(Capo, null=True, on_delete = models.SET_NULL)
class Agent(StandardProfile):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
manager = models.ForeignKey(Manager, null=True, on_delete = models.SET_NULL)
subManager = models.ForeignKey(SubManager, null=True, blank=True, on_delete = models.SET_NULL)
class MembershipCard(models.Model):
agent = models.ForeignKey(Agent, null=True,blank=True, on_delete = models.SET_NULL)
client = models.ForeignKey(Client, null=True,blank=True, on_delete = models.SET_NULL)
creation_date = models.DateTimeField(auto_now_add=True, null=True)
activation_date = models.DateTimeField(null=True,blank=True)
expiration_date = models.DateTimeField(null=True,blank=True)
views.py
#login_required(login_url='login')
def profilePage(request, pk): #www.mysite.com/profilePage/<pk>
user = User.objects.get(id=pk) #getting the user from <pk>
cards = MembershipCard.objects.filter(agent__manager=user.manager)
myFilter = MembershipCardFilter(request.GET,queryset=cards,user=user)
cards = myFilter.qs
#page_obj is used for Pagination, and contains the cards, i removed this part of code for better readability, can add it if needed
context = {'page_obj': page_obj,"user": user,"myFilter":myFilter}
return render(request, 'polls/profilePage.html',context)
filters.py
class MembershipCardFilter(django_filters.FilterSet):
class Meta:
model = MembershipCard
fields = ['agent','agent__subManager']
exclude = ['creation_date']
By reading answers to similar questions i think i have to modify the __init__ method in the CardFilter class, i've tried to adapt some answers to my case but it didn't work for some reasons . Any anser/comment is appreciated!
PS: I don't know if the title is clear, feel free to suggest a better one
You can try feeding the agent dropdown during init like (not tested!):
class MembershipCardFilter(django_filters.FilterSet):
agent= django_filters.ModelChoiceFilter(
queryset=Agent.objects.none(),
)
class Meta:
model = MembershipCard
fields = ['agent','agent__subManager']
exclude = ['creation_date']
def __init__(self, *args, **kwargs):
user = kwargs.get("user")
agents = Agent.objects.filter(manager__user=user)
super().__init__(*args, **kwargs)
self.filters["agent"].queryset = agents
I am Developing a E-commerce Application with Django
So what I was thinking is getting the category of the Product in a separate Model and list them down in another using choice field in CharField.
So Here is the code for this
This is the model for getting the Categories from the user
class ProjektCat(models.Model):
id = models.AutoField(primary_key=True)
Option_Name = models.CharField(max_length=50)
Option_Number = models.IntegerField()
Number_Visits = models.IntegerField(default=0)
def __str__(self):
return f'{self.Option_Name}'
and here is the code to list those categories as a dropdown in the CharField
class Software_And_Service(models.Model):
id = models.AutoField(primary_key=True)
Product_Name = models.CharField(max_length=100, default='')
projectKats = ProjektCat.objects.all()
choice = []
for i in projectKats:
option = (i.Option_Number, i.Option_Name)
choice.append(option)
Cateogary = models.CharField(
max_length=256, choices=choice)
Price = models.IntegerField(default=0)
Description = models.TextField(default='', max_length=5000)
pub_date = models.DateField(auto_now_add=True, blank=True, null=True)
image = models.URLField(default='')
linkToDownload = models.URLField(default='')
def __str__(self):
return f'Projekt : {self.Product_Name}'
But it's Showing me an Error that there is no such table in app_name.projektcat
Is there is any solution for this??
It's not how you do this. First correctly assign the projectKats field i.e
# You can set max_length as per your choice
projectKats = models.CharField(max_length=50)
You need to do this logic in django forms rather than django models.
So this is how you can do it.
forms.py
from django import forms
from .models import ProjektCat, Software_And_Service
def get_category_choices():
return [(obj.Option_Name,obj.Option_Name) for obj in ProjektCat.objects.values_list('Option_Name',flat=True).distinct()]
class SoftwareAndServiceForm(forms.ModelForm):
projectKats = forms.ChoiceField(choices=get_category_choices)
class Meta:
model = Software_And_Service
fields = [
'projectKats',
# whatever fields you want
]
In Django there are field types called ForeignKey and OneToMany/OneToOne, I was wondering would I use ForeignKey or the relationship type as the field type in this scenario? User to Profile has been identified as OneToOne but I'm unsure about the others.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
fullname = models.CharField(max_length=100)
dob = models.DateField()
address = models.TextField()
city = models.CharField(max_length=100)
profilephoto = models.ImageField(default='default_profile.jpg', upload_to='reviewApp/static/profile_images')
class Product(models.Model):
name = models.CharField(max_length=100)
brand = models.CharField(max_length=100)
cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00)
category = models.CharField(max_length=100)
releasedate = models.DateField()
description = models.TextField()
productphoto = models.ImageField(default='default_product.jpg', upload_to='reviewApp/static/product_images')
class Review(models.Model):
product = models.ForeignKey(Product)
profile = models.ForeignKey(Profile)
author = models.ForeignKey(User, on_delete=models.CASCADE)
rating = model.PositiveSmallIntegerField(default=1, validators = [MinValueValidator(1), MaxValueValidator(5)])
reviewtext = models.TextField()
postdate = models.DateTimeField(auto_now_add=True)
lastmodified = models.DateTimeField(auto_now=True)
So from what I see here, it seems to be good if the following is what you want:
User can have only one profile and one Profile is related to only one user.
a Profile can make multiple Review but a Review belongs to only one profile.
A Product can have multiple Review but a Review is specific to one Product.
Be carefull to define the on_delete argument for your foreign keys depending of what you want to keep in your database after a delete.
More info from the doc : https://docs.djangoproject.com/fr/2.2/ref/models/fields/#arguments
I'm confused with my django models,
My models:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
picture = models.ImageField(upload_to="photos/", default="photos/none/default.png")
film = models.ManyToManyField(Film)
class Film(models.Model):
title = models.CharField(max_length=60)
year = models.IntegerField(choices=YEARS)
image = models.ImageField(upload_to="images/", default="images/none/blank_poster.jpg")
def __str__(self):
return self.title
and now I trying to make a ratings for my film, when user adding a film to his list.
I tried M2M with through, but it wasn't exactly what I wanted, because user could add the same film several times and another problem with it was remove single film from list.
Now i thinking about additional models like this:
class FilmRating(models.Model):
user = models.ForeignKey(User)
film = models.ForeignKey(Film)
rate = models.IntegerField(choices=CHOICES)
Im glad If you can point me to the correct way to solve this problem, In future I want probably to store all rating from users for set average rate.