django: daterangefield attribute error - django

I get this error 'int' object has no attribute 'days' in trace this is highlighted camp.save()
My model class:
class Campaign(models.Model):
time_to_next = DateTimeRangeField()
rank = models.PositiveIntegerField()
address = models.ForeignKey(Address)
description = models.CharField(max_length = 200)
display = models.BooleanField()
date_created = models.DateField(auto_now_add=True)
url = models.URLField()
current_promotion = models.ForeignKey(Promotion, related_name="campaign_current_promotion")
promotions = models.ManyToManyField(Promotion)
enabled = models.BooleanField()
My view:
camp = campaign.save(commit=False)
camp.business = bdns
camp.time_to_next = 2
camp.rank = 1
camp.address = addr
camp.display = 1
camp.url = 'http://test1.com'
camp.current_promotion = promo
camp.enabled = True
camp.save()
cp = promo
camp.promotions.add(cp)
what could be the issue?

Related

Django ORM query for filtering product price between two number is not working properly

class Product(models.Model):
product_name = models.CharField(max_length=255,unique=True)
slug = models.SlugField(max_length=255)
brand = models.CharField(max_length=255)
price = models.CharField(max_length=255)
product_image_1 = models.ImageField(upload_to = 'photos/product',blank = False)
product_image_2 = models.ImageField(upload_to = 'photos/product', blank = False)
product_image_3 = models.ImageField(upload_to = 'photos/product', blank = False)
product_image_4 = models.ImageField(upload_to = 'photos/product',blank = False)
product_description = models.TextField()
category_id = models.ForeignKey(Categories,on_delete=models.CASCADE)
subcategory_id = models.ForeignKey(SubCategories, on_delete=models.CASCADE)
stock = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.product_name
def get_url(self):
return reverse('product_detail',args = [self.category_id.slug , self.subcategory_id.slug,
self.slug ])
'''view'''
val=request.POST.get('value')
val = re.findall("\d+", val) # code to get all inigers from string
min_price = int(val[0])
max_price = int(val[1])
print(min_price)
print(max_price)
***product = Product.objects.filter(category_id = categories,is_active =
True,price__gte = min_price, price__lte = max_price)***
when i give value greater than max_value product object returns null object
I want all objects between the two min_value and max_value

Having issue in handling multipart form data in django rest framework

