I'm trying to learn in Django. I'm trying to prepare the inventory application. But I do not calculate the input and output products.
I prepare models & views.
Models:
class Kategori(models.Model):
adi = models.CharField(max_length=10, verbose_name="Kategori")
def __str__(self):
return self.adi
class Birim(models.Model):
birim = models.CharField(max_length=2, verbose_name="Birim")
def __str__(self):
return self.birim
class Urunler(models.Model):
adi = models.CharField(max_length=50, verbose_name="Ürün Adı")
kod = models.PositiveSmallIntegerField(verbose_name="Ürün Kodu", blank=True, null=True)
etkenMadde = models.CharField(max_length=100, verbose_name="İçerik Etken Madde", blank=True, null=True)
tarih = models.DateField(default=datetime.now(), editable=False)
birim = models.ForeignKey(Birim, verbose_name="Birim")
kategori = models.ForeignKey(Kategori, verbose_name="Kategori")
aciklama = models.CharField(max_length=50, verbose_name="Açıklama", blank=True, null=True)
def __str__(self):
return self.adi
class StokCikis(models.Model):
urun = models.ForeignKey(Urunler, related_name="scikis_urun", verbose_name="Ürün")
tarih = models.DateTimeField(default=datetime.now())
miktar = models.PositiveSmallIntegerField(verbose_name="Miktar", default=0)
teslimAlan = models.CharField(max_length=20, verbose_name="Teslim Alan")
tesimEden = models.CharField(max_length=20, verbose_name="Teslim Eden")
def __str__(self):
return self.urun.adi
class StokGiris(models.Model):
urun = models.ForeignKey(Urunler, related_name="sgiris_urun", verbose_name="Ürün")
tedarikci = models.CharField(max_length=100, verbose_name="Tedarikçi", blank=True, null=True)
irsaliyeNo = models.PositiveSmallIntegerField(verbose_name="İrsaliye No", blank=True, null=True)
tarih = models.DateField(default=datetime.now().strftime("%d.%m.%Y"))
miktar = models.PositiveSmallIntegerField(verbose_name="Miktar", default=0)
aciklama = models.CharField(max_length=100, verbose_name="Açıklama", blank=True, null=True)
def __str__(self):
return self.urun.adi
Views.py
def kategori(request):
kategori = Kategori.objects.all()
return render_to_response('stok_kategoriler.html', locals())
def kategoriEkle(request):
kategoriId = request.GET.get('id')
if kategoriId:
ktgr = Kategori.objects.get(pk=kategoriId)
form = KategoriForm(instance=ktgr)
else:
form = KategoriForm
if request.method == 'POST':
if kategoriId:
form = KategoriForm(request.POST, instance=ktgr)
else:
form = KategoriForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/stok/kategoriler')
button = "Ekle"
baslik = "Kategoriler"
return render(request, 'stok_kategori_ekle.html', locals())
def kategoriSil(request):
kategoriId = request.GET.get('id')
kategori = Kategori.objects.get(pk=kategoriId)
kategori.delete()
return HttpResponseRedirect('/stok/kategoriler')
def stokBirimler(request):
birimler = Birim.objects.all()
return render_to_response('stok_birimler.html',locals())
def stokBirimEkle(request):
birimId = request.GET.get('id')
if birimId:
stok_birim = Birim.objects.get(pk=birimId)
form = BirimForm(instance=stok_birim)
else:
form = BirimForm()
if request.method == 'POST':
if birimId:
form = BirimForm(request.POST, instance=stok_birim)
else:
form = BirimForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/stok/birimler/')
baslik = "Stok Birimleri"
return render(request, 'stok_birim_ekle.html', locals())
def stokBirimSil(request):
birimId = request.GET.get('id')
birim = Birim.objects.get(pk=birimId)
birim.delete()
return HttpResponseRedirect('/stok/birimler/')
def stokUrunler(request):
urunler = Urunler.objects.all()
return render_to_response('stok_urunler.html', locals())
def urunEkle(request):
urunId = request.GET.get('id')
if urunId:
stok_urun = Urunler.objects.get(pk=urunId)
form = UrunForm(instance=stok_urun)
else:
form = UrunForm()
if request.method == 'POST':
if urunId:
form = UrunForm(request.POST, instance=stok_urun)
else:
form = UrunForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/stok/urunler/')
baslik = "Stok Ürünleri"
return render(request, 'stok_urun_ekle.html', locals())
def urunSil(request):
urunId = request.GET.get('id')
urun = Urunler.objects.get(pk=urunId)
urun.delete()
return HttpResponseRedirect('/stok/urunler/')
Located in the model StokGiris.miktari and Stok.Cikis.miktari fields need calculation. Total = StokGiris.miktari - StokCikis.miktari and I want to list the records.
If I understand your question correctly, you want to aggregate the values of miktar of both models and subtract them from each other. You can do it with Django built-in aggregation:
from django.db.models import Sum
total = StokGiris.objects.all().aggregate(Sum('miktar')) - StokCikis.objects.all().aggregate(Sum('miktar'))
As for listing the records... Not really sure what you mean again, but some ways to "list the records":
# Just a list of DB items
list_of_stokgiris = list(StokGiris.objects.all())
# Serialized list of dictionaries with the DB values
list_of_stokcikis = StokCikis.objects.values() # You can add an argument to specify which fields you want to be serialized
# Serialized list of tuples with DB values
# I.e. [('Filipp',), ('Artjom',), ('Marat',)]
list_of_urunler = Urunler.objects.values_list('adi') # Same here for the argument. Multiple args are also supported.
Related
Flight funtion doesn't return from models in view. I changed models from null=True to nothing. Is the problem within my return code or is it something else? The thing is nothing gives an error other than views which is weird.
def add_flight(request):
if request.method == 'POST':
form = FlightForm(request.POST)
if form.is_valid():
a = Flight(departing_date=form.cleaned_data["departing_date"],
deptAirport=form.cleaned_data["deptAirport"],
arrAirport=form.cleaned_data["arrAirport"],
duration=form.cleaned_data["departing_date"],
airline=form.cleaned_data["airline"],
price=form.cleaned_data["price"],
deptCity=form.cleaned_data["deptCity"],
arrCity=form.cleaned_data["arrCity"],
deptHour=form.cleaned_data["deptHour"], ,
arrHour=form.cleaned_data["arrHour"])
a.save()
#return HttpResponse("Success!")
return HttpResponseRedirect('/flights/')
else:
form = FlightForm()
return render(request, 'add_flight.html', {'form': form})
It can't return Flight model from models which looks like this
class Flight(models.Model):
departing_date = models.CharField(max_length=10)
deptAirport = models.CharField(max_length=100)
arrAirport = models.CharField(max_length=100)
duration = models.CharField(max_length=5)
airline = models.CharField(max_length=20)
price = models.CharField(max_length=100)
deptCity = models.CharField(max_length=100)
arrCity = models.CharField(max_length=100)
deptHour = models.CharField(max_length=4)
arrHour = models.CharField(max_length=4)
def __str__(self):
return self.departing_date+" "+self.deptAirport+" "+self.arrAirport+" "+self.duration+" "\
+self.airline+" "+self.price+" "+self.deptCity+" "+self.arrCity+" "+self.deptHour+" "+self.arrHour
Any suggestions?
Model.py
class UserAccountModel(models.Model):
ContactEmail = models.EmailField(max_length=30)
FirstName = models.CharField(max_length=30)
LastName = models.CharField(max_length=40)
Counrty = models.CharField(max_length=50)
Phone = models.IntegerField()
ChooseUserName = models.CharField(max_length=30)
password = models.CharField(max_length=32)
EnterCaptcha = models.CharField(max_length=4)
payments = models.BooleanField(max_length=6, default=False)
showsponsor = models.CharField(max_length=30, default=False)
RegisteredDate = models.DateTimeField(auto_now_add=True, blank=True)
ActivationOn = models.DateField(auto_now_add=False,blank=True)
expiry_date = models.DateField(auto_now_add=False,blank=True)
def save(self, **kwargs):
super(AddProgramModel, self).save(**kwargs)
vote = UserAccountModel(AddProgramModel=self)
vote.save()
def __str__(self):
return self.FirstName + ":" + self.ChooseUserName
views.py
this one is views of my project and bellow with bold text is a actual error location from django debugger while saving a record ,help me to resolve it
def join(request):
if request.method == 'POST':
refrer = request.POST['showsponsor']
try:
if UserAccountModel.objects.get(ChooseUserName=str(refrer)):
ContactEmail=request.POST['email']
FirstName=request.POST['firstname']
LastName=request.POST['lastname']
Counrty=request.POST['country1']
Phone=request.POST['phone']
ChooseUserName=request.POST['username']
password=request.POST['password2']
EnterCaptcha=request.POST['captcha']
payments=request.POST['payment']
# referal_Name = request.POST['showsponsor']
Note: error start from here join_save_record to join_save_record.save()
join_save_record = UserAccountModel.objects.create(ContactEmail=ContactEmail,FirstName=FirstName,
LastName=LastName,Counrty=Counrty,Phone=Phone,
ChooseUserName=ChooseUserName,password=password,
EnterCaptcha=EnterCaptcha, payments='True',
ActivationOn=datetime.now,expiry_date=datetime.now,)
join_save_record.save()
print(join_save_record.FirstName)
namew=request.POST['showsponsor']
# session creating
request.session['ChooseUserName'] = str(refrer)
rerredby = request.session.get("ChooseUserName")
print("session created : " + str(rerredby))
return render(request, 'payment_verify.html', {'rerredby':rerredby})
# messages.info(request, 'invalid refrer user except case name contact to the right persone who did')
print("denied")
except UserAccountModel.DoesNotExist :
return redirect("/join")
else :
return render(request, 'join.html')
I am building ecommerce and having trouble creating dashboard for sellers. No matter how I try to get filter processed orders so I can show sold products to sellers I couldn't make it happen. Some help will be a great relief. Following is my Seller Mixin I am trying to create:
mixins.py
class SellerAccountMixin(LoginRequiredMixin, object):
account = None
products = []
transactions = []
orders = []
def get_account(self):
user = self.request.user
accounts = SellerAccount.objects.filter(user=user)
if accounts.exists() and accounts.count() == 1:
self.account = accounts.first()
return accounts.first()
return None
def get_products(self):
account = self.get_account()
products = Product.objects.filter(seller=account)
self.products = products
return products
def get_all_products(self):
account = self.get_account()
products = Product.objects.all()
self.products = products
return products
def get_sold_products(self):
orders = UserCheckout.objects.get(user_user=self.user)
return orders
seller/views.py:
class SellerDashboard(SellerAccountMixin, FormMixin, View):
form_class = NewSellerForm
success_url = "/seller/"
def post(self, request, *args, **kwargs):
user = self.user
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def get(self, request, *args, **kwargs):
apply_form = self.get_form() #NewSellerForm()
account = self.get_account()
exists = account
active = None
context = {}
if exists:
active = account.active
if not exists and not active:
context["title"] = "Apply for Account"
context["apply_form"] = apply_form
elif exists and not active:
context["title"] = "Account Pending"
elif exists and active:
context["title"] = "Dashboard"
#products = Product.objects.filter(seller=account)
context["products"] = self.get_products()
context["today_sales"] = self.get_today_sales()
context["sold_products"] = self.get_sold_products()
#context["total_profit"] = self.get_total_profit()
else:
pass
return render(request, "sellers/dashboard.html", context)
Above is my seller app and I am bringing the products model with simple features. The problem is that its not letting me get processed orders with UserCheckout model in Orders app. Following is a snapshot of Orders app.
Orders/models.
class UserCheckout(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True)
email = models.EmailField(unique=True)
def __unicode__(self):
return self.email
ADDRESS_TYPE = (
('billing', 'Billing'),
('shipping', 'Shipping'),
)
class UserAddress(models.Model):
user = models.ForeignKey(UserCheckout)
type = models.CharField(max_length=120, choices=ADDRESS_TYPE)
street = models.CharField(max_length=120)
city = models.CharField(max_length=120)
state = models.CharField(max_length=120)
zipcode = models.CharField(max_length=120)
def __unicode__(self):
return self.street
def get_address(self):
return "%s, %s, %s, %s" %(self.street, self.city, self.state, self.zipcode)
CHOICES = (
('CreditCard', "CreditCard"),
('Cash On Delivery', 'Cash On Delivery'),
('PayPal', 'PayPal'),
)
ORDER_STATUS_CHOICES={
('created','Created'),
('paid','Paid'),
}
class Order(models.Model):
status = models.CharField(max_length=120, choices=ORDER_STATUS_CHOICES, default='created')
cart = models.ForeignKey(Cart)
user = models.ForeignKey(UserCheckout, null=True)
billing_address = models.ForeignKey(UserAddress, related_name='billing_address', null=True)
shipping_address = models.ForeignKey(UserAddress, related_name='shipping_address', null=True)
shipping_total_price = models.DecimalField(max_digits=50, decimal_places=2, default=5.99)
user_seller = models.ForeignKey(settings.AUTH_USER_MODEL)
order_total = models.DecimalField(max_digits=50, decimal_places=2, )
order_id = models.CharField(max_length=20, null=True, blank=True)
paymethod = models.CharField(max_length=120, choices=CHOICES, default='CreditCard')
seller = models.ForeignKey(SellerAccount, null=True)
def __unicode__(self):
return str(self.cart.id)
I can get multiple products but I need to filter products by seller and orders by seller. After trying multiple times I always get stuck with error:
user has to be a UserCheckout instance:
User "Admin": Must be a "User" instance.
and
'SellerDashboard' object has no attribute 'user'
I need to filter products by seller.
I need filter orders with paid status by the seller.
Seller Account Model:
class SellerAccount(models.Model):
user = models.ForeignKey(User)
managers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="manager_sellers", blank=True)
#orders = models.ManyToManyField(Order)
active = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
def __unicode__(self):
return str(self.user.username)
def get_absolute_url(self):
return reverse("products:vendor_detail", kwargs={"vendor_name": self.user.username})
I am stuck so bad that I don't have courage to continue with django anymore. Please help.
While I hit the search button..it shows the
Page not found (404)
No Category matches the given query.
My views
def search_in_category(request, slug):
# reset the search params, if present
try:
del request.session['search']
except KeyError:
pass
return search_results(request, slug)
def search_results(request, slug):
category = get_object_or_404(Category, slug=slug)
fields = list(category.field_set.all())
fields += list(Field.objects.filter(category=None))
fieldsLeft = [field.name for field in fields]
if request.method == "POST" or 'search' in request.session:
ads = category.ad_set.filter(active=True,
expires_on__gt=datetime.datetime.now())
# A request dictionary with keys defined for all
# fields in the category.
post = {}
if 'search' in request.session:
post.update(request.session['search'])
else:
post.update(request.POST)
sforms = prepare_sforms(fields, fieldsLeft, post)
isValid = True
for f in sforms:
# TODO: this assumes the form is not required
# (it's a search form after all)
if not f.is_valid() and not f.is_empty():
isValid = False
if isValid:
if request.method == 'POST':
request.session['search'] = {}
request.session['search'].update(request.POST)
return redirect('classifieds_browse_search_results', slug=slug)
for f in sforms:
ads = f.filter(ads)
if ads.count() == 0:
return render_to_response('classifieds/list.html',
{'no_results': True,
'category': category},
context_instance=RequestContext(request))
else:
context = context_sortable(request, ads)
context['category'] = category
return render_to_response('classifieds/list.html', context,
context_instance=RequestContext(request))
else:
sforms = prepare_sforms(fields, fieldsLeft)
return render_to_response('classifieds/search.html',
{'forms': sforms, 'category': category},
context_instance=RequestContext(request))
My models.py
class Category(models.Model):
site = models.ForeignKey(Site)
template_prefix = models.CharField(max_length=200, blank=True)
name = models.CharField(max_length=200)
slug = models.SlugField()
enable_contact_form_upload = models.BooleanField(default=False)
contact_form_upload_max_size = models.IntegerField(default=2 ** 20)
contact_form_upload_file_extensions = models.CharField(max_length=200,
default="txt,doc,odf,pdf")
images_max_count = models.IntegerField(default=0)
images_max_width = models.IntegerField(help_text=_(u'Maximum width in pixels.'),
default=1024)
images_max_height = models.IntegerField(help_text=_(u'Maximum height in pixels.'),
default=1024)
images_max_size = models.IntegerField(help_text=_(u'Maximum size in bytes.'),
default=2 ** 20)
images_allowed_formats = models.ManyToManyField(ImageFormat, blank=True)
description = models.TextField(default='')
sortby_fields = models.CharField(max_length=200,
help_text=_(u'A comma separated list of field names that should show up as sorting options.'),
blank=True)
sort_order = models.PositiveIntegerField(default=0)
def __unicode__(self):
return self.name + u' Category'
class Meta:
verbose_name_plural = u'categories'
My url
url(r'^search/(?P<slug>[-\w]+)/$', 'browse.search_in_category',
name='classifieds_browse_category_search'),
url(r'^search/results/(?P<slug>[-\w]+)/$', 'browse.search_results',
name='classifieds_browse_search_results'),
This my code, Why I am getting the 404 error? What I have to do for fix this error?
you cannot do
return search_results(request, slug)
do rather this redirect
return redirect(reverse('classifieds_browse_search_results', kwargs={'slug':slug}))
dont forget to import
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
I have the following models -
class Jobdtl(models.Model):
jobdtl_id = models.IntegerField(primary_key=True)
jobdtl_cmd = models.TextField(blank=True)
jobdtl_envfile = models.TextField(blank=True)
jobdtl_retnsn = models.SmallIntegerField(blank=True, null=True)
jobdtl_allowadhoc = models.CharField(max_length=1, blank=True)
jobdtl_waitop = models.CharField(max_length=1, blank=True)
class Meta:
managed = False
db_table = 'jobdtl'
class Jobmst(models.Model):
jobmst_id = models.IntegerField(primary_key=True)
jobmst_prntid = models.IntegerField(blank=True, null=True)
jobmst_active = models.CharField(max_length=1, blank=True)
jobmst_evntoffset = models.SmallIntegerField(blank=True, null=True)
jobmst_name = models.TextField(blank=True)
jobmst_owner = models.IntegerField(blank=True, null=True)
jobmst_crttm = models.DateTimeField()
jobdtl_id = models.ForeignKey('Jobdtl', db_column='jobdtl_id', related_name='mstdtl', blank=True, null=True)
jobmst_lstchgtm = models.DateTimeField(blank=True, null=True)
def __unicode__(self):
return self.jobmst_name
class Meta:
managed = False
db_table = 'jobmst'
I'm trying to generate a json similar to what we have here -
http://stackoverflow.com/questions/19709101/django-rest-framework-multiple-models
using the steps here -
http://stackoverflow.com/questions/16793608/how-to-write-a-django-rest-framework-serializer-field-to-merge-data-from-gener
These are my serializers -
class JobmstSerializer(serializers.ModelSerializer):
class Meta:
model = Jobmst
class JobdtlSerializer(serializers.ModelSerializer):
jobmst_id = JobmstSerializer(many=True)
class Meta:
model = Jobdtl
And this is my view
class ResultsList(ListAPIView):
def list(self, request, *args, **kwargs):
jobmstquery = Jobmst.objects.using('Admiral').all()
jobdtlquery = Jobdtl.objects.using('Admiral').all()
results = list()
entries = list(chain(jobmstquery, jobdtlquery)) # combine the two querysets
for entry in entries:
type = entry.__class__.__name__.lower() # 'jobmst', 'jobdtl'
if isinstance(entry, Jobmst):
serializer = JobmstSerializer(entry)
dictionary = {'type': jobmst, 'jobmst_id': jobmst_id, 'jobmst_type': jobmst_type, 'jobmst_prntid': jobmst_prntid, 'jobmst_active': jobmst_active, 'evntmst_id': evntmst_id, 'jobmst_evntoffset': jobmst_evntoffset, 'jobmst_name': jobmst_name, 'jobmst_mode': jobmst_mode, 'jobmst_owner': jobmst_owner, 'jobmst_desc': jobmst_desc, 'jobmst_crttm': jobmst_crttm, 'jobdtl_id': jobdtl_id, 'jobmst_lstchgtm': jobmst_lstchgtm}
if isinstance(entry, Jobdtl):
serializer = JobdtlSerializer(entry)
dictionary = {'type': jobdtl, 'jobdtl_id': jobdtl, 'jobdtl_cmd': jobdtl_cmd, 'jobdtl_envfile': jobdtl_envfile, 'jobdtl_retnsn': jobdtl_retnsn, 'jobdtl_allowadhoc': jobdtl_allowadhoc, 'jobdtl_waitop': jobdtl_waitop}
results.append(dictionary)
return Response(results)
I tie it through my URL -
urlpatterns = patterns('TidalDEV.views',
url(r'^TidalDEV/$', 'ResultsList'),
url(r'^TidalDEV/(?P<pk>[0-9]+)/$', 'ResultsList'),
)
But when I hit my URL at http://localhost/TidalDEV/ or http://localhost/TidalDEV/50244/
I get slammed with an error -
Exception Type: TypeError
Exception Value:
__init__() takes 1 positional argument but 2 were given
Exception Location: D:\Python33\lib\site-packages\django\core\handlers\base.py in get_response, line 114
I ended up doing the following and it worked -
class JobdtlSerializer(serializers.ModelSerializer):
class Meta:
model = Jobdtl
class JobmstSerializer(serializers.ModelSerializer):
jobdtl_id = JobdtlSerializer()
class Meta:
model = Jobmst
then connected with the variation of the default views -
#csrf_exempt
def jobmst_list(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
DEV = Jobmst.objects.using('AdmiralDEV').all()
serializer = JobmstSerializer(DEV, many=True)
return XMLResponse(serializer.data)
elif request.method == 'POST':
data = XMLParser().parse(request)
serializer = JobmstSerializer(data=data)
if serializer.is_valid():
serializer.save()
return XMLResponse(serializer.data, status=201)
else:
return XMLResponse(serializer.errors, status=400)
#csrf_exempt
def jobmst_detail(request, pk):
"""
Retrieve, update or delete a code snippet.
"""
try:
DEV = Jobmst.objects.using('AdmiralDEV').get(jobmst_id=pk)
except Jobmst.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = JobmstSerializer(DEV)
return XMLResponse(serializer.data)
elif request.method == 'PUT':
data = XMLParser().parse(request)
serializer = JobmstSerializer(DEV, data=data)
if serializer.is_valid():
serializer.save()
return XMLResponse(serializer.data)
else:
return XMLResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
DEV.delete()
return HttpResponse(status=204)
That allowed me to get from the 2 separate models. It's unformatted and ugly but proves it can be done. Need to figure out how to link more than these 2 models now (I have 5 minimum).