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?
Related
I am struggling with a weird issue in Django (4.0.7) where multiple instances for the same primary key are shown in Django Admin, as well as when executing queries. I have displayed the primary keys to make clear that they are identical:
The two classes involved are Collection and Card, where every card has a foreign key to a collection.
class Collection(models.Model):
FREQUENCY_CHOICES = [('never', 'Never'), ('less', 'Less'), ('normal', 'Normal'), ('more', 'More')]
title = models.CharField(max_length=200)
author = models.CharField(max_length=200, blank=True, null=True)
user = models.ForeignKey(User, related_name='collections', on_delete=models.CASCADE)
type = models.CharField(max_length=10, choices=(('books', 'Books'), ('tweets', 'Tweets'), ('articles', 'Articles'), ('podcasts', 'Podcasts')))
custom_id = models.CharField(max_length=200, blank=True, null=True) # e.g. raindropref, amazon book id, etc.
url = models.URLField(blank=True, null=True)
tags = TaggableManager(blank=True)
connection = models.ForeignKey(Connection, related_name='collections', null=True, blank=True, on_delete=models.SET_NULL)
frequency = models.CharField(max_length=10, choices=FREQUENCY_CHOICES, default='normal')
class Card(models.Model):
text = models.TextField()
collection = models.ForeignKey(Collection, related_name='cards', on_delete=models.CASCADE, blank=True)
custom_id = models.CharField(max_length=200, null=True, blank=True)
author = models.CharField(max_length=200, null=True, blank=True)
url = models.URLField(blank=True, null=True)
created_at = models.DateTimeField(default=timezone.now)
favorite = models.BooleanField(default=False)
tags = TaggableManager(blank=True)
notes = models.TextField(blank=True, null=True)
location = models.IntegerField(blank=True, null=True)
I cannot fathom where the issue might be. I have already set up the databse from scratch, with no success.
Here is an example database query:
for c in Collection.objects.all():
print(c.pk, c.id)
12 12
12 12
12 12
13 13
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.
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
I have a User model that has 20 count field:
class User(models.Model):
username = models.CharField(max_length=16)
password = models.CharField(max_length=40) # sha1
real_name = models.CharField(max_length=12, null=True,blank=True)
phone = models.CharField( max_length=11)
email = models.EmailField(blank=True, null=True )
qq = models.CharField(max_length=10, null=True, blank=True)
address = models.CharField(max_length=64, blank=True, null=True)
id_card = models.CharField(blank=True, null=True, max_length=18, validators=[RegexValidator(regex='^.{18}$', message='身份证长度必须为18', code='nomatch')])
id_card_img_front = models.CharField(max_length=256, blank=True, null=True)
id_card_img_back = models.CharField(max_length=256, blank=True, null=True)
nickname = models.CharField(max_length=16, blank=True, null=True)
profile = models.CharField(max_length=256, blank=True, null=True, default=' ')
usertype = models.ForeignKey(to='UserType', default=1, blank=True)
user_c_type = models.CharField(max_length=4, null=True)
fixed_phone = models.CharField(max_length=16, null=True)
fax = models.CharField(max_length=16, null=True)
main_bussiness = models.CharField(max_length=16, null=True)
main_industry = models.CharField(max_length=16, null=True)
company_name = models.CharField(max_length=32, null=True)
company_address = models.CharField(max_length=32, null=True)
province = models.CharField(max_length=32, null=True, default="--省--")
town = models.CharField(max_length=32, null=True, default="--市--") # 省市县
country_level = models.CharField(max_length=32, null=True, default="--县--")
ctime = models.DateTimeField(auto_now_add=True)
uptime = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, null=True, default=1)
And in my Django project, I want to use Paginator to realize paging for user list.
Because the count of my user in my database is no more than 10,000 rows.
So, whether I can get all of the user in my database then paginate them?
user_all = models.User.objects.all()
paginator = Paginator(user_all, 10)
try:
user_list_page = paginator.page(page_number)
except PageNotAnInteger:
user_list_page = paginator.page(1)
except EmptyPage:
user_list_page = paginator.page(paginator.num_pages)
And I don't know whether this method(query out all the rows of user data) is inefficiency.
Or, how to weight the balance of query out the users from database? For a positive limit numbers ( over the count I should change paginate method, less than that I can use my page method )?
Or is there a better method to paginate my users?
The generic ListView brings a paginator. You should make sure that your queryset is sorted, otherwise the pages might repeat some of the objects (that is not a Django issue - paging without a sort order is just not practical).
https://docs.djangoproject.com/en/1.11/ref/class-based-views/generic-display/#listview
from django.views.generic.list import ListView
class UserListView(ListView):
template = 'my_user_list_template.html'
model = User # not django.contrib.User but your's
paginate_by = 10
def get_queryset(self):
return super().get_queryset().order_by('realname', 'pk')
The template will contain all context data required to render pagination, and the max 10 objects for the current page.
There are 3rd party modules like pure_pagination that extend the pagination to allow for other GET parameters in the pagination links: https://github.com/jamespacileo/django-pure-pagination
More links:
https://docs.djangoproject.com/en/1.11/ref/class-based-views/mixins-multiple-object/#django.views.generic.list.MultipleObjectMixin.paginate_by
See also on the same page: paginate_orphans, paginator_class etc.
I have 2 models that are connected.
Model 1 is userprofiles and model 2 is events
each user can have multiple events... each event can be active or deactivated.
I have a for loop in the template showing all the userprofiles... but I also want to show how many active events each user has.
today = datetime.now().strftime('%Y-%m-%d')
perm = Permission.objects.get(codename='chef_user')
user_profiles = User.objects.filter(profile__user_profile_active='y').filter(is_active=True).filter(Q(groups__permissions=perm) | Q(user_permissions=perm)).distinct()[:6]
in the template I have my loop
{% for kitchen_list in user_profiles %}
-- CODE --
{{ kitchen_list.events_set.count }} <--- WHERE I AM TRYING TO SHOW ACTIVE EVENTS COUNT
--CODE--
{% endfor %}
my models:
class UserProfile(models.Model):
EVENT_TYPE = (('0', "Apartment"), ('1', "Home"),)
CURRENCY = (('R', "Rand"),)
OPTIONS = (('y', "Yes"),('n', "No"),)
OPTIONS_USER = (('y', "Yes"), ('n', "No"),('p', "Pending"),)
user = models.OneToOneField(User, related_name='profile')
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,12}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
phone = models.CharField(validators=[phone_regex], max_length=12, default='', blank=True) # validators should be a list
currency = models.CharField(max_length=50, blank=True, default='R', choices=CURRENCY)
bookingpermissions = models.CharField(max_length=100, blank=True, default='n', choices=OPTIONS)
title = models.CharField(max_length=50, default='', blank=True)
bio = models.TextField(max_length=500, default='', blank=True)
city = models.CharField(max_length=100, default='', blank=True)
longitude = models.CharField(max_length=100, default='na', blank=True)
latitude = models.CharField(max_length=100, default='na', blank=True)
image = ResizedImageField(size=[400, 400], crop=['middle', 'center'], upload_to='userprofile/static/images', default='', blank=True)
kitchen_type = models.CharField(max_length=50, blank=True, default='a', choices=EVENT_TYPE)
user_profile_active = models.CharField(max_length=1, default='n', blank=True, choices=OPTIONS_USER)
class Events(models.Model):
ACTIVE = (('d', "Deactivated"), ('e', "Expired"), ('a', "Active"), ('b', "Drafts"),)
ALCOHOL = (('0','No bring own alcohol'),('1','There will be complimentary wine pairing'))
user = models.ForeignKey(User, on_delete=models.CASCADE)
active = models.CharField(max_length=1, default='b', choices=ACTIVE)
title = models.CharField(max_length=50, blank=True, default='')
description = models.TextField(max_length=500, blank=True, default='')
date = models.DateField()
time = models.TimeField()
price = models.CharField(max_length=240, blank=True, default='')
seats = models.IntegerField()
alcohol_choice = models.CharField(max_length=1, default='n' ,choices=ALCOHOL)
starter = models.TextField(max_length=350, blank=True, default='')
main_menu = models.TextField(max_length=350, blank=True, default='')
dessert = models.TextField(max_length=350, blank=True, default='')
notes = models.TextField(max_length=350, blank=True, default='')
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.title
you can try use model propery
in model:
class UserProfile(models.Model):
# You code here
#property
def active_events(self):
return self.user.events_set.filter(active='a').count()
in template:
{{ kitchen_list.userprofile.active_events }}
Rather do it in the views.py instead of the template to count then pass the values to the template. Assuming you hva e set up the foreign relations well in the models then in the views do the following:
user_profiles = User.objects.filter(profile__user_profile_active='y').filter(is_active=True)
counts = user_profiles.events_set.count()
Then pass that as a context.
Or you can try creating a method in your model UserProfile:
class UserProfile:
....
def events(self):
return self.events_set.count()