I have an addproduct api in which frontend is sending a multipart/formdata in a post axios call. multipart/form-data is used because there is an image field that needs to be sent in arrays.
But I got the following error.
Category field is required
The data is sent like this
name: Soap
category[0]: 7
category[1]: 23
brand: 7
collection: 11
availability: in_stock
warranty: no_warranty
service: cash_on_delivery
rating: 3
best_seller: true
top_rated: true
featured: true
main_product_image: (binary)
merchant: 2
variants[0][product_id]: fgfdg
variants[0][price]: 127
variants[0][quantity]: 1
variants[0][color]: red
variants[0][size]: M
variants[0][variant_availability]: not_available
variants[0][variant_image]: (binary)
variants[1][product_id]: fgfdg
variants[1][price]: 127
variants[1][quantity]: 1
variants[1][color]: red
variants[1][size]: M
variants[1][variant_availability]: not_available
variants[1][variant_image]: (binary)
The same issue is with the variants.
My models:
class Variants(models.Model):
product_id = models.CharField(max_length=70, default='OAXWRTZ_12C',blank=True)
price = models.DecimalField(decimal_places=2, max_digits=20,default=500)
size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True)
color = models.CharField(max_length=70, default="not applicable",blank=True,null=True)
variant_image = models.ImageField(upload_to="products/images", blank=True,null=True)
thumbnail = ImageSpecField(source='variant_image',
processors=[ResizeToFill(100, 50)],
format='JPEG',
options={'quality': 60})
quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity of given product
variant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available')
class Meta:
verbose_name_plural = "Variants"
def __str__(self):
return self.product_id
#Product Model
class Product(models.Model):
merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True)
category = models.ManyToManyField(Category, blank=False)
sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
featured = models.BooleanField(default=False) # is product featured?
best_seller = models.BooleanField(default=False)
top_rated = models.BooleanField(default=False)
tags = TaggableManager(blank=True) # tags mechanism
name = models.CharField(max_length=150,unique=True)
main_product_image = models.ImageField(upload_to="products/images", null=True, blank=True)
thumbnail = ImageSpecField(source='main_product_image',
processors=[ResizeToFill(100, 50)],
format='JPEG',
options={'quality': 60})
slug = models.SlugField(max_length=200,blank=True)
description = RichTextField(blank=True)
#picture = models.ImageField(upload_to="products/images", null=True, blank=True)
picture = models.ManyToManyField(ImageBucket,null=True,blank=True,verbose_name="Add extra 3 images")
rating = models.IntegerField(choices=((1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 5))
)
availability = models.CharField(max_length=70, choices=AVAILABILITY, default='in_stock')
warranty = models.CharField(max_length=100, choices=WARRANTY, default='no_warranty')
services = models.CharField(max_length=100, choices=SERVICES, default='cash_on_delivery')
variants = models.ManyToManyField(Variants,related_name='products')
My view:
class ProductAddAPIView(CreateAPIView):
permission_classes = [IsAuthenticated]
parser_classes = [MultiPartParser,JSONParser,FormParser]
# queryset = Product.objects.all()
serializer_class = AddProductSerializer
Here I have used parser class just in case if it works.
Updated Code:
class AddProductSerializer(serializers.ModelSerializer):
id = serializers.PrimaryKeyRelatedField(read_only=True)
variants = VariantSerializer(many=True)
slug = serializers.SlugField(read_only=True)
class Meta:
model = Product
fields = ['id','merchant','featured', 'top_rated','category','brand','collection','sub_category',
'name','slug','description', 'main_product_image','best_seller','picture',
'rating','availability','warranty','services','variants']
#depth = 1
def create(self, validated_data):
#user = self.context['request'].user
picture_data = validated_data.get('picture')
merchant = validated_data.get('merchant')
category_data = validated_data.get('category')
featured = validated_data.get('featured')
top_rated = validated_data.get('top_rated')
brand = validated_data.get('brand')
collection = validated_data.get('collection')
sub_category = validated_data.get('sub_category')
name = validated_data.get('name')
description = validated_data.get('description')
main_product_image = validated_data.get('main_product_image')
best_seller = validated_data.get('best_seller')
rating = validated_data.get('rating')
availability = validated_data.get('availability')
warranty = validated_data.get('warranty')
services = validated_data.get('services')
#variants_logic
variants_data = validated_data.get('variants')
#breakpoint()
print(variants_data)
# from pudb import set_trace;set_trace()
#products-logic
product = Product.objects.create(featured=featured,top_rated=top_rated,
brand=brand,collection=collection,sub_category=sub_category,
name=name,description=description,
main_product_image=main_product_image,
best_seller=best_seller,rating=rating,
availability=availability,warranty=warranty,
services=services,merchant=merchant)
product.save()
product.category.set(category_data)
# product.variants.set(variants_data)
product.save()
for variants_data in variants_data:
abc = Variants.objects.create(**variants_data)
product.variants.add(abc)
product.save()
return product

How to use update_or_create with defaults argument

