I am building a small web application where people will be able to join shows and for it to show that they joined it on a template. However, my current problem is that on my User Profile model I have added a couple of shows but the Show model object doesn't show that the User Profile is apart of it. How can I achieve this in Django?
models.py:
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True, related_name='user')
bio = models.TextField(max_length=500, blank=True)
image = models.ImageField(blank=True, upload_to="uploads/profile")
show = models.ManyToManyField('Show', blank=True)
def __str__(self):
return str(self.user)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
class Show(models.Model):
user = models.ForeignKey(User, null=True, blank=True)
name = models.CharField(max_length=120, null=True, blank=True)
description = models.TextField(max_length=500, null=True, blank=True)
image = models.ImageField(null=True, blank=True, upload_to="uploads/show")
venue = models.CharField(max_length=120, null=True, blank=True)
date = models.DateField(null=True, blank=True)
genre = models.CharField(max_length=120, null=True, blank=True)
def __str__(self):
return self.name
Related
Hy there,
I want to access value and apply position ordering on related field with in change_form file of django admin.
I have two model
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
PRODUCT_TYPE_CHOICES=[(1,'New'),(2,'Old')]
CURRENCY_TYPE_CHOICES=[(1,'USD'),(2,'INR')]
class Product(models.Model):
name = models.CharField(max_length=255)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
product_category = models.ForeignKey(
ProductCategory,
on_delete=models.SET(get_default_category)
)
product_type = models.IntegerField(choices=PRODUCT_TYPE_CHOICES,blank=True, null=True)
currency_type=models.IntegerField(choices=CURRENCY_TYPE_CHOICES,blank=True, null=True)
country = CountryField(max_length=10, blank=True, null=True)
city = models.CharField(max_length=255, blank=True, null=True)
state = models.CharField(max_length=255, blank=True, null=True)
price = models.FloatField(max_length=255,blank=True, null=True)
class Comment(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
forum = models.ForeignKey(
Product, on_delete=models.CASCADE,related_name="product_comments")
In admin panel
I want to display comment of particular product under the user field as shown in below image. Can you guys help me how do i solve this scenario.
I have a very reasonable pagespeed inside the django admin interface when i open my "facility" objects. But if i open one of my "facility addresses" it will take more than 8 seconds to load. I imagine that this is caused by the fact that all existing facilities are being loaded into the dropdown of the OneToMany Field even though the facility is only connected to one address.
How can i limit it so there is either no dropdown on these OneToMany Fields or that it only shows the current objects it is connected to?
class Facility(models.Model):
UUID = models.CharField(max_length=150, null=True, blank=True)
Name = models.CharField(max_length=150, null=True, blank=True)
class Meta:
verbose_name_plural = "facilities"
def __str__(self):
return self.Name
class FacilityAddress(models.Model):
PrimaryAddress = models.CharField(max_length=50, null=True, blank=True)
SecondaryAddress = models.CharField(max_length=50, null=True, blank=True)
City = models.CharField(max_length=50, null=True, blank=True)
RegionOrState = models.CharField(max_length=30, null=True, blank=True)
PostalCode = models.CharField(max_length=20, null=True, blank=True)
Geolocation = models.CharField(max_length=20, null=True, blank=True)
AddressInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE, related_name='fa')
class Meta:
verbose_name_plural = "facility addresses"
def __str__(self):
return f"{self.PrimaryAddress} {self.City}"
You should use autocomplete_fields in your admin so that all instances are not loaded by your ForeignKey
admin.py
from django.contrib import admin
from .models import Facility, FacilityAddress
class FacilityAdmin(admin.ModelAdmin):
search_fields = ['Name']
class FacilityAddressAdmin(admin.ModelAdmin):
autocomplete_fields = ['AddressInfo']
admin.site.register(Facility, FacilityAdmin)
admin.site.register(FacilityAddress, FacilityAddressAdmin)
here is my models.py code. im trying to run the python3.8 manage.py migrate command to create the tables for the database but i keep getting this error, what could be the issue here. Profile is a class in the models.py code. if you need another part of my code please ask
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Image(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null='True', blank=True)
image = models.ImageField(upload_to = 'pics/')
name = models.CharField(max_length=50,blank=True)
caption = models.CharField(max_length=250, blank=True)
likes = models.ManyToManyField(User, related_name='likes', blank=True, )
date_posted = models.DateTimeField(default=timezone.now)
class Comment(models.Model):
comment = models.TextField()
image = models.ForeignKey('Image', on_delete=models.CASCADE,related_name='comments',null='True', blank=True )
name = models.CharField(max_length=100, blank=True)
user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='comments',null='True', blank=True )
created = models.DateTimeField(auto_now_add=True, null=True)
class Profile(models.Model):
name = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField(upload_to='images/', default='default.png')
bio = models.TextField(max_length=500, default="My Bio", blank=True)
followers = models.ManyToManyField(User, related_name="followers", blank=True)
following = models.ManyToManyField(User, related_name="following", blank=True)
You are using the Profile class before defining it. Switch the order of the Comment class and Profile class. Like so:
class Profile(models.Model):
name = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField(upload_to='images/', default='default.png')
bio = models.TextField(max_length=500, default="My Bio", blank=True)
followers = models.ManyToManyField(User, related_name="followers", blank=True)
following = models.ManyToManyField(User, related_name="following", blank=True)
class Comment(models.Model):
comment = models.TextField()
image = models.ForeignKey('Image', on_delete=models.CASCADE,related_name='comments',null='True', blank=True )
name = models.CharField(max_length=100, blank=True)
user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='comments',null='True', blank=True )
created = models.DateTimeField(auto_now_add=True, null=True)
You are referencing the Profile class before this is constructed. You can make use of a string literal instead:
class Comment(models.Model):
# …
user = models.ForeignKey(
'Profile', # ← a string literal
on_delete=models.CASCADE,
related_name='comments',
null='True',
blank=True
)
# …
It might also be better to rename the field to profile, to make it clear the ForeignKey is referencing a Profile object, not a User object:
class Comment(models.Model):
# …
profile = models.ForeignKey( # ← rename to profile
'Profile',
on_delete=models.CASCADE,
related_name='comments',
null='True',
blank=True
)
# …
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
I am trying to create a blog post model and I added a schedule filed on Django model that I can schedule my post by date and time if schedule time == now. Then post should be verified and display to dashboard so for this I used def save function. But save function does not respond. When I tried to schedule a blog post from admin panel it did not change verified = True. Here is code what I did so far:
from django.utils import timezone
now = timezone.now() # get the current time
class Blog(models.Model):
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="post")
title = models.CharField(_("Title of blog post"),
max_length=250, null=True, blank=True)
header = models.CharField(
_("Blog title eg. TIPS, "), max_length=250, null=True, blank=True)
slug = models.SlugField(_("Slug of the title"), max_length=250,
unique_for_date='publish', null=True, blank=True)
photo = models.ImageField(_("Blog post main image"), default="img.png",
null=True, blank=True, upload_to='users/avatar')
read_time = models.TimeField(
_("Blog post read time"), null=True, blank=True)
category = models.ForeignKey(Category, verbose_name=_(
"Blog category list"), on_delete=models.CASCADE, null=True, blank=True)
publish = models.DateField()
tags = TaggableManager(blank=True)
description = HTMLField()
views = models.IntegerField(default="0") # <- here
verified = models.BooleanField(
_("Approved post before push on production"), default=False)
schedule = models.DateTimeField(
_("Schedule post by date and time"), auto_now=False, auto_now_add=False, null=True, blank=True)
class Meta:
verbose_name = _('blog')
verbose_name_plural = _('blogs')
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if self.schedule >= now:
self.verified = True
print(self.verified)
else:
self.slug = slugify(self.title) # this also not respond
super(Blog, self).save(*args, **kwargs)
what is now ? I don't see it defined. I think that the correct way to do it is
from django.utils.timezone import now
if self.schedule <= now():
do it
The save() function is only called when you save an object. This thus means that although an object has a self.schedule that is already passed the current timestamp, one should wait until the object is saved again (and that can take a long time).
It is better to annotate the queryset with a field that specifies that it is verified when self.scheduled is less than (or equal to) Now(). We thus can define a manager that injects the annotation, and remove the verified field:
from django.db.models import BooleanField, ExpressionWrapper, Q
from django.db.models.functions import Now
class BlogManager(models.Manager):
def get_queryset(self, *args, **kwargs):
return super().get_queryset(*args, **kwargs).annotate(
verified=ExpressionWrapper(Q(scheduled__lte=Now()), BooleanField())
)
class Blog(models.Model):
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="post")
title = models.CharField(_("Title of blog post"),
max_length=250, null=True, blank=True)
header = models.CharField(
_("Blog title eg. TIPS, "), max_length=250, null=True, blank=True)
slug = models.SlugField(_("Slug of the title"), max_length=250,
unique_for_date='publish', null=True, blank=True)
photo = models.ImageField(_("Blog post main image"), default="img.png",
null=True, blank=True, upload_to='users/avatar')
read_time = models.TimeField(
_("Blog post read time"), null=True, blank=True)
category = models.ForeignKey(Category, verbose_name=_(
"Blog category list"), on_delete=models.CASCADE, null=True, blank=True)
publish = models.DateField()
tags = TaggableManager(blank=True)
description = HTMLField()
views = models.IntegerField(default=0)
schedule = models.DateTimeField(
_("Schedule post by date and time"), auto_now=False, auto_now_add=False, null=True, blank=True)
objects = BlogManager()
I want to add items from Available classic to Chosen classic
how can i do that as in image below
i can get Chosen classic by
Profile.objects.get(user=request.user).classic.add(id=2)
but i can't add iems from Available classic to Chosen classic
any one can help this problem fast please
Thanks for all
Models.py
from django.db import models
# Create your models here.
from django.utils import timezone
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Language(models.Model):
language = models.CharField(
max_length=2,
choices=[
('AR', 'Arabic'),
('EN', 'English'),
],
default='AR'
)
def __str__(self):
return self.language
class Classic(models.Model):
name = models.CharField(max_length=50, blank=False, null=False)
music = models.FileField(upload_to='', max_length=100, blank=True, null=True)
lang = models.ForeignKey(Language, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
classic = models.ManyToManyField(Classic, blank=True, null=True)
workOut = models.ManyToManyField(WorkOut, blank=True, null=True)
chillOut = models.ManyToManyField(ChillOut, blank=True, null=True)
romantic = models.ManyToManyField(Romantic, blank=True, null=True)
happy = models.ManyToManyField(Happy, blank=True, null=True)
sad = models.ManyToManyField(Sad, blank=True, null=True)
lang = models.ManyToManyField(Language, blank=True, null=True)
def __str__(self):
return str(self.user)
def update_user_profile(sender, **kwargs):
if kwargs['created']:
user = Profile.objects.create(user=kwargs['instance'])
post_save.connect(update_user_profile,sender=User)
Admin.py
from django.contrib import admin
# Register your models here.
from . import models
class ClassicAdmin(admin.TabularInline):
model = models.Classic
class PlayLists(admin.ModelAdmin):
inlines = [ClassicAdmin]
class Favo(admin.ModelAdmin):
filter_horizontal = ['classic']
admin.site.register(models.Language, PlayLists)
admin.site.register(models.Profile, Favo)
what's wrong with in my code
thank for all
Thant's works with me
Profile.objects.get(user=request.user).classic.add(Classic.objects.get(id=1))