I'm trying to create an address form with multiple address, where the user can choose home or shipping address. I have the current model:
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class Address(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60, default="Miami")
state = models.CharField(max_length=30, default="Florida")
zipcode = models.CharField(max_length=5, default="33165")
country = models.CharField(max_length=50)
class Meta:
verbose_name = 'Address'
verbose_name_plural = 'Address'
def __str__(self):
return self.name
So I was wondering if that's correct.
Anyway, I was wondering how with the current model I can create a view so I can have the address form. Using a normal model would be "easy" but how can I do it using the through option in the model?
Could someone lend me a hand please?
Thank you
use a foreign key to point to your address model:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
nick_name = models.CharField('Nick name', max_length=30, blank=True, default='')
bio = models.TextField(max_length=500, blank=True)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
addresses = models.ForeignKey(Address) # <-- fix here
Hope this helps!
You should declare ForeignKey with '<app>.<model>' format:
class AddressType(models.Model):
address = models.ForeignKey('yourapp.Address', on_delete=models.CASCADE)
profile = models.ForeignKey('yourapp.Profile', on_delete=models.CASCADE)
or directly give the class:
address = models.ForeignKey(Address, on_delete=models.CASCADE)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
Both of the other answers were incorrect, I ended up modifying everything and also creating a new model, here it is:
class Address(models.Model):
name = models.CharField(max_length=100, blank=False)
address1 = models.CharField("Address lines 1", max_length=128)
address2 = models.CharField("Address lines 2", max_length=128, blank=True)
city = models.CharField("City", max_length=64)
# state = USStateField("State", default='FL')
state = models.CharField("State", max_length=128, default='FL')
zipcode = models.CharField("Zipcode", max_length=5)
user = models.ForeignKey(Profile, on_delete=models.CASCADE, blank=False)
class Meta:
verbose_name_plural = 'Address'
def __str__(self):
return self.name
Related
I have 2 models in my project. What I want to do is access CustomUser model field "user_coins". But the problem is that I need to get it with only having offer_id from the TradeOffer model. So essentially what I would like to happen is to find the TradeOffer field with offer_id and through ForeignKey get the CustomUser field user_coins that the offer_id belongs to. I can't seem to figure out how to do that.
class CustomUser(AbstractUser):
username = models.CharField(max_length=32, blank=True, null=True)
name = models.CharField(max_length=200, unique=True)
user_coins = models.FloatField(default=0.00)
class TradeOffers(models.Model):
name = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
offer_id = models.CharField(max_length=150, unique=True)
offer_state = models.IntegerField()
offer_message = models.TextField(null=True)
trade_id = models.CharField(max_length=150, unique=True, null=True)
date_added = models.DateTimeField(auto_now_add=True)
Simple. To get the "user_coins" through "TradeOffers" objects you have to do this:
tradeoffer = TradeOffers.objects.get(offer_id = <whatever>) #Get the object.
user_coins = tradeoffer.name.user_coins #Get the user_coins field.
Or directly:
user_coins = TradeOffers.objects.get(offer_id = <whatever>).name.user_coins
models.py
class User(models.Model):
googleId = models.CharField(max_length=512, primary_key=True, default='')
imageURL = models.CharField(max_length=512, null=True)
userName = models.CharField(max_length=512, null=True)
firstName = models.CharField(max_length=512, null=True)
lastName = models.CharField(max_length=512, null=True)
#phoneNumberRegex = RegexValidator(regex=r"^+?1?\d{8,15}$")
phoneNumber = models.CharField(max_length=512, null=True)
email1 = models.CharField(max_length=512, blank=False)
email2 = models.CharField(max_length=512, blank=True)
bio = models.TextField(blank=True)
planId = models.ForeignKey('primal_user.Plans',
on_delete=models.CASCADE,
default="Free")
password = models.CharField(max_length=512, null=True)
accountCreationDate = models.DateTimeField(auto_now_add=True)
coins = models.IntegerField(default=2)
assetsDownloaded = models.IntegerField(default=0)
assetsPurchased = models.IntegerField(default=0)
class Asset(models.Model):
assetId = models.CharField(max_length=20, primary_key=True)
devUserId = models.ForeignKey(User, on_delete=models.CASCADE)
keywordId = models.ForeignKey(Tags, on_delete=models.CASCADE)
assetName = models.CharField(max_length=50, null=False)
description = models.TextField(blank=True)
features = models.TextField(blank=True)
uploadedDate = models.DateField(auto_now_add=True)
typeId = models.BooleanField(default=True)
paidStatus = models.BooleanField(default=False)
price = models.IntegerField(null=True)
size = models.FloatField(null=False)
downloadCount = models.BigIntegerField(null=True)
version = models.CharField(max_length=10)
serializer.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
class AssetSerializer(serializers.ModelSerializer):
class Meta:
model = Asset
fields = '__all__'
views.py
class UserAsset(APIView):
def get(self,request,devUserId):
try:
user = Asset.objects.filter(devUserId=devUserId).values()
serializer = AssetSerializer(user, many= True)
return Response(serializer.data)
except Asset.DoesNotExist:
raise Http404
KeyError
I am a beginner in Django, so am unable to figure out what the issue is. I tried looking for solutions to similar questions but could not resolve the issue. I was getting attribute error, then it was resolved after I entered many=True in AssetSerializer but now I am stuck with this KeyError. A while trying to figure out the error, I noticed that this error is thrown while executing serializer.data. Thank You for any help possible.
In your code, just a small change is needed in syntax.
Instead of:
user = Asset.objects.filter(devUserId=devUserId).values()
Write:
user = Asset.objects.filter(devUserId=devUserId)
And that should solve the issue!
try with user = Asset.objects.values('fieldnamehere').filter(devUserId=devUserId)
I just created a model like this :
from django.db import models
# Create your models here.
class Category:
title = models.CharField(max_length=50)
slug = models.CharField(max_length=200)
cat_image = models.ImageField(upload_to='images/')
def __str__(self):
return self.title
class Brand:
title = models.CharField(max_length=50)
slug = models.CharField(max_length=200)
brand_image = models.ImageField(upload_to='images/')
def __str__(self):
return self.title
class UOM:
title = models.CharField(max_length=100)
def __str__(self):
return self.title
class Product_Images:
multi_images = models.ImageField(upload_to='images/')
class Product:
name = models.CharField(max_length=100)
slug = models.CharField(max_length=200)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
price = models.IntegerField(null=True, blank=True)
height = models.IntegerField(null=True, blank=True)
weight = models.IntegerField(null=True, blank=True)
length = models.IntegerField(null=True, blank=True)
color = models.IntegerField(null=True, blank=True)
stock = models.BooleanField()
SKU = models.CharField(max_length=150)
def __str__(self):
return self.name
class Customer:
phone_number = models.CharField(max_length=11)
first_name = models.CharField(max_length=10)
last_name = models.CharField(max_length=10)
email = models.CharField(max_length=20)
password = models.CharField(max_length=10)
def __str__(self):
return self.first_name
class Order:
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
invoice = models.CharField(max_length=16, null=True, blank=True)
phone = models.CharField(max_length=12)
address = models.CharField(max_length=150)
But facing this error dont have any idea why i am getting this kind of error. I cant even makemigrations if i delete some fields. It says no change detected but i changed some fields still getting this kind of error can some one solve this issue for me. and please explain why ia magetting this kind of error i cant find any problem here. I am also facing this no changes issue on my macos also. i am changing some fields still it says no changes detected .
Models in django haveto be like:
class ModelClass(models.Model):
I am having an issue with 2 Foreign Key assignments in my django model. See models.py below:
from django.db import models
from django.contrib.auth.models import User
class userData(models.Model):
user = models.ForeignKey(User)
house = models.CharField(max_length=100)
address = models.CharField(max_length=100, blank=True, null=True)
street = models.CharField(max_length=150)
state = models.CharField(max_length=100)
postcode = models.CharField(max_length=20)
country = models.CharField(max_length=100)
telephone = models.CharField(max_length=20)
subscription = models.IntegerField(default=0)
active = models.IntegerField(default=0)
class area(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class country(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class city(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class foodType(models.Model):
food_type_name = models.CharField(max_length=100)
class restaurant(models.Model):
restaurant_name = models.CharField(max_length=100)
food_type = models.ForeignKey(foodType)
area = models.ForeignKey(area)
country = models.ForeignKey(country)
city = models.ForeignKey(city)
date_added = models.DateField()
main_image = models.ImageField(blank=True, null=True)
website = models.URLField(blank=True, null=True)
summary = models.TextField(blank=True, null=True)
description = models.TextField(blank=True, null=True)
featured = models.IntegerField(default=0)
class restaurantFeature(models.Model):
feature_name = models.CharField(max_length=100)
restaurant_id = models.ForeignKey(restaurant)
Django Foreign Key not working correctly
The image shows the Country and City, not showing correctly, like the FoodType and Area does. Theses show with the + buttons for adding, the mysql database is showing the key next to the fields. I have also tried renaming country and City adding Location after, thinking it could be something with these names.
Appreciate any help with this one.
You're having this issue because you need to reference ALL the models inside the admin.py. Django admin doesn't know what you're referencing.
I have the following models:
class BaseAddress(models.Model):
name = models.CharField(max_length=100)
business_name = models.CharField(max_length=100, blank=True, null=True)
address = models.CharField(max_length=100, blank=True, null=True)
address_2 = models.CharField(max_length=100, blank=True, null=True)
address_3 = models.CharField(max_length=100, blank=True, null=True)
city = models.CharField(max_length=100, blank=True, null=True)
state = models.CharField(max_length=2, blank=True, null=True)
zip_code = models.CharField(max_length=10, blank=True, null=True)
phone = models.CharField(max_length=30, blank=True, null=True)
class Meta:
abstract = True
class ProfileBilling(BaseAddress):
profile = models.OneToOneField(
Profile, related_name='billing_info')
class OrderBilling(BaseAddress):
order = models.OneToOneField(Order, related_name='billing')
name_on_card = models.CharField(max_length=100)
#card_type = models.PositiveSmallIntegerField(
# choices=CARD_TYPE, default=0)
#card_number = models.CharField(
# max_length=16, default=0)
expire_month = models.PositiveSmallIntegerField(
choices=MONTHS, null=True, default=0)
expire_year = models.PositiveSmallIntegerField(
choices=YEARS, null=True, default=1960)
When customers input a billing address, I want to save it in OrderBilling, but I also want to save it in ProfileBilling as their most recent billing address. How do I do so?
How do I go about using forms to save billing address in two different tables when the OrderBilling and ProfileBilling have most of the same fields...?
How do I do this in Django?
Here is my OrderBilling form:
class OrderBillingForm(forms.ModelForm):
class Meta:
model = OrderBilling
exclude = ('order',)
def __init__(self, *args, **kwargs):
super(OrderBillingForm, self).__init__(*args, **kwargs)
self.fields['address'].required = True
self.fields['city'].required = True
self.fields['state'] = USStateField()
self.fields['zip_code'] = us.USZipCodeField()
self.fields['phone'].required = False
self.fields['expire_month'].required = False
self.fields['expire_year'].required = False
def clean(self):
return self.cleaned_data
You can override save() method, But the smarter way in your case would be using post_save signal for this purpose.
After aOrderBilling get saved, You can save its data into ProfileBilling too.
look at some example on google search in case to be familiar with post_save signal,
like:
https://groups.google.com/forum/?fromgroups=#!topic/django-users/2m88qTrqnM8
http://www.djangofoo.com/85/signal-connect-disconnect-django-signals
etc...
then Easyily in your post_save receiver|callback funcstion get the OrderBilling instance
orderbil_instance = kwargs['instance']
And create your ProfileBilling from its data
ProfileBilling.objects.create(name=orderbil_instance.name, ....)
Something like on post_save signal receiver
def do_something(sender, **kwargs):
# Getting OrderBilling instance which get saved just now
orderbil_instance = kwargs['instance']
# Save the data into new ProfileBilling
ProfileBilling.objects.create(name=orderbil_instance.name, ....)