Configure Django model form with jQuery and JavaScript - 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

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.

How to write the json for patch on Django REST Framework

I have PATCH button form on ModelViewSet
class CompanyViewSet(viewsets.ModelViewSet):
serializer_class = s.CompanySerializer
queryset = m.Company.objects.all()
def patch(self, request, id, format=None):
print(id)
Now I try to modify the existing data id = 1
So I write this in textarea and push PATCH button.
{
"id":1,
"name": ""
}
However , there comes error like
patch() missing 1 required positional argument: 'id'
Maybe my json is wrong?? How can I do PATCH?
patch() missing 1 required positional argument: 'id'
Use perform_update like this :
class CompanyViewSet(viewsets.ModelViewSet):
serializer_class = s.CompanySerializer
queryset = m.Company.objects.all()
def perform_update(self, serializer):
instance = serializer.instance
request = self.request
serializer.save(**modified_attrs)
return Response(status=status.HTTP_200_OK)

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

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

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)

Extjs And Grails How can i prevent ancestors

I work a project which server site is Grails, Client Site is Extjs4.1, I use relational database. In this situation i work fine but when i call store then i facing some problem.
This problem based on parents. when I call store like below..... then i must call its parents but i do not want to call its parents..
def stote(){
def prices = []
Price.getAll()?.each{ v ->
def a = v.article,
b = a.brand,
bt = b.brandType,
gp = b.genericProducts,
c = gp.categories,
m = b.manufacturers
def manufacture = [id:m.id, name:m.name]
def category = [id:c.id, name:c.name]
def genericProduct = [id:gp.id, name:gp.name, m01i001001:category]
def brandType = [id:bt.id, name:bt.name]
def brand = [id:b.id, name:b.name, m01i002001:manufacture, m01i003001:genericProduct, m01i004001:brandType]
def article = [id:a.id, name:a.name, mbcode:a.mbcode, pbcode:a.pbcode, details:a.details, m01i005001:brand]
def price = [id: v.id, m01i006001:article, price:v.price, date:v.date]
prices << price
}
return prices
}
Those are belongTo association key
m01i001001, m01i002001, m01i003001,m01i004001,m01i005001,m01i006001
my belongTo like as
belongsTo : [{
model : '${pkgName}.M01I005001',
associatedName : 'M01I005001' ,
associationKey : 'm01i005001' ,
primaryKey : 'id' ,
foreignKey : 'brandId'
}],
i want to call like this store...
def stote(){
def prices = []
Price.getAll()?.each{ v ->
def a = v.article
def article = [id:a.id, name:a.name, mbcode:a.mbcode, pbcode:a.pbcode, details:a.details]
def price = [id: v.id, m01i006001:article, price:v.price, date:v.date]
prices << price
}
return prices
}
but when i call this store then client side loading problem. I can not lazy its parents. its show always eager.
Please let me know if you have any idea to resolve this error.
Thanks in advance
This is not a solution for this. I create a proxy model for this and i remove all relation which are not necessary then i solve my problem that means i keep only one belongsto so keep only one association key.

Categories

Resources