I have the model League
class League(models.Model):
league = models.IntegerField(primary_key=True)
league_name = models.CharField(max_length=200)
country_code = models.ForeignKey("Country",null=True, on_delete=models.SET_NULL)
season = models.ForeignKey("Season", null=True,on_delete = models.SET_NULL, to_field = "season")
season_start = models.DateField(null = True) season_end = models.DateField(null = True)
league_logo = models.URLField(null = True) league_flag = models.URLField(null = True)
standings = models.IntegerField(null=True)
is_current = models.IntegerField(null=True)
I created objects from this model. After it i needed to add some additional fields to League model after adding those fields League object became so
class League(models.Model):
league = models.IntegerField(primary_key=True)
league_name = models.CharField(max_length=200)
country_code = models.ForeignKey("Country",null=True, on_delete=models.SET_NULL)
season = models.ForeignKey("Season", null=True,on_delete = models.SET_NULL, to_field = "season")
season_start = models.DateField(null = True) season_end = models.DateField(null = True)
league_logo = models.URLField(null = True) league_flag = models.URLField(null = True)
standings = models.IntegerField(null=True)
is_current = models.IntegerField(null=True)
cover_standings = models.BooleanField(null=True)
cover_fixtures_events = models.BooleanField(null=True)
cover_fixtures_lineups = models.BooleanField(null=True)
cover_fixtures_statistics = models.BooleanField(null=True)
cover_fixtures_players_statistics = models.BooleanField(null=True)
cover_players = models.BooleanField(null=True)
cover_topScorers = models.BooleanField(null=True)
cover_predictions = models.BooleanField(null=True)
cover_odds = models.BooleanField(null=True)
lastModified = models.DateTimeField(auto_now=True)
I did migrations and added these fields to db schema. Now i want to add to these added fields values. I read about
update_or_create method and tried to use it for updating League model objects
leagues_json = json.load(leagues_all)
data_json = leagues_json["api"]["leagues"]
for item in data_json:
league_id = item["league_id"]
league_name = item["name"] country_q =Country.objects.get(country = item["country"])
season = Season.objects.get(season = item["season"])
season_start = item["season_start"]
season_end = item["season_end"]
league_logo = item["logo"]
league_flag = item["flag"]
standings = item["standings"]
is_current = item["is_current"]
coverage_standings = item["coverage"]["standings"]
coverage_fixtures_events = item["coverage"]["fixtures"]["events"]
coverage_fixtures_lineups = item["coverage"]["fixtures"]["lineups"]
coverage_fixtures_statistics = item["coverage"]["fixtures"]["statistics"]
coverage_fixtures_plaers_statistics = item["coverage"]["fixtures"]["players_statistics"]
coverage_players = item["coverage"]["players"]
coverage_topScorers = item["coverage"]["topScorers"]
coverage_predictions = item["coverage"]["predictions"]
coverage_odds = item["coverage"]["odds"]
b = League.objects.update_or_create(league = league_id,
league_name = league_name,
country_code = country_q,season = season,
season_start = season_start,
season_end = season_end,
league_logo = league_logo,
league_flag = league_flag,
standings = standings,
is_current = is_current,
cover_standings = coverage_standings,
cover_fixtures_events = coverage_fixtures_events,
cover_fixtures_lineups = coverage_fixtures_lineups,
cover_fixtures_statistics= coverage_fixtures_statistics,
cover_fixtures_players_statistics = coverage_fixtures_players_statistics,
cover_players= coverage_players,
cover_topScorers = coverage_topScorers,
cover_predictions = coverage_predictions,
cover_odds = coverage_odds)
While i am trying to update objects by above method i get an error
django.db.utils.IntegrityError: duplicate key value violates unique constraint "dataflow_league_pkey"
DETAIL: Key (league)=(1) already exists.
I read about defaults argument of update_or_create method but didn't understand how to useit in my case. Can anyone help me
If you use update_or_create like this, first of all, your code will search the row in db with that all parameters.
I think you want to search league by league id and it works like this
You create the dict by any way of defaults, I just copy your code
defaults = dict(
league_name=league_name,
country_code=country_q,
season=season,
season_start=season_start,
season_end=season_end,
league_logo=league_logo,
league_flag=league_flag,
standings=standings,
is_current=is_current,
cover_standings=coverage_standings,
cover_fixtures_events=coverage_fixtures_events,
cover_fixtures_lineups=coverage_fixtures_lineups,
cover_fixtures_statistics=coverage_fixtures_statistics,
cover_fixtures_players_statistics=coverage_fixtures_players_statistics,
cover_players=coverage_players,
cover_topScorers=coverage_topScorers,
cover_predictions=coverage_predictions,
cover_odds=coverage_odds)
And use this defaults to update or create league with particular id
League.objects.update_or_create(defaults=defaults, league=league_id)
This code will find league with league_id and update it with data which you passed as the defaults parameter
OR
This code will create new league with that id and these params
You can use update_or_create like this
if exist, it return obj and created false
if not exist, it return obj and created true.
obj, created = League.objects.update_or_create(defaults=defaults, league=league_id)

get post by name of user or by id

i have this model
class Post(models.Model):
auth = models.ForeignKey(settings.AUTH_USER_MODEL,default=1)
title = models.CharField(max_length=120)
DESCSPECSOFT = (
(u'Null','Null'),
(u'Phone',u'Phone'),
(u'Car',u'Car'),
(u'Laptop',u'Laptop'),
(u'jops',u'Jops'),
(u'Electronic',u'Electronic'),
(u'Clothes',u'Clothes'),
(u'Makeup',u'Makeup'),
(u'Furnishings',u'Furnishings'),
(u'books',u'books'),
(u'sports',u'sports'),
(u'Property',u'Property'),
(u'Other',u'Other'),
)
City = (
(u'Null','Null'),
(u'Kosti',u'Kosti'),
(u'Khartoum',u'Khartoum'),
(u'Rabbik',u'Rabbik'),
(u'Duwaim',u'Duwaim'),
(u'Sinnar',u'Sinnar'),
(u'Bahri',u'Bahri'),
(u'Omdurman',u'Omdurman'),
(u'Sawakin',u'Sawakin'),
(u'Port Sudan',u'Port Sudan'),
(u'Kasala',u'Kasala'),
(u'Madani',u'Madani'),
(u'Alabid',u'Alabid'),
)
Case = (
(u'Null','Null'),
(u'New',u'New'),
(u'Old',u'Old'),
(u'Second Hand',u'Second Hand'),
(u'Other',u'Other'),
)
Type = models.CharField(choices=DESCSPECSOFT, default='Null',blank = False,null = False,max_length=120)
company = models.CharField(max_length=120)
dis = models.TextField(default="in here you w,ll write all the discribtion about your product")
image = models.ImageField(null=True,blank=True,width_field="width_field", height_field="height_field")
width_field = models.IntegerField(default=0)
height_field = models.IntegerField(default=0)
case = models.CharField(choices=Case, default=99,blank = False,null = False,max_length=120)
price = models.BigIntegerField(default=0)
city = models.CharField(choices=City, default='Null',blank = False,null = False,max_length=120)
address = models.CharField(max_length=120)
draft = models.BooleanField(default=False)
#pup = models.DateField(auto_now=False,auto_now_add=False ,null=False)
date = models.DateTimeField(auto_now=True ,auto_now_add=False)
puplis = models.DateTimeField(auto_now=False ,auto_now_add=True)
objects = PostManager()
def __str__(self):
return self.title
def __unicode__(self):
return self.title
any user can add a post but i want the user name show in the data base means the user how add the post because every post show the admin name not the user how add the post can someone show me haw can i fix this ???
sorry my en is bad ...

why would my databse entries be coming up empty?

I'm trying to create new instances based off of the form below however when it saves, the database only saves the foreign key value and the order value but nothing else. Any Idea why?
models:
class danceType(models.Model):
eventtype = models.ForeignKey(compType)
dance_name = models.CharField(max_length = 20)
Price = models.FloatField(max_length = 7, null=True, blank=True )
field_2 = models.CharField(max_length = 20, null=True, blank=True)
def __unicode__(self):
fields = ('field_2')
return self.dance_name
class dancer(models.Model):
dancetype = models.ForeignKey(danceType)
e_number = models.IntegerField(max_length = 4, null=True, blank=True)
D1_first_name = models.CharField(max_length = 20)
D1_last_name = models.CharField(max_length = 20)
D1_email = models.EmailField(max_length = 20)
city = models.CharField(max_length = 20)
order = models.PositiveIntegerField()
perform = models.NullBooleanField(null=True, blank=True)
View:
if request.method =='POST':
sub_type = request.POST.get("form")
dancetype = request.POST.get("dancetype")
ext = request.POST.get("quantity")
form = modelformset_factory(dancer, form=CompReg, extra=int(ext))
productform = form(queryset = dancer.objects.none())
if sub_type == "submitted":
productform = form(request.POST, request.FILES)
if productform.is_valid():
for p in productform:
dance=p.save(commit=False)
dance.dancetype_id = 4
dance.order = 1
dance.save()
else:
der = "it didnt save"