i have two rendered contexts in my view:
def PostHomeView(request):
RecentPost = Post.objects.order_by("-date").all()[:5]
AllOtherPosts = Post.objects.order_by("-date").all()
template_name = 'lista_post.html'
context = {**strong text**
'recentposts' : RecentPost,
'allposts' : AllOtherPosts
}
return render(request,template_name,context)
in the second one ('allposts') i would like to get all objcects without the first fve
how can i do it?
Use slicing as AllOtherPosts = Post.objects.order_by("-date").all()[5:]
Related
My model is as follows
class Drawing(models.Model):
drawingJSONText = models.TextField(null=True)
project = models.CharField(max_length=250)
Sample data saved in drawingJSONText field is as below
{"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]}
I am trying to write a view file where the data is filtered based on project field and all the resulting queryset of drawingJSONText field are made into one data
def load(request):
""" Function to load the drawing with drawingID if it exists."""
try:
filterdata = Drawing.objects.filter(project=1)
ids = filterdata.values_list('pk', flat=True)
length = len(ids)
print(list[ids])
print(len(list(ids)))
drawingJSONData = dict()
drawingJSONData = {'points': [], 'lines': []}
for val in ids:
if length >= 0:
continue
drawingJSONData1 = json.loads(Drawing.objects.get(id=ids[val]).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]
length -= 1
#print(drawingJSONData)
drawingJSONData = json.dumps(drawingJSONData)
context = {
"loadIntoJavascript": True,
"JSONData": drawingJSONData
}
# Editing response headers and returning the same
response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context))
return response
I runs without error but it shows a blank screen
i dont think the for function is working
any suggestions on how to rectify
I think you may want
for id_val in ids:
drawingJSONData1 = json.loads(Drawing.objects.get(id=id_val).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]
I'm trying to create a new product.
Here is my model :
class Product(models.Model) :
door = models.ForeignKey(Door, on_delete=models.CASCADE)
options = models.ManyToManyField(Option)
Here is my views :
def new_product(request, door_id) :
door = get_object_or_404(Door, id=door_id)
checked = request.POST.getlist('checks[]')
c_checked = []
for check in checked :
new_check = get_object_or_404(Option, name=check)
c_checked.append(new_check)
product = Product.objects.create(
door = door,
options = c_checked,
)
product.save()
return render(request, "confirmation.html")
Unfortunately, when I run the server, I get an error saying :
Direct assignment to the forward side of a many-to-many set is
prohibited. Use options.set() instead
Please help me if you have the answer.
.
According to the documentation, you should use add. create method represents one insert in a database but you want to insert multiple records.
def new_product(request, door_id) :
door = get_object_or_404(Door, id=door_id)
checked = request.POST.getlist('checks[]')
c_checked = []
for check in checked :
new_check = get_object_or_404(Option, name=check)
c_checked.append(new_check)
product = Product.objects.create(door=door)
product.options.add(*c_checked)
return render(request, "confirmation.html")
take a look at these 2 function following:
def get_recommended_products_IT_WORKS(request):
carrello = get_basket(request)
articoli_carrello = Articolo.objects.filter(
variantearticolo__rigareferenza__referenza__paginavendita_referenza__rigacarrello__carrello=carrello)
TEMP = Referenza.objects.filter(rigareferenza__variante_articolo__articolo__in=articoli_carrello)
recommended_products = RecommendedProduct.objects.exclude(paginavendita_referenza__referenza__in=TEMP)
return recommended_products
def get_recommended_products_IT_DOESNT_WORK(request):
carrello = get_basket(request)
articoli_carrello = Articolo.objects.filter(
variantearticolo__rigareferenza__referenza__paginavendita_referenza__rigacarrello__carrello=carrello)
recommended_products = RecommendedProduct.objects.exclude(
paginavendita_referenza__referenza__rigareferenza__variante_articolo__articolo__in=articoli_carrello)
return recommended_products
To me, it seems that they should return the same results, but it's not working this way.
The former works like I need and the latter not.
Can you give me some hints? Thank you.
in the models.py, I have a model which has a list attribute:
Class Controller(models.Model):
def controller(self):
result = []
#...do some works here...
result = xxx
Now I want to use the "result" attribute in the template, in views.py I have:
def results(request):
cmodel = Controller()
cmodel.controller()
firstList = get_list_or_404(Controller, 'I am not sure how to write this filter')
return render_to_response('blablabla/')
I am not sure how to write the filter, since the samples are giving something like "pk=1", but I don't have any primary keys or ids for the 'result' object. Can anyone help me? Thank you.
Your controller function should return result:
Class Controller(models.Model):
def controller(self):
result = []
#...do some works here...
result = xxx
return result # <----------
And then you can get it as:
c = Controller()
result_list = c.controller()
Is that what you want?
In my views.py I have a method:
#......
def get_filter_result(self, customer_type, tag_selected):
list_customer_filter=[]
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected))
for customer_filter in customers_filter:
customer_filter.list_authorize_sale_type = sale_type_selected(customer_filter.authorize_sale_type)
list_customer_filter.append(customer_filter)
return list_customer_filter
**My case tag_selected is the checkbox values that user checked
I have a problems with tag_selected(is the list=1,2,3,...) that pass from my url
/?customer_type=TDO&tag=2 ===>filter okay
/?customer_type=TDO&tag=3 ===>filter okay
?customer_type=TDO&tag=2,3 ===>How Can I add And condition in filter?
for example
if len(tag_selected)==1:
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected))
else:
customers_filter = Customer.objects.filter(Q(type__name=customer_type),
Q(active=True),
Q(tag__id=tag_selected[0])
Q(tag__id=tag_selected[1])
Q(tag__id=tag_selected[2])
...
)
This works for both single and multiple conditions:
idseq = request.POST['tag'].split(',')
tag_qs = reduce(operator.or_, (Q(tag__id=x) for x in idseq))
Customers.objects.filter(..., tag_qs)