I am Neeraj. i want retrieve data using two dropdown with find button from database that i am created using django model.py
home.html
<form class="flormo">
<div class="row no-gutters">
<div class="form-group col-lg-5 col-md-4">
<select class="form-control" id="vendor_type">
<option value="">Select vendor type</option>
<option value="Photographer">Photographer</option>
<option value="others">others</option>
<option value="Makeup Artist">Makeup Artist</option>
<option value="Marriage Banquet Hall">Marriage Banquet Hall</option>
</select>
</div>
<div class="form-group col-lg-4 col-md-4">
<select class="form-control" id="cityy">
<option value="">Select City</option>
<option value="Andhra Pradesh">Andhra Pradesh</option>
<option value="Delhi">Delhi</option>
</select>
</div>
<div class="form-group col-lg-3 col-md-4">
<button class="fillobtn" type="button" onclick="searchVendor()">
Find Now
</button>
</div>
</div>
</form>
Model.py
# vendor model details
class v_type(models.Model):
name = models.CharField(max_length=100, default=False)
def __str__(self):
return self.name
class v_city(models.Model):
name = models.CharField(max_length=100, default=False)
def __str__(self):
return self.name
class rank_img(models.Model):
image = models.ImageField(upload_to='vendor/rank_img')
name = models.CharField(max_length=100, default=False)
def __str__(self):
return self.name
class vendor_details(models.Model):
V_type = models.ForeignKey(v_type, null=False, on_delete=models.DO_NOTHING)
V_city = models.ForeignKey(v_city, null=False, on_delete=models.DO_NOTHING)
Profile_image = models.ImageField(upload_to='vendor/profile_imgs')
Rank_img = models.ForeignKey(rank_img, null=True, on_delete=models.DO_NOTHING)
Title = models.CharField(max_length=100, null=False)
Short_title = models.CharField(max_length=100, null=True)
User_upto = models.CharField(max_length=100)
Location = models.CharField(max_length=200, null=False)
Latitude = models.IntegerField()
Longitude = models.IntegerField()
Star = models.CharField(max_length=5)
All_Price_list = RichTextField()
First_service_name = models.CharField(max_length=200)
First_service_Price = models.CharField(max_length=200, default='')
Second_service_name = models.CharField(max_length=200)
Second_service_Price = models.CharField(max_length=200, default='')
slug = models.SlugField(default='', max_length=500, null=True, blank=True)
publish_date = models.DateTimeField(auto_now_add=True, editable=False)
def admin_photo(self):
return mark_safe('<img src="{}" width="100" />'.format(self.Profile_image.url))
admin_photo.short_description = 'Image'
admin_photo.allow_tags = True
def __str__(self):
return self.Title
def get_absolute_url(self):
from django.urls import reverse
return reverse("vendor_detail", kwargs={'slug': self.slug})
class Meta:
db_table = "app_vendor_details"
def create_slug(instance, new_slug=None):
slug = slugify(instance.Title)
if new_slug is not None:
slug = new_slug
qs = vendor_details.objects.filter(slug=slug).order_by('-id')
exists = qs.exists()
if exists:
new_slug = "%s-%s" % (slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, vendor_details)
class v_Image(models.Model):
Vendor_details = models.ForeignKey(vendor_details, on_delete=models.CASCADE)
Vendor_Image = models.ImageField(upload_to='vendor/vendor_Image')
def admin_photo(self):
return mark_safe('<img src="{}" width="100" />'.format(self.Vendor_Image.url))
admin_photo.short_description = 'Image'
admin_photo.allow_tags = True
class v_desc(models.Model):
vendor_details = models.ForeignKey(vendor_details, on_delete=models.CASCADE)
V_heading = models.CharField(max_length=100, null=False)
V_descrption = RichTextField()
def __str__(self):
return self.V_heading
Admin.py
from django.contrib import admin
from .models import *
class Product_Images(admin.TabularInline):
model = Product_Image
readonly_fields = ('admin_photo',)
class Product_Admin(admin.ModelAdmin):
inlines = (Product_Images,)
list_display = ('admin_photo','Title','Categories','SKU','Real_Price','Sale_Price','section','featured_image')
list_editable = ('Categories','section')
list_filter = ('Categories','section')
readonly_fields = ('admin_photo',)
list_display_links = ['Title','Sale_Price']
#for vendor
class Vendor_Images(admin.TabularInline):
model = v_Image
readonly_fields = ('admin_photo',)
class Vendor_desc(admin.TabularInline):
model = v_desc
class Vendor_Admin(admin.ModelAdmin):
inlines = (Vendor_Images,Vendor_desc)
list_display = ('admin_photo', 'Title', 'V_type', 'V_city', 'Star', 'slug', 'publish_date')
list_editable = ('Star',)
list_filter = ('V_type', 'V_city')
readonly_fields = ('admin_photo',)
list_display_links = ['Title',]
search_fields = ['Title','V_type']
# Register your models here.
admin.site.register(top_slider)
admin.site.register(Popular_Venue)
admin.site.register(Sub_Banner)
admin.site.register(Popular_Search)
admin.site.register(Top_Categories)
admin.site.register(Main_category)
admin.site.register(Category)
admin.site.register(Sub_Category)
admin.site.register(Product,Product_Admin)
admin.site.register(Product_Image)
admin.site.register(Section)
#admin.site.register(v_desc)
admin.site.register(vendor_details,Vendor_Admin)
admin.site.register(v_Image)
admin.site.register(v_city)
admin.site.register(v_type)
admin.site.register(rank_img)
urls.py
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .import views
urlpatterns = [
path('admin/', admin.site.urls),
path('base/',views.BASE, name='base.html'),
path('404',views.Error404,name='404'),
path('', views.HOME, name='home.html'),
path('product/<slug:slug>',views.PRODUCT_DETAIL,name='product_detail'),
#account
path('my-account', views.MY_ACCOUNT,name='my-account'),
#vendor
path('vendor/<slug:slug>', views.V_DETAILS,name='vendor_detail')
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
views.py
from django.shortcuts import redirect, render
from app.models import top_slider, Popular_Venue, Sub_Banner, Popular_Search, Top_Categories, Product, vendor_details
def BASE(request):
return render(request, 'base.html')
def HOME(request):
top_sliders = top_slider.objects.all().order_by('-id')
Popular_Venues = Popular_Venue.objects.all().order_by('-id')
Sub_Banners = Sub_Banner.objects.all().order_by('-id')
Popular_Searches = Popular_Search.objects.all().order_by('-id')
Top_Category = Top_Categories.objects.all().order_by('-id')
product = Product.objects.filter(section__name="dot")
context = {
'top_sliders': top_sliders,
'Popular_Venues': Popular_Venues,
'Sub_Banners': Sub_Banners,
'Popular_Searches': Popular_Searches,
'Top_Category': Top_Category,
'product': product
}
return render(request, 'Main/home.html', context)
def Error404(request):
return render(request, 'errors/404.html')
def PRODUCT_DETAIL(request,slug):
return render(request, 'product/product_detail.html')
def MY_ACCOUNT(request):
return render(request, 'account/my-account.html')
def V_DETAILS(request,slug):
vendor = vendor_details.objects.filter(slug = slug)
context = {
'vendor':vendor,
}
return render(request, 'v_items/vendor_detail.html',context)
After filter dropdown & click on findnow button redirect on this page { vendor.py}
vendor.py
{% extends 'base.html' %}
{% block content %}
<!-- Bread Crumb STRAT -->
<div class="banner inner-banner1 toper1">
<div class="container">
<section class="banner-detail center-xs">
<h1 class="banner-title">Photographer</h1>
<div class="bread-crumb right-side float-none-xs">
<ul>
<li>Home/</li>
</ul>
</div>
</section>
</div>
</div>
<!-- Bread Crumb END -->
<!-- CONTAIN START ptb-95-->
<section class="ptb-70">
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="filpric">
<div class="price-range mb-30">
<div class="inner-title">Price range</div>
<input class="price-txt" type="text" id="amount">
<div id="slider-range"></div>
</div>
</div>
</div>
<div class="short-by float-right-sm">
<span>Sort By :</span>
<div class="select-item select-dropdown">
<fieldset>
<select name="speed" id="sp" onchange="selPrice('Photographer','Delhi','')">
<option value="">Select Rating</option>
<option value="1">Rating(low>high)</option>
<option value="0">Rating(high > low)</option>
</select>
</fieldset>
</div>
</div>
<div class="col-md-4">
<div class="short-by ">
<span>Vendor :</span>
<div class="select-item select-dropdown">
<fieldset>
<select name="speed" id="sv" onchange="selVendor('Photographer','Delhi','')">
<option value="" selected="selected">Select Vendor</option>
<option value="Photographer">Photographer</option>
<option value="others">others</option>
<option value="Makeup Artist">Makeup Artist</option>
<option value="Marriage Banquet Hall">Marriage Banquet Hall</option>
</select>
</fieldset>
</div>
</div>
</div>
</div>
<hr class="liko">
<!-- vendor list-->
<div class="row">
<div class="col-lg-4 col-md-4">
<div class="vankibox">
<a href="{{i.get_absolute_url}}">
<div class="vanki_img">
<img src="admin.cpanel/prod_image/20220723114525.jpg">
<img class="vatag" src="images/handpicked.png">
</div>
<div class="vankjdes">
<div class="vantitl">
<h4 class="">
seth </h4>
<p>
<i class="fa fa-star"></i> 4 <span>(5 review)</span>
</p>
</div>
<div class="">
<p class="vanadd">
<i class="fa fa-map-marker"></i> <span>New Delhi</span>
</p>
<p class="vanpric">
<span>
<small>ff</small>
<br>
<i class="fa fa-inr"></i>8000 </span>
<span>
<small>ff</small>
<br>
<i class="fa fa-inr"></i>6000 </span>
</p>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
</section>
{% endblock %}
so please help me how i can code this dropdown using my store value with vendor type {v_type} & vendor city {v_city} in Vendor details model.
I have a template containing a form . Whenever i am using the form to submit an image, the image is not being added to my admin table and neither being added to my media folder. What should I do ?
I was expecting that the image would be uploaded to my django admin's table's record and also added to my media folder
but Whenever the image is being submitted along with other fields the other data is being uploaded to admin except image.
This is the section of template containing form
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
<div class="mb-3">
<label for="Name" class="form-label">Name</label>
<input type="text" class="form-control" id="seller_name" name="seller_name">
</div>
<div class="mb-3">
<label for="phone" class="form-label">Phone No.</label>
<input type="text" class="form-control" id="seller_phone" name="seller_phone">
</div>
<div class="mb-3">
<label for="Rawmaterialname" class="form-label">Raw Material Name</label>
<input type="text" class="form-control" id="seller_raw" name="seller_raw">
</div>
<div class="mb-3">
<label for="priceperstd" class="form-label">Price Per Std.</label>
<input type="text" class="form-control" id="seller_price"
placeholder="Your Expected Price Per std." name="seller_price">
</div>
<div class="mb-3">
<label for="textarea" class="form-label">Description</label>
<textarea class="form-control" name="desc" id="desc" cols="30" rows="10"
placeholder="Enter your text here"></textarea>
</div>
<div class="mb-3">
<label for="formFile" class="form-label">Enter Image</label>
<input class="form-control" type="file" id="formFile" name="img">
</div>
<div class="mb-3 form-check">
<input type="checkbox" class="form-check-input" id="seller_agree" checked>
<label class="form-check-label" for="agree">Agree <a data-bs-toggle="modal"
data-bs-target="#terms" class="link-primary">Terms And
Conditions</a></label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
this is the section of my views.py
def index(request):
if request.method=="POST":
# form = Seller_table(request.POST, request.FILES)
name=request.POST.get('seller_name')
phone=request.POST.get('seller_phone')
raw=request.POST.get('seller_raw')
price=request.POST.get('seller_price')
discription=request.POST.get('desc')
image=request.POST.get('img')
Seller=Seller_table(seller_name=name,seller_phone=phone,seller_raw=raw,seller_price=price,desc=discription,img=image)
Seller.save()
messages.success(request,'Successfully Made A Registration')
return render(request,"seller.html")
this is my models.py
from django.db import models
# Create your models here.
class Seller_table(models.Model):
seller_name=models.CharField(max_length=100)
seller_phone=models.CharField(max_length=100)
seller_raw=models.CharField(max_length=50)
seller_price=models.CharField(max_length=10)
desc=models.CharField(max_length=500,default="")
img=models.ImageField( upload_to='images/',default="")
def __str__(self):
return self.seller_raw
this the section of my urls.py of base directory
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('',include("Home.urls")),
path('seller/',include("Seller.urls")),
path('buyer/',include("Buyer.urls")),
]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
this is my settings regarding media
# Base url to serve media files
MEDIA_URL = '/media/'
# Path where media is stored
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
Is something else needed?
plz try with this correction
image=request.FILES.get('img')
--------- OR ----------
image=request.FILES['img']
I have a blog Post model, and one of its attributes is a categorical attribute (store_type). This categorical attribute contains 4 possible values: cafe, coffee house, dessert cafe, and restaurant
I want to create a filter so that I can display the posts according to the type of store associated with that post, and I want the user to be able to use a drop down menu, rather than search by character field input. Here's my model.
I have already made a filter for the title, and it works accordingly.
class Post(models.Model):
store_choices = [
('1', 'cafe'),
('2', 'dessert cafe'),
('3', 'coffee house'),
('4', 'restaurant')
]
title = models.CharField(max_length=100)
review = models.TextField(default='Paragraph 1', max_length=3000)
store_type = models.CharField(choices=store_choices, max_length=100)
In my views.py file, I created a filter class, and I passed the store_type list into context so that I could reference these values in my template.
def PostFilter(request):
qs = Post.objects.all()
store_type = [
('cafe'),
('dessert cafe'),
('coffee house'),
('restaurant')
]
title_query = request.GET.get('title')
store_type_query = request.GET.get('store_type')
if valid_query(title_query):
qs = qs.filter(title__icontains=title_query)
context = {
'queryset': qs,
'store_type': store_type
}
return render(request, 'blog/search.html', context)
Then in my html template, I try to reference these categorical values:
<div class="container py-5">
<form method="GET" action=".">
<!-- Search by title -->
<div class="form-row d-block">
<div class="form-group col">
<label for="title">Store Name</label>
<div class="input-group">
<input class="form-control py-2 border-right-0 border" type="search" name="title" placeholder="Name contains..." />
<span class="input-group-append">
<div class="input-group-text bg-transparent">
<i class="fa fa-search"></i>
</div>
</span>
</div>
</div>
<!-- Search by store type-->
<div class="row">
<div class="form-group col-6">
<div class="container mt-4 mb-4">
<label for="storetype">Store Type</label>
<select class="form-control" name="store_type">
<option selected>Choose...</option>
{% for store in store_type %}
<option value="{{ store }}"> {{ store }} </option>
{% endfor %}
</select>
</div>
Again, my filtering method seems to work fine when it comes to filtering by character field input, but I can't seem to get a working filter that uses a drop down menu (option select) method.
I can not understand why, but the records in the database are not updated ... All data reaches, even after the save () method if you dump the object, then the data from the form is stored correctly, and in the database itself there is no change, besides it is not the first method updating the data, making stores with the same method and everything worked, even in this project the category editing method works. Here's the actual method:
public function UpdateCountry(Request $request)
{
$Countries = Countries::where('Id', $request->get('Id'))->first();
$Countries->Country = $request->get('Country');
$Countries->Continent = $request->get('Continent');
$Countries->Class = $request->get('Class');
$Countries->save();
return back()->with('status', 'Updated success!');
}
Model fillable:
protected $fillable = ['Id', 'Country', 'Class', 'Continent'];
Routes, which use this method:
Route::get('country/editor/edit/{Id}','AdminController#EditCountry')->name('EditCountry');
Route::post('country/editor/save','AdminController#UpdateCountry')->name('UpdateCountry');
A similar method for editing categories that works.
public function UpdateCat(Request $request) {
$data = $request->all();
$Category = Categories::find($data['id']);
$Category->Category = $data['Category'];
$Category->save();
return back()->with('status', 'Updated success');
}
View:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card card-default">
<div class="card-header">Dashboard</div>
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
<div class="container">
<form action="{{route('UpdateCountry')}}" method="post">
#foreach($Country as $item)
<div class="form-group">
<label for="Country">Country</label>
<input type="hidden" value="{!! $item->Id !!}" name="Id" id="Id">
<input type="text" class="form-control" id="Country" name="Country" value="{{$item->Country}}" required>
</div>
<div class="form-group">
<label for="Continent">Continent</label>
<input type="text" class="form-control" id="Continent" name="Continent" value="{{$item->Continent}}" required>
</div>
#endforeach
<input type="hidden" id="Class" name="Class" value="flag flag-default">
<button type="submit" class="btn btn-success">Save</button>
{{csrf_field()}}
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
Well, I solved this question, and it turned out to be very simple. In the model it was necessary simply to indicate:
protected $primaryKey = ['Id'];
Am using the new implementation of uploading files which is the IFormFile. I created a view model and mapped it on a model, however, I am getting a null value on the ImageFile property of the view model. In inserting the record, I am using AngularJS to prevent it from reloading. Below is my views and controller.
public string CreateNewProduct([FromBody] ProductViewModel _product)
{
var imgFile = _product.ImageFile;
var fileName = ContentDispositionHeaderValue.Parse(imgFile.ContentDisposition).FileName.Trim('"');
var targetDirectory = Path.Combine(environment.WebRootPath, string.Format("Common\\Images\\"));
var savePath = Path.Combine(targetDirectory, fileName);
imgFile.CopyTo(new FileStream(savePath, FileMode.Create));
Products product = new Products
{
ItemCode = _product.ItemCode,
FileName = fileName,
FilePath = savePath
};
context.Products.Add(product);
context.SaveChanges();
return "";
}
And here is my view in a dialog box.
<div class="modal" role="dialog" id="addItemDialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="text-info">Add New Item</h3>
</div>
<div class="modal-body">
<form id="newproductform" class="form-horizontal" role="form" enctype="multipart/form-data">
<div class="form-group">
<span class="col-sm-3 control-label">Item Code</span>
<div class="col-sm-6">
<input type="text" class="form-control input-sm" ng-model="ItemCode" />
</div>
</div>
<div class="form-group">
<span class="col-sm-3 control-label">Image</span>
<input type="file" name="file" accept="image/*" onchange="angular.element(this).scope().selectFileforUpload(this.files)" required />
<span class="error" ng-show="(f1.file.$dirty || IsFormSubmitted) && f1.file.$error.required">Image required!</span>
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" ng-click="InsertProduct()">Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
I just used the submit button but still I get null value on ImageFile property on the view model.
Here is my view model.
public class ProductViewModel
{
public string ItemCode { get; set; }
//[FileExtensions(Extensions = "jpg/jpeg")]
public IFormFile ImageFile { get; set; }
}