I need to show a list of countries for users to select from the ship's country field. But it's showing the Country object(1), Country object(2)... instead of showing names of countries
I've created classes for Ship and Country with the Ship class having a foreign key of country.
class Ship(models.Model):
# Fields
name = models.CharField(max_length=255)
slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
callsign = models.CharField(max_length=50)
last_updated = models.DateTimeField(auto_now=True, editable=False)
weight = models.DecimalField(max_digits=20, decimal_places=4)
# RelationShip Fields
shipflag = models.ForeignKey(
'manifest.Country', on_delete=models.SET_NULL,
related_name="Ships", null=True
)
class Meta:
ordering = ('-created',)
def __unicode__(self):
return u'%s' % self.slug
def get_absolute_url(self):
return reverse('manifest_Ship_detail', args=(self.slug,))
def get_update_url(self):
return reverse('manifest_Ship_update', args=(self.slug,))
class Country(models.Model):
# Fields
name = models.CharField(max_length=255)
slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
code = models.CharField(max_length=5)
# RelationShip Fields
continent = models.ForeignKey(
'manifest.Continent',
on_delete=models.CASCADE, related_name="Countrys",
)
class Meta:
ordering = ('-created',)
def __unicode__(self):
return u'%s' % self.slug
def get_absolute_url(self):
return reverse('manifest_Country_detail', args=(self.slug,))
def get_update_url(self):
return reverse('manifest_Country_update', args=(self.slug,))
In the 'create new ship' form at the country dropdown combo I expect to see a list of countries like United States, Mexico, Canada... but instead am seeing countries as objects like this object(1), Country object(2)...
add this method to your models. ;)
def __str__(self):
return self.name
Related
I am working for a personal project that is using an API and having user authentication with JWT (but used in serializer). I wanted to implement ManyToManyField for user and city but it doesn't work properly. This is the extended model I have found and django aggregation . I want that the UserSearchLocation to store the City and when logged in to see the city, while other users will not see it until the search same city.
models.py
class UserSearchLocation(models.Model):
city_name = models.CharField(max_length=85, blank=False)
def __str__(self):
return self.city_name
class City(models.Model):
user_searched_locations = models.ManyToManyField(User,
through='UsersLocations',
through_fields=('city', 'user'),
related_name="my_cities",
blank=True)
id = models.AutoField(primary_key=True, editable=False)
location = models.CharField(max_length=85)
country = models.CharField(max_length=85, blank=True)
country_code = models.CharField(max_length=2, blank=True)
latitude = models.DecimalField(max_digits=6, decimal_places=4,
null=True, blank=True)
longitude = models.DecimalField(max_digits=6, decimal_places=4,
null=True, blank=True)
zip_code = models.PositiveIntegerField(default=0)
#users_location = models.ManyToManyField(UserSearchLocation)
def __str__(self):
return f'{self.location}, {self.country_code}'
def save(self, *args, **kwargs):
self.location = self.location.capitalize()
self.country = self.country.capitalize()
self.country_code = self.country_code.capitalize()
return super(City, self).save(*args, **kwargs)
class Meta:
verbose_name_plural = 'cities'
unique_together = ("location", "country_code")
class UsersLocations(models.Model):
id = models.AutoField(primary_key=True, editable=False)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
city = models.ForeignKey(City,
on_delete=models.CASCADE,
related_name='locations_by_users',
null=True)
To add in localhost/admin/ a City works, but when to add a UserSearchLocation I have this error:
Exception Value:
column base_usersearchlocation.user_id does not exist
LINE 1: SELECT "base_usersearchlocation"."user_id", "base_usersearch...
Your error says the city.location doesn't exist - location is a CharField on your City model - are you sure you've run migrations and don't have any naming conflicts?
I have a Product model that has a ManyToMany to Category.
Category has a ForeignKey to itself named parent.
I want to add all parents of selected category to category field.
example for category:
digital appliance->None __ Mobile->digital appliance __ Samsung->Mobile and...
when choose Samsung for category of a product, I want to add Mobile and digital appliance to category
it's my models, the save method doesn't do anything
Class Product:
class Product(models.Model):
STATUS_CHOICES = (
('s', 'show'),
('h', 'hide'),
)
title = models.CharField(max_length=150)
slug = models.SlugField(max_length=170, unique=True)
category = models.ManyToManyField(Category)
thumbnail = models.ImageField(upload_to='images/products', default='images/no-image-available.png')
image_list = ImageSpecField(source='thumbnail', processors=[ResizeToFill(400, 200)], format='JPEG',options={'quality': 75})
image_detail = ImageSpecField(source='thumbnail', processors=[ResizeToFill(1000, 500)], format='JPEG',options={'quality': 100})
description = models.TextField()
inventory = models.IntegerField()
features = models.ManyToManyField(Feature)
status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='s')
def __str__(self):
return self.title
class Meta:
verbose_name = "product"
verbose_name_plural = "products"
def save(self, *args, **kwargs):
for cat in self.category.all():
if cat.parent:
self.category.add(cat.parent)
return super(Product, self).save(*args, **kwargs)
objects = ProductManager()
Category and CategoryManager:
class CategoryManager(models.Manager):
def no_parent(self):
return self.filter(parent=None)
def get_parent(self, parent):
return self.filter(parent=parent)
class Category(models.Model):
parent = models.ForeignKey('self', default=None, null=True, blank=True, on_delete=models.SET_NULL,related_name='children')
title = models.CharField(max_length=40)
slug = models.SlugField()
status = models.BooleanField(default=True)
I think it makes more sense to have Foreign Key to category table rather than m2m relation. You can flatten it in the view whenever needed
I am creating ecommerce website. There are multiple categories. For example, phones, computers and others. I created a model for each of them. In OrderItems I want to foreign key each of them. So, I want to use multiple models in ForeignKey.
models.py
class Telefon(models.Model):
name = models.CharField(max_length=200)
category = models.CharField(max_length=300, choices=TELEFON, default="xiaomi")
price = models.FloatField()
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
#property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
class TV(models.Model):
name = models.CharField(max_length=200)
category = models.CharField(max_length=300, choices=TELEFON, default="xiaomi")
price = models.FloatField()
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
#property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
Product={'Telefon', 'TV'}
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
#property
def get_total(self):
total = self.product.price * self.quantity
return total
So, how can I use multiple models in Foreign Key field in my OrderItems model.
I have 2 modules a module representing a company:
class ExternalService(models.Model):
# Fields
company_name = models.CharField(max_length=60)
address_street = models.CharField(max_length=60)
address_postcode = models.CharField(max_length=30)
address_city = models.CharField(max_length=30)
company_telephone = models.CharField(max_length=30)
company_email = models.CharField(max_length=60)
company_support_telephone = models.CharField(max_length=30)
company_support_email = models.CharField(max_length=30)
company_website = models.URLField(null=True, blank=True)
notes = models.TextField(max_length=448)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
class Meta:
pass
def __str__(self):
return str(self.company_name)
def get_absolute_url(self):
return reverse("asset_app_ExternalService_detail", args=(self.pk,))
def get_update_url(self):
return reverse("asset_app_ExternalService_update", args=(self.pk,))
and a module representing employees:
class ExternalServiceContact(models.Model):
# Relationships
company = models.ForeignKey("asset_app.ExternalService", on_delete=models.SET_NULL, blank=True, null=True)
position = models.ForeignKey("asset_app.ExternalServicePosition", on_delete=models.SET_NULL, blank=True, null=True)
# Fields
name = models.CharField(max_length=60)
email = models.CharField(max_length=30)
cellphone = models.CharField(max_length=30)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
class Meta:
pass
def __str__(self):
return str(self.name)
def get_absolute_url(self):
return reverse("asset_app_ExternalServiceContact_detail", args=(self.pk,))
def get_update_url(self):
return reverse("asset_app_ExternalServiceContact_update", args=(self.pk,))
In my views.py I want to get all the employees belonging to that company. So when I look at my DetailView I only get listed employees beloning to that company.
class ExternalServiceDetailView(generic.DetailView):
model = models.ExternalService
form_class = forms.ExternalServiceForm
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['employees'] = models.ExternalServiceContact.get(#######).order_by('name')
return context
just dont know what to insert into my get()
You can query with:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['employees'] = self.object.externalservicecontact_set.order_by('name')
return context
I have a Property Model as follows =
class Property(models.Model):
property_type = models.CharField(max_length=255, default='Apartment')
specifications = models.CharField(max_length=255, default='Basic')
built_up_area = models.FloatField(max_length=6, null=False, default=0)
total_area = models.FloatField(null=False, default=0)
number_of_bedrooms = models.CharField(max_length=3, default=1)
number_of_bathrooms = models.CharField(max_length=3, default=1)
number_of_parking_spaces = models.CharField(max_length=2, default=0)
address_line_one = models.CharField(max_length=255, null=False)
address_line_two = models.CharField(max_length=255, null=True, default=None)
connectivity = models.CharField(max_length=255, default=None, null=True)
neighborhood_quality = models.CharField(max_length=255, default=None,
null=True)
comments = models.CharField(max_length=255, default=None, null=True)
city = models.ForeignKey('City')
state = models.ForeignKey('State')
pin_code = models.ForeignKey('PinCode')
developer = models.ForeignKey('Developer', null=True, default=None)
owner = models.ForeignKey('Owner', null=True, default=None)
created_by = models.ForeignKey('custom_user.User')
project = models.ForeignKey('Project')
def __unicode__(self):
return self.property_type
class Meta:
verbose_name_plural = 'Properties'
And a City model as follows -
class City(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(City, self).save(*args, **kwargs)
def __unicode__(self):
return self.name
Now I want to make a single form where I can enter the Property details and while entering the city, I can enter the name of the city instead of selecting from the dropdown list.
So how do I create the inline formset using the inlineformset_factory to create the form?
==EDIT==
I've tried to use the following code to create the formset
CityFormset = inlineformset_factory(City, Property,
fields=('city',),
extra=0,
min_num=1,
can_delete=False)
You've misunderstood what an inline formset is. It's for editing the "many" side of a one-to-many relationship: that is, given a parent model of City, you could edit inline the various Properties that belong to that city.
You don't want a formset at all to simply edit the single City that a property can belong to. Instead, override the city field within your Property form to be a TextField, and either create a new City or find an existing one in the clean_city method.
class PropertyForm(forms.ModelForm):
city = forms.TextField(required=True)
class Meta:
model = Property
exclude = ('city',)
def __init__(self, *args, **kwargs):
super(PropertyForm, self).__init__(*args, **kwargs)
if self.instance and not self.data:
self.initial['city'] = self.instance.city.name
def save(self, commit=True):
city_name = self.cleaned_data['city']
city, _ = City.objects.get_or_create(name=city_name)
instance = self.save(commit=False)
instance.city = city
if commit = True:
instance.save()
return instance