how to integrate and generate invoices with django? - python

i am new in django , i would like to integrate an invoice functionality in my pharmacy app , but i have difficulties with table relations and i also lack some inspiration , i would also like to add the elements of my database how the product, the price ... in the invoice but I don't know how to do if you can not only help me solve this but you can also give me ideas for a pharmacy application.
thank you in advance!
I don't have an idea, I lack an idea to generate invoices for my models file and there
from django.db import models
class Client(models.Model):
name = models.CharField(max_length = 30)
date = models.DateTimeField(auto_now_add=True)
class Stock (models.Model):
balance = models.IntegerField(null=True)
date = models.DateTimeField(auto_now_add=True )
class Produit(models.Model):
name = models.CharField(max_length=100 , verbose_name= 'Nom')
quantite = models.IntegerField(null=True , verbose_name= 'Quantité')
price = models.IntegerField(null=True , verbose_name = 'Prix')
expiration = models.DateField(null=True , verbose_name= 'Expiration')
stock = models.ForeignKey(Stock , blank=True, null=True , on_delete= models.SET_NULL, verbose_name= 'Stock')
date = models.DateTimeField(auto_now_add=True ,verbose_name= 'Date')
description = models.CharField( blank= True , null= True, max_length=500 )
class Vente(models.Model):
name = models.CharField(max_length=30)
quantite = models.IntegerField(null=True)
price = models.IntegerField(null=True)
total = models.IntegerField(null=True)
produit = models.ForeignKey(Produit, on_delete=models.CASCADE )
date = models.DateTimeField(auto_now_add=True )
class Facture(models.Model):
vente = models.ForeignKey(Vente, on_delete= models.CASCADE)
client = models.ForeignKey( Client , on_delete= models.CASCADE )
prix = models.IntegerField(null=True)
produit = models.ManyToManyField(Produit)
date = models.DateTimeField(auto_now_add=True)
class Paiement(models.Model):
facture = models.ForeignKey(Facture, on_delete= models.CASCADE)
client = models.ForeignKey(Client, on_delete= models.CASCADE)
prix = models.IntegerField(null=True)
date = models.DateTimeField(auto_now_add=True)
class Daicaissement(models.Model):
user = models.CharField(max_length= 30)
montant = models.IntegerField(null=True)
date = models.DateTimeField(auto_now_add=True)
class provisionnement(models.Model):
produit = models.ForeignKey(Produit, on_delete= models.CASCADE)
quantite = models.IntegerField(null=True)
date = models.DateTimeField(auto_now_add=True)
class Conseil(models.Model):
produit = models.ForeignKey(Produit, on_delete= models.CASCADE)
notice = models.TextField(blank=True , null= True)
date = models.DateTimeField(auto_now_add=True )
def __str__(self):
return f'{self.name , id}'

Related

NFT payment gateway django

How to accept NFTs on django site? Right now there are two models:
class Product(models.Model):
''' Product represents what a user can purchase to fund their wallet'''
TYPE_CHOICES = ((-1, "NONE"),(0,"BTC"),(1,'NFT'), (2, "FIAT"), (3, "DUMB"))
type = models.IntegerChoices(choices = TYPE_CHOICES, default = -1, blank = False)
price = models.FloatField(default = 0.00, null=False, blank=False)
title = models.CharField(max_length=50)
# TODO qr_code = models.ImageField(upload_to='qr_codes', blank=True)
description = models.TextField()
# active = models.BooleanField Whether a product is active or not
objects = ProductManager()
class Invoice(models.Model):
''' The invoice represents a transaction when a user purchases a product'''
STATUS_CHOICES = ((-1,"Not Started"),(0,'Unconfirmed'), (1,"Partially Confirmed"), (2,"Confirmed"), (3, "Wallet Credited"))
user = models.ForeignKey(User, on_delete = models.CASCADE)
product = models.ForeignKey("Product", on_delete=models.CASCADE)
status = models.IntegerField(choices=STATUS_CHOICES, default=-1)
order_id = models.CharField(max_length=250)
address = models.CharField(max_length=250, blank=True, null=True)
btcvalue = models.IntegerField(blank=True, null=True)
received = models.IntegerField(blank=True, null=True)
txid = models.CharField(max_length=250, blank=True, null=True)
rbf = models.IntegerField(blank=True, null=True)
created_at = models.DateField(auto_now=True)
objects = InvoiceManager()
We want to accept NFTs as one sort of product such that users are able to send us NFTs and the backend credits their accounts with those NFTs. Is there a good package/service that does this?

Django ManyToMany field object automatically pre-fills

I have an PaypalOrder model that is created when someone orders from a website, and it has a ManyToManyField that connects it to multiple OrderItems. Whenever I create a PaypalOrder, it automatically lists every OrderItem that exists in the django admin panel. How do I only list the objects that I set it to connect to?
my models.py:
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.IntegerField()
is_a_subscription = models.BooleanField(default=False)
subscription = models.ForeignKey('Subscription', on_delete=models.CASCADE, null=True, blank=True)
class PaypalOrder(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
items_and_quantities = models.ManyToManyField(OrderItem, blank=True, related_name="paypalorder")
full_name = models.CharField(max_length=100)
address1 = models.CharField(max_length=250)
address2 = models.CharField(max_length=250, null=True, blank=True)
city = models.CharField(max_length=100)
zipcode = models.CharField(max_length=20)
created_at = models.DateTimeField(auto_now_add=True)
total_paid = models.DecimalField(max_digits=10, decimal_places=2)
order_id = models.CharField(max_length=100, null=True, blank=True)
subscription_id = models.CharField(max_length=100, null=True, blank=True)
email=models.CharField(max_length=100, null=True)
country_code = models.CharField(max_length=100)
state = models.CharField(max_length=50, null=True)
my view:
order = PaypalOrder.objects.create(
user = user,
full_name= resp['subscriber']['name']['given_name'] + " " + resp['subscriber']['name']['surname'],
email = resp['subscriber']['email_address'],
city = resp['subscriber']['shipping_address']['address']['admin_area_2'],
state = resp['subscriber']['shipping_address']['address']['admin_area_1'],
address1 = resp['subscriber']['shipping_address']['address']['address_line_1'],
address2 = addr2,
zipcode = resp['subscriber']['shipping_address']['address']['postal_code'],
country_code = resp['subscriber']['shipping_address']['address']['country_code'],
total_paid = resp['billing_info']['last_payment']['amount']['value'],
order_id = "product_ID: " + resp['id'],
subscription_id = resp['plan_id'],
created_at = resp['create_time'],
)
order.save()
subscription = Subscription.objects.create(user = request.user, paypal_order = order)
order.items_and_quantities.set(OrderItem.objects.filter(pk=100))
I believe that you are being tricked by the Front end; look again; even when the Django admin displays all the items, only those related to PayPal orders are highlighted.

How can I split orders by attributes in my API

I have a method that creates orders from the user's cart. For the courier to take an order from different restaurants, the order is divided into several. But at the moment I'm splitting the order just by the dish in the cart. How to make an order split by restaurants? that is, if a user orders 5 dishes from two different restaurants, then 2 orders were formed.
views.py
#action(methods=['PUT'], detail=False, url_path='current_customer_cart/add_to_order')
def add_cart_to_order(self, *args, **kwargs):
cart = Cart.objects.get(owner=self.request.user.customer)
cart_meals = CartMeal.objects.filter(cart=cart)
data = self.request.data
for cart_meal in cart_meals:
order = Order.objects.create(customer=self.request.user.customer,
cart_meal=cart_meal,
first_name=data['first_name'],
last_name=data['last_name'],
phone=data['phone'],
address=data.get('address', self.request.user.customer.home_address),
restaurant_address=cart_meal.meal.restaurant.address,
)
order.save()
return response.Response({"detail": "Order is created", "added": True})
models.py
class Order(models.Model):
"""User's order"""
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='related_orders')
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
phone = models.CharField(max_length=20)
cart_meal = models.ForeignKey(CartMeal, on_delete=models.CASCADE, null=True, blank=True)
restaurant_address = models.CharField(max_length=1024, null=True)
address = models.CharField(max_length=1024)
status = models.CharField(max_length=100, choices=STATUS_CHOICES, default=STATUS_NEW)
created_at = models.DateTimeField(auto_now=True)
delivered_at = models.DateTimeField(null=True, blank=True)
courier = models.OneToOneField('Courier', on_delete=models.SET_NULL, null=True, blank=True)
class CartMeal(models.Model):
"""Cart Meal"""
user = models.ForeignKey('Customer', on_delete=models.CASCADE)
cart = models.ForeignKey('Cart', verbose_name='Cart', on_delete=models.CASCADE, related_name='related_meals')
meal = models.ForeignKey(Meal, verbose_name='Meal', on_delete=models.CASCADE)
qty = models.IntegerField(default=1)
final_price = models.DecimalField(max_digits=9, decimal_places=2)
class Meal(models.Model):
"""Meal"""
title = models.CharField(max_length=255)
description = models.TextField(default='The description will be later')
price = models.DecimalField(max_digits=9, decimal_places=2)
discount = models.IntegerField(default=0)
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True)
slug = models.SlugField(unique=True)
class Restaurant(models.Model):
"""Restaurant"""
name = models.CharField(max_length=255)
slug = models.SlugField(unique=True)
address = models.CharField(max_length=1024)
owner = models.ForeignKey('Restaurateur', on_delete=models.CASCADE, null=True)
meals = models.ManyToManyField('Meal', related_name='related_restaurant', blank=True)
How can I do this, please help me
You can group your meals with respect to resturants.
import itertools
from core.models import CartMeal, Order
for restaurant, cart_meals in itertools.groupby(CartMeal.objects.order_by('meal__restaurant'), lambda s: s.meal.restaurant):
order = Order.objects.create(
customer=self.request.user.customer,
first_name=data['first_name'],
last_name=data['last_name'],
phone=data['phone'],
address=data.get('address', self.request.user.customer.home_address),
restaurant_address=cart_meal.meal.restaurant.address,
)
order.cart_meal.set([cart_meal for cart_meal in cart_meals])
Ref: The answer is formulated by taking help from following answer.
https://stackoverflow.com/a/57897654/14005534

How can I create a model property based on specific model fields?

Let's say I have the following model:
class DriverReview(models.Model):
driver = models.ForeignKey(Driver, on_delete=models.CASCADE,)
driving_score = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(5)])
communication_score = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(5)])
professionalism_score = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(5)])
review_text = models.TextField()
created = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User, related_name="driver_review_created_by", on_delete=models.CASCADE, null=True, blank=True)
last_updated = models.DateTimeField(auto_now=True)
last_updated_by = models.ForeignKey(User, related_name="driver_review_last_updated_by", on_delete=models.CASCADE, null=True, blank=True)
is_deleted = models.BooleanField(default=False)
deleted = models.DateTimeField(null=True, blank=True)
deleted_by = models.ForeignKey(User, related_name="driver_review_deleted_by", on_delete=models.CASCADE, null=True, blank=True)
#property
def review_average_score(self):
review_average_score = round(np.mean([self.driving_score, self.communication_score, self.professionalism_score]), 2)
return review_average_score
I have created a property to get the review average score. The issue is that I don't want to hardcode the _score fields. Is there a way to filter the fields that contain _score and use them in the average ?
Yes, you can inspect the fields through the _meta, so:
#property
def review_average_score(self):
data = [
getattr(self, f.attname)
for f in self._meta.get_fields()
if '_score' in f.name
]
review_average_score = np.mean(data), 2)
return review_average_score

Is this possible? Using signals to set a global variable

I have made this function that runs every time a user logs in. I want to get the branch from 'user' but every time the session is set it's only available to the function even after setting it to BRANCH_ID in the settings file. any help? plus I don't want to do anything in view function with the request as it's not accessible from models
EDIT
I have added all the models
def perform_some_action_on_login(sender, request, user, **kwargs):
"""
A signal receiver which performs some actions for
the user logging in.
"""
request.session[settings.BRANCH_ID] = user.profile.branch_id
branch = request.session.get(settings.BRANCH_ID)
print(branch)
user_logged_in.connect(perform_some_action_on_login)
class WaybillTabularInlineAdmin(admin.TabularInline):
model = WaybillItem
extra = 0
# form = WaybillItemForm
fk_name = 'waybill'
autocomplete_fields = ('product',)
class WaybillAdmin(admin.ModelAdmin):
list_display = (
'from_branch',
'to_branch',
'updated_by',
)
list_filters = (
'from_branch',
'to_branch',
'product',
)
inlines = [WaybillTabularInlineAdmin]
readonly_fields = ("updated_by",)
what I was trying to do is products by the branch
class Waybill(models.Model):
from_branch = models.ForeignKey(
Branch,
default=1,
on_delete=models.CASCADE, related_name='from_branch')
to_branch = models.ForeignKey(
Branch, on_delete=models.CASCADE, related_name='to_branch')
comments = models.CharField(max_length=1024, blank=True)
created_date = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(
User, on_delete=models.CASCADE,
blank=True, null=True,
related_name='waybill_created')
updated = models.BooleanField(default=False)
updated_by = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='waybill_user')
def __str__(self):
return 'from {} to {}'.format(
self.from_branch.branch_name,
self.to_branch.branch_name,
)
class WaybillItem(models.Model):
waybill = models.ForeignKey(Waybill, on_delete=models.CASCADE)
product = models.ForeignKey(ProductDetail, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
def __str__(self):
return 'from {} to {}'.format(
self.waybill.from_branch,
self.waybill.to_branch
)
class Product(models.Model):
item = models.ForeignKey(
Item, on_delete=models.CASCADE, related_name="product")
branch = models.ForeignKey(
Branch, default=1, on_delete=models.CASCADE)
in_stock = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now=True)
objects = ProductManager()
class Meta:
verbose_name = "Inventory"
verbose_name_plural = "Inventories"
ordering = ("-created_date",)
constraints = [
models.UniqueConstraint(
fields=['item', 'branch'], name='unique product'),
]
def __str__(self):
return self.item.item_description
class ProductDetail(models.Model):
ITEM_CONDITION_CHOICES = (
("NEW", "New"),
("BROKEN", "Broken"),
("FAIRLY USED", "Fairly Used"),
)
condition = models.CharField(max_length=12, choices=ITEM_CONDITION_CHOICES,
default=ITEM_CONDITION_CHOICES[0][0])
product = models.ForeignKey(Product, on_delete=models.CASCADE)
short_description = models.CharField(max_length=255, blank=True)
color = models.CharField(max_length=15, blank=True)
bought_price = models.PositiveIntegerField(default=0.00)
sales_price = models.PositiveIntegerField(default=0.00)
retail_price = models.PositiveIntegerField(default=0.00)
item_code = models.CharField(max_length=15, default=0)
item_model_number = models.CharField(max_length=20, default=0)
quantity = models.PositiveIntegerField(default=0)
manufacturer_website = models.CharField(max_length=255, blank=True)
generated_url = models.CharField(max_length=255, blank=True)
created_date = models.DateTimeField(default=timezone.now)
updated_date = models.DateTimeField(auto_now=True)
# objects = ProductDetailManager()

Categories

Resources