FieldError at /add-to-cart/test-product1 - javascript

Hello guys i need help here please, while trying my dd to cart button i received this message.
FieldError at /add-to-cart/test-product1/
Cannot resolve keyword 'ordered' into field. Choices are: id, item, item_id, order, quantity
my views.py for the add to cart function.
def add_to_cart(request, slug):
item = get_object_or_404(Item, slug=slug)
order_item, created = OrderItem.objects.get_or_create(
item=item,
user=request.user,
ordered=False
)
order_qs = Order.objects.filter(user=request.user, ordered=False)
if order_qs.exists():
order = order_qs[0]
# check if the order item is in the order
if order.items.filter(item__slug=item.slug).exists():
order_item.quantity += 1
order_item.save()
else:
ordered_date = timezone.now()
order = Order.objects.create(user=request.user,
ordered_date=ordered_date)
order.items.add(order_item)
return redirect("store:product", slug=slug)
my models.py
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
item = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add=True)
ordered_date = models.DateTimeField()
ordered = models.BooleanField(default=False)
def __str__(self):
return self.user.username

You are trying to perform a get_or_create on the OrderItem model. However, this model does not contain the field ordered (as confirmed in your comment). The field ordered only exists in the Order model, hence why Django will raise an exception saying that the field does not exist in the model.

then include all naming's to your view.py.```
```my views```
```in the views.py in my cart function, I used the order,
created method whereby i queried my Order Class model from my model.py.
then I made sure that the object that is being called has also be
mentioned also in my model class. just like the customer object.
if the object been called hasn't been mentioned you are must
likely to get a field error.```
def cart(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
else:
items = []
context = {'items':items}
return render(request, 'shop/cart.html', context)
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False, null=True, blank=False)
transaction_id = models.CharField(max_length=200, null=True)
def __str__(self):
return str(self.id)
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)
def __str__(self):
return str(self.product.id)

Related

Is it possible to send data from one form to multiple models in django using a normal form instead of multiple ModelForm?

I know it sounds weird, but I'm struggling a lot to show multiple tables with an inline, which populates three models with foreign keys, so I'm trying to find easier solutions than creating a script with JavaScript (which I don't know how to do) or a very complicated solution. My idea is to create a normal form with all of the fields and use it to fill all the models.
class Order(models.Model):
customer = models.ForeignKey("Customer", on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
class Meta:
ordering = ("-created",)
def get_absolute_url(self):
return reverse("sales:order-update", kwargs={"pk": self.pk})
def __str__(self):
return "Order {}".format(self.id)
def get_total_cost(self):
return sum(item.get_cost() for item in self.items.all())
class OrderItem(models.Model):
order = models.ForeignKey(Order, related_name="items", on_delete=models.CASCADE)
product = models.ForeignKey(
Product, related_name="order_items", on_delete=models.CASCADE
)
quantity = models.PositiveIntegerField(default=1)
def __str__(self):
return "{}".format(self.id)
def get_cost(self):
return self.price * self.quantity
class Customer(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
phone = models.CharField(max_length=15, null=True)
email = models.EmailField()
address_line_1 = models.CharField(max_length=250)
address_line_2 = models.CharField(max_length=60, null=True)
postal_code = models.CharField(max_length=20)
city = models.CharField(max_length=100)
state = models.CharField(max_length=100, null=True)
country = models.CharField(max_length=100, default="Mexico")
def __str__(self):
return f"{self.first_name} {self.last_name}"
def get_absolute_url(self):
return reverse("sales:modalcustomercreation")
I only tried the first solution in [this stackoverflow question](https://stackoverflow.com/questions/5720287/django-how-to-make-a-form-for-a-models-foreign-keys) but It doesn't worked.

size date not saving in cartitem model but the product is saving.. Any solution how to save the size data also?

views.py
def add_to_cart(request, pk):
variant = request.GET.get('variant')
product = Product.objects.get(pk =pk)
user = request.user
cart , _ = Cart.objects.get_or_create(user = user, is_paid = False)
cart_item = CartItem.objects.create(cart = cart , product = product ,)
if variant:
variant = request.GET.get('variant')
size_variant = SizeVariant.objects.get(size_name = variant)
color_variant = ColorVariant.objects.get(color_name = variant)
cart_item.color_variant = color_variant
cart_item.size_variant = size_variant
cart_item.save()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
models.py
class CartItem(models.Model):
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
color_variant = models.ForeignKey(ColorVariant, on_delete=models.CASCADE,null=True, blank=True)
size_variant = models.ForeignKey(SizeVariant, on_delete=models.CASCADE ,null=True, blank=True)
quantity = models.PositiveIntegerField(default=0)
coupon = models.ForeignKey(Coupon, on_delete=models.SET_NULL, null=True, blank=True)
[22/Aug/2022 16:17:38] "GET /account/add_to_cart/1/?variant= HTTP/1.1" 302 0
XXX
16049.0
class SizeVariant(models.Model):
size_name = models.CharField(max_length=100)
price = models.IntegerField(default=0)
def __str__(self):
return self.size_name
------------------------------------------------------------///////
I don't know the exact problem, but I'd recommend to use get_object_or_404(), and also creating instance directly using create() instead of first creating then updating, so try below view:
def add_to_cart(request, pk):
variant = request.GET.get('variant')
product = get_object_or_404(Product,pk=pk)
user = request.user
cart , _ = Cart.objects.get_or_create(user = user, is_paid = False)
if variant:
size_variant = get_object_or_404(SizeVariant,size_name=variant)
color_variant = get_object_or_404(ColorVariant,color_name=variant)
CartItem.objects.create(cart = cart, product = product,color_variant=color_variant,size_variant=size_variant)
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Get the id of variant instead of name. Just send the id with ajax like how you got the same object's name.
def add_to_cart(request, pk):
variant = request.GET.get('variant')
product = Product.objects.get(pk =pk)
user = request.user
cart , _ = Cart.objects.get_or_create(user = user, is_paid = False)
cart_item = CartItem.objects.create(cart = cart , product = product ,)
if variant:
variant_id = request.GET.get('variant_id')
size_variant = SizeVariant.objects.get(id=variant_id)
color_variant = ColorVariant.objects.get(id=variant_id)
cart_item.color_variant = color_variant
cart_item.size_variant = size_variant
cart_item.save()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
I can help you out about ajax if you can share the ajax side of this page.

Extracting users from manytomany field from model Django

I want to extract users who follow specific user. I have two models here
class User(AbstractUser):
pass
class Follower(models.Model):
user = models.ForeignKey(User,null=True, on_delete=models.CASCADE, related_name="follow")
following = models.ManyToManyField(User, null=True, blank=True)
views.py
def profile(request, userq):
usera = User.objects.get(id = userq)
posts = Post.objects.filter(userp = userq).all()[::-1]
print(userq)
try:
follow1 = Follower.objects.filter(following = usera).all()
except:
follow1= []
try:
follow2 = Follower.objects.get(user = usera).following.all()
except:
f = Follower.objects.create(user = usera)
follow2= f.following.all()
print(follow1)
print(follow2)
return render(request,"network/profile.html",{
"posts":posts,"usera":usera,"follow1":follow1,"follow2":follow2
})
How to do achieve this in views.py?
If you need users which are followed by specific user:
Follower.objects.get(user = your_user).following.all()
If you need users who follow specific user:
User.objects.filter(follower__user = your_user)
Django docs

Configure Django model form with jQuery and JavaScript

I have three models :
class Instances(models.Model):
name_of_instances = models.CharField(max_length=255)
url_of_instances=models.URLField(max_length=255,default='')
def __str__(self):
return self.name_of_instances
class Projects(models.Model):
name_of_instances = models.ForeignKey(Instances,on_delete=models.CASCADE)
name_of_jproject = models.CharField(max_length=255)
project_id= models.CharField(max_length=25)
def __str__(self):
return self.name_of_project
class All(models.Model):
choices_instance=Instances.objects.all()
b = [str(i.name_of_instances) for i in choices_instance]
a=[str(i.url_of_instances) for i in choices_instance]
choices_instance=tuple(zip(a,b))
name = models.CharField(max_length=255,choices=choices_instance)
project = models.CharField(max_length=255,)
story = models.CharField(max_length=500)
depends_on = models.CharField(max_length=500, default='')
rfc = models.CharField(max_length=255)
def __str__(self):
return self.name
I have a models form:
class Form(ModelForm):
class Meta:
model = All
fields =('name','project','story','depends_on','rfc')
In template, I want to know what user has drop down in 'name' field , and I want to send the name value to back end function where I will filter out all the projects associated with name value, and send the result to 'project' field as choices (drop down).
i got the solution using java script and ajax on the template

django bulk remove and add many to many relationships

Im having a problem with bulk many to many relationship removing and adding.
This is the JS that sends the pk of the user to be updated and the pk of the skills that will be added to the many to many.
function attachskillls(){
var checkedValues = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
console.log(checkedValues)
data = {
'skills' : checkedValues,
'pk' : getUrlVars()["id"]
}
console.log(data)
$.ajax({
type: "POST",
url: "/api/skill/attch/",
data: JSON.stringify(data),
contentType: "application/json",
dataType: "json"
})
data is packed like this
{"skills":["1","2","3"],"pk":"1"}
This is the model the skills will be related to
class Resource(models.Model):
title = models.CharField(max_length=10)
preferred_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=30)
employstatus = models.CharField(max_length=20)
employer = models.ForeignKey('Employer')
role = models.ForeignKey('Role')
location = models.ForeignKey('Location')
workphone = models.CharField(max_length=25, blank=True, null=True)
mobile_phone = models.CharField(max_length=15, blank=True, null=True)
email = models.CharField(max_length=15, blank=True, null=True)
notes = models.CharField(max_length=200, blank=True, null=True)
updated_by = models.CharField(max_length=30, blank=True, null=True)
skillset = models.ManyToManyField('ReferenceSkillList')
This is my api so far I am trying to filter resource by pk so I have the correct user to add the skills to then to clear all relationships that may already be added then to bulk add the new relationships.
def Skillattachment(request):
body = json.loads(request.body)
if request.method == "POST":
pk = body['pk']
skills = body
res = Resource.objects.filter(pk=pk)
res.skillset.clear()
res.skillset.add(skills)
else:
search_id = ''
return HttpResponse(json.dumps(body), content_type='application/json')
Is there a better way to do what I am trying todo?
I I currently get the error
'QuerySet' object has no attribute 'skillset'
though I am unsure why? maybe I have made the M2M incorrectly but I have followed the docs
You should use res = Resource.objects.get(pk=pk) instead. filter would give you a queryset as result.
Also your variable skills is just a data structure not objects. You might need:
skills = ReferenceSkillList.objects.filter(id__in=body['skills'])
res = Resource.objects.get(pk=pk)
res.skillset.clear()
res.skillset.add(*skills)
Django docs.

Categories

Resources