I am trying to exclude that orders which in my orderRequest table, but it show only that orders which is in orderRequest table and exclude the others.Function get the right id's of orders but it not exclude that orders. It exclude the other orders and show that orders which already in orderRequest table
View.py
class OrderProduct_View(TemplateView):
template_name = 'purchase/orderProduct.html'
def get(self, request, *args, **kwargs):
allOrder = OrderProduct.objects.all()
allOrd = Order.objects.all()
categories = Category.objects.all()
categoryId = self.request.GET.get('SelectCategory')
product = Product.objects.filter(category_id=categoryId)
def filter_order(order):
try:
orderReq = order.orderRequest
return orderReq
except:
return True
filteredOrders = list(filter(filter_order, allOrd))
args = {'categories': categories, 'product': product, 'filteredOrders': filteredOrders}
return render(request, self.template_name, args)
Model.py
class OrderProduct(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
description = models.CharField(max_length=90)
quantity = models.IntegerField()
order_cancel = models.BooleanField(default=False)
class Order(models.Model):
orderProduct = models.ForeignKey(OrderProduct, on_delete=models.CASCADE)
created_by = models.CharField(max_length=20)
created_at = models.DateTimeField(auto_now_add=True)
destination = models.CharField(max_length=30)
vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE)
shipping_cost = models.IntegerField()
class OrderRequest(models.Model):
order_status = models.CharField(max_length=10)
order = models.OneToOneField(Order, related_name='orderRequest', on_delete=models.CASCADE)
HTML
{% for allOrders in filteredOrders%}
{{ allOrders.orderProduct.id }}
{{ allOrders.orderProduct.product.name }}
{{ allOrders.orderProduct.quantity }}
<button>Place Order</button>
{% endfor %}
You can use the isnull lookup [Django docs] to find instances which don't have a related instance, so to find Order instances which have no OrderRequest instances you can use:
Order.objects.filter(orderRequest__isnull=True)
Hence you can write your view as:
class OrderProduct_View(TemplateView):
template_name = 'purchase/orderProduct.html'
def get(self, request, *args, **kwargs):
filteredOrders = Order.objects.filter(orderRequest__isnull=True)
categories = Category.objects.all()
categoryId = self.request.GET.get('SelectCategory')
product = Product.objects.filter(category_id=categoryId)
args = {'categories': categories, 'product': product, 'filteredOrders': filteredOrders}
return render(request, self.template_name, args)
Note: Class names should be in PascalCase so OrderProductView instead of OrderProduct_View. Variable names should be in
snake_case so filtered_orders instead of filteredOrders,
etc. See PEP 8 -- Style Guide for Python
Code
A:your function filter_order does not work, it always True;
B: return False in your try part
Related
I am creating a blog app in django. For that, I have made a page where all available blogs are listed. I am using generic.ListView view to achieve this. But, I also want to create a writer's section where I can list some details about the writers that have written those blogs. For this, I need to get all the users that have written a blog and then find distinct users from that and list out their username. I have an author field in my Blog model that keeps track of the writer user. How can I get the distinct usernames of these writers and pass it into my template?
Models.py:
class Blog(models.Model):
blog_head = models.CharField(max_length=100)
blog_header_image = models.ImageField(upload_to="photos/blogs/", null=True, blank=True)
#blog_content = models.TextField()
blog_content = RichTextField(blank=True, null=True)
#blog_summary = models.TextField(max_length=355)
blog_summary = models.CharField(max_length=100)
author = models.ForeignKey(User, on_delete=models.CASCADE)
blog_date = models.DateField(auto_now_add=True)
likes = models.ManyToManyField(User, related_name='blog_post_likes', blank=True)
def __str__(self):
return self.blog_head
def get_absolute_url(self):
return reverse('blog-full', args=[str(self.id)])
def blog_likes_count(self):
return self.likes.count()
Views.py:
class blogs_getting_Listview(ListView):
model = Blog
template_name = 'blogs.html'
ordering = ["-blog_date"]
def get_context_data(self, *args, **kwargs):
context = super(blogs_getting_Listview, self).get_context_data()
authors_id_list = Blog.objects.get(id=id).author
authors_list = ""
for author_in in authors_id_list:
author_obj = User.objects.get(id=author_id)
authors_list = authors_list + author_obj
context.update({
"authors_list": authors_list
#'more_context': Model.objects.all(),
})
print(type(context["authors_list"]))
return context
urls.py:
urlpatterns = [
#path('', views.blogs_getting, name='blogs/'),
path('', blogs_getting_Listview.as_view(), name='blogs/'),
path('blog/<int:pk>', blogs_getting_Detailview.as_view(), name='blog-full'),
path('new_blog/', add_blog_view.as_view(), name='add_blog'),
path('update_blog/<int:pk>', edit_blog_view.as_view(), name='update_blog' ),
path('delete_blog/<int:pk>', delete_blog_view.as_view(), name='delete_blog' ),
path('like/<int:pk>', like_view, name='like_blog' ),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
template:
{% for author in authors_list %}
<p>{{ author }}</p>
{% endfor %}
(Here I am trying to render the author objects' queryset on my page.)
Thankful for any help
Try accessing directly the author entitie:
class blogs_getting_Listview(ListView):
model = Blog
template_name = 'blogs.html'
ordering = ["-blog_date"]
def get_context_data(self, *args, **kwargs):
context = super(blogs_getting_Listview, self).get_context_data()
authors = Blog.objects.get(id=id)
authors_list = ""
for author in authors:
author_obj = User.objects.get(id=author.id)
authors_list.append(author_obj)
context["authors_list"] = authors_list
return context
I would like to have a page that contains product and related competitor products with it. I tried, but all the times competitor products stay same. Would you please help me?
models:
class Product(models.Model):
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.CharField(max_length=120)
brand = models.CharField(max_length=120)
product = models.CharField(max_length=120)
price = models.DecimalField(decimal_places=2,max_digits=100)
class Comp_Product(models.Model):
product = models.ForeignKey(Product,on_delete=models.CASCADE)
competitor = models.URLField()
price = models.DecimalField(decimal_places=2,max_digits=100)
change = models.FloatField()
stock = models.BooleanField()
last_update = models.DateField(auto_now_add=True)
views:
class ProductListView (ListView):
model = Comp_Product
context_object_name = 'comp_products'
template_name = 'products.html'
class ProductDetailView (LoginRequiredMixin,DetailView):
model = Product
template_name = 'product.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comp_products'] = Comp_Product.objects.all()
return context
urls.py:
path('product/<int:pk>/', ProductDetailView.as_view(),name='product_detail'),
path('comp_products/', ProductListView.as_view(),name='comp_products'),
Here you say comp_products = All the Comp Products in the database.
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
>>> context['comp_products'] = Comp_Product.objects.all()
return context
What do you display in your template? Is it {{comp_products}} or
{% for pr in product.comp_products.all %}
{{ pr }}
{% endfor %}
For this you need related_name="products" in your product field in the Comp_Product model
You may find the template that I wrote:
{%for comp_product in comp_products %}
{{comp_product.competitor}} - {{comp_product.price}} -
{{comp_product.change}} - {{comp_product.stock}} - {{comp_product.last_update}}
{%endfor%}
I have a django UpdateView which needs to inherit three different models and different models. CreateView is working fine with three different modelforms.
models.py:
class Employee(models.Model):
"""
Create employee attributes
"""
employee_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
e_id = models.IntegerField(unique=True, null=True, blank=True)
first_name = models.CharField(max_length=128,blank=True)
last_name = models.CharField(max_length=128, blank=True)
.....
class WorkExperience(models.Model):
"""
Stores employee previous work experiences
"""
employee = models.ForeignKey('Employee', related_name='we_employee', on_delete=models.CASCADE, null=True)
previous_company_name = models.CharField(max_length=128, null=True)
job_designation = models.CharField(max_length=128, null=True)
from_date = models.DateField(null=True)
......
class Education(models.Model):
"""
Stores employee education background
"""
employee = models.ForeignKey('Employee', related_name='edu_employee', on_delete=models.CASCADE, null=True)
institution_name = models.CharField(max_length=128, null=True)
degree = models.CharField(max_length=128, null=True)
.....
views.py:
class EmployeeUpdateView(LoginRequiredMixin,UpdateView):
"""
Update a created a employee
"""
login_url = '/authentication/login/'
template_name = 'employee/employee_add_form.html'
form_class = EmployeeAddModelForm
work_form_class = WorkExperienceForm
education_form_class = EducationForm
queryset = Employee.objects.all()
def form_valid(self, form):
print(form.cleaned_data)
return super().form_valid(form)
def get_object(self):
id_ = self.kwargs.get("id")
return get_object_or_404(Employee, id=id_)
WHen I go to Update view, I am only able to update EmployeeAddModelForm values. But other form's(WorkExperienceForm, EducationForm ) fields do not appear let alone edit the values of the fields.
I suppose my views.py is not correct.
I need suggestion to correct my updateview.
If you want to put multiple forms in one HTML file, in my way, write as follows.
class EmployeeUpdateView(LoginRequiredMixin,UpdateView):
login_url = '/authentication/login/'
def form_valid(self, form):
print(form.cleaned_data)
return super().form_valid(form)
def get(self, request, *args, **kwargs):
id_ = self.kwargs.get("id")
user = Employee.objects.get(id=id_)
work = WorkExperience.objects.get(employee=user)
education = Education.objects.get(employee=user)
return render(request, self.template_name, {
'form': EmployeeAddModelForm(instance=user),
'work_form': WorkExperienceForm(instance=work),
'education_form': EducationForm(instance=education)
}
)
def post(self, request):
first_name = request.POST['first_name']
# Your own code...
.....
I think the argument of each form depends on the definition of Form.
And in a very simple way, the HTML file looks like this:
<body>
<form method="post">
{% csrf_token %}
{{ employ_form }}
{{ work_form }}
{{ edu_form }}
<button type="submit">OK</button>
</form?
</body>
</html>
I'm not sure if this is the best option.
How about putting forms into get_context_data?
Something like
context['form1'] = EmployeeAddModelForm()
context['form2] = WorkExperienceForm()
Etc.
Edit:
def get_context_data(self, **kwargs):
context = super(EmployeeUpdateView, self).get_context_data(**kwargs)
context['form'] = EmployeeAddModelForm()
context['form2'] = WorkExperienceForm()
context['form3'] = EducationForm()
return context
I have a question. In my DetailView I want to placed data from two models. Moreover, I want to filter them, that on my scenario-detail was only that comments related to specyfic scenario, related by ForeignKey->Scenario.
My views.py:
class ScenarioDetailView(LoginRequiredMixin, DetailView):
model = Scenario
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comments'] = Comment.objects.all()
return context
And in scenario_detail.html i have a simple {{ comments }}
I thinking on filtering my comment object in views.py, something like: Comment.objects.get(commentScenario=Scenario.id) but it didn't work at all.
My models.py:
class Scenario(models.Model):
scenarioTitle = models.CharField(max_length=256)
scenarioArea = models.ForeignKey(ScenarioArea, on_delete=models.CASCADE)
scenarioAuthor = models.ForeignKey(User, on_delete=models.CASCADE)
scenarioDate = models.DateTimeField(default=timezone.now)
scenarioDescription = models.TextField()
def __str__(self):
return self.scenarioTitle
def get_absolute_url(self):
return reverse('scenario-detail', kwargs={'pk': self.pk})
class Comment(models.Model):
commentText = models.CharField(max_length=256)
commentScenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
commentAuthor = models.ForeignKey(User, on_delete=models.CASCADE)
commentDate = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.commentText
And urls.py:
path('scenario/<int:pk>/', ScenarioDetailView.as_view(), name='scenario-detail'),
Could someone help me?
You don't need to send any extra context to your template in order to show the related comments; As you already have the related comments to your Scenario with backward relationship.
So you can simply use Scenario.comment_set.all in your template to access them.
As an example:
{% for comment in object.comment_set.all %}
{{ comment }}
{% endfor %}
try this
class ScenarioDetailView(LoginRequiredMixin, DetailView):
model = Scenario
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comments'] = Comment.objects.filter(commentScenario=self.object)
return context
I am a beginner in Django, hence this might be a simple issue. But I'm not able to get past this successfully.
This is my models.py
class Category(models.Model):
name = models.CharField(max_length=128)
abbr = models.CharField(max_length=5)
def __unicode__(self):
return self.name
class Fabric(models.Model):
name = models.CharField(max_length=128)
abbr = models.CharField(max_length=5)
def __unicode__(self):
return self.name
class Manufacturer(models.Model):
name = models.CharField(max_length=128)
location = models.CharField(max_length=128)
name_abbr = models.CharField(max_length=5, default=None)
loc_abbr = models.CharField(max_length=5, default=None)
def __unicode__(self):
return self.name
class Images(models.Model):
design_id = models.CharField(max_length=128)
file = models.ImageField(upload_to='images')
cost_price = models.FloatField()
category = models.ForeignKey(Category, on_delete=models.CASCADE)
fabric = models.ForeignKey(Fabric, on_delete=models.CASCADE)
manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
selling_price = models.FloatField()
aliveness = models.IntegerField()
date_added = models.DateTimeField(default=datetime.datetime.now)
set_cat = models.IntegerField()
set_cat_no = models.IntegerField()
set_cat_name = models.CharField(max_length=50, blank=True)
I'm building an apparel management database system which contains cloth designs.
My forms.py is
class ImagesForm(forms.ModelForm):
class Meta:
model = Images
fields = ('file','cost_price','set_cat_no','set_cat_name',)
My views.py
#login_required
def uploadphoto(request):
context = RequestContext(request)
context_dict = {}
if request.method == 'POST':
form = ImagesForm(request.POST,request.FILES)
if form.is_valid():
image = form.save(commit=False)
image.save()
return render_to_response(request,'cms/upload-photo.html', {'upload_image': form})
else:
print form.errors
else:
form = ImagesForm()
context_dict = {'upload_image': form}
return render_to_response('cms/upload-photo.html',context_dict, context)
My upload-photo.html is
{% block main %}
<form id="upload_form" method="post" action="/zoomtail/upload-photo/" enctype="multipart/form-data">
{% csrf_token %}
{{ upload_image }}
</form>
{% endblock %}
The problem here is when I goto /upload-photo/ I don't see the drop-downs to the foreign keys to categories, fabric and manufacturers. I have read that it should be automatically generated but I don't see any.
And selling_price has to be calculated based on the given percentage increase from the cost_price which has to be entered in the form. How do I do this? And aliveness of an apparel has to be set by default as 1. How to do this?
set-cat field of an apparel is 1 if it belongs to a set and 2 if it belongs to a catalogue. How do I get a radio button asking whether set or catalogue and that to be captured as an integer in the database?
And design-id field of an apparel has to be a string which contains abbreviations of category, fabric, manufacturer, etc etc all the fields it belongs to. How do I do this dynamically?
I know, this is a very long question but I'm a newbie and these are literally giving me headache since days. I shall be very thankful to those who answer this.
I believe the issue with the dropdown is that you've excluded the fields from ImageForm. You have:
fields = ('file','cost_price','set_cat_no','set_cat_name',)
but should have:
fields = ('file','cost_price','set_cat_no','set_cat_name', 'category', 'fabric', 'manufacturer,)`
if that doesn't work, are there any options in your database for Categories, Fabric, and Manufacturer? If your tables are empty, the dropdown will be empty. If there are values in the database, is there HTML being generated but the label value is blank (i.e. <option>{this is blank}</option>)? In django, you can override the __str__ function to specify how the dropdown options get labeled
Override __str__ as follows:
class Category(models.Model):
name = models.CharField(max_length=128)
abbr = models.CharField(max_length=5)
def __unicode__(self):
return self.name
def __str__(self):
return self.name
You can compute the value of selling_price and any other computed value in the block if request.method == 'POST'.
Example:
def uploadphoto(request):
context = RequestContext(request)
context_dict = {}
if request.method == 'POST':
form = ImagesForm(request.POST,request.FILES)
#- Calculate value(s) here -#
if form.is_valid():
image = form.save(commit=False)
image.save()`
Please see this post here for using radio buttons
You would do this in the same place as #2 above