Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In django, what is the correct way to pass a form input into a custom email template as a variable?
Here is my email view function in which I am passing form to context and I have tried using the {{ form.name.value }} as suggested in other posts but in the received email, it doesn't appear in email_invite.html template attachment; not even a white space. How can I get that name variable to render. I got it in the subject but do I need to also pass name in to the context and how if so is the correct way to use it in the template. Thanks in advance def email_invite(request): if request.method == 'POST': form = EmailInviteForm(request.POST) if form.is_valid(): cd = form.cleaned_data name = f'{cd["name"]}' subject = f'{cd["name"]} has sent you a invitation' from_email = settings.DEFAULT_FROM_EMAIL comment = f'{cd["comment"]}' html_template = get_template('profiles/email/email_invite_message.html').render() msg = EmailMultiAlternatives(subject, comment, from_email, [cd['to']]) msg.attach_alternative(html_template, 'text/html') msg.send(fail_silently=False) messages.success(request, 'Your email has been sent') return HttpResponseRedirect(reverse('profiles:find_friends')) else: form = EmailInviteForm() template = 'profiles/email_invite.html' context = { 'form': form, } return render(request, template, context) -
django.urls.exceptions.NoReverseMatch: Reverse for 'email-verify' not found. 'email-verify' is not a valid view function or pattern name
Not sure why this error is happening to me, I'm trying to send a verification email to a new registered user. Here is my error: django.urls.exceptions.NoReverseMatch: Reverse for 'email-verify' not found. 'email-verify' is not a valid view function or pattern name. I clearly state the name of the url and link everything up to my understanding. Here is my code: users/urls.py from django.urls import path from .views import CustomUserCreate, VerifyEmail, BlacklistTokenUpdateView app_name = 'users' urlpatterns = [ path('register/', CustomUserCreate.as_view(), name="register"), path('email-verify/', VerifyEmail.as_view(), name="email-verify"), path('logout/blacklist/', BlacklistTokenUpdateView.as_view(), name='blacklist'), ] users/view.py from django.urls import reverse from django.contrib.sites.shortcuts import get_current_site from rest_framework_simplejwt.views import TokenObtainPairView from rest_framework import generics ,status from rest_framework.response import Response from rest_framework.views import APIView from rest_framework_simplejwt.tokens import RefreshToken from rest_framework.permissions import AllowAny from .models import NewUser from .serializers import RegisterSerializer from .utils import ConfirmEmail class CustomUserCreate(generics.GenericAPIView): permission_classes = [AllowAny] serializer_class = RegisterSerializer def post(self, request, format='json'): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data user = NewUser.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('email-verify') #Error starts here absurl = 'http://'+current_site+relativeLink+"?token="+str(token) email_body = 'Hi '+user.username + \ ' Use the link below to verify your email \n' + absurl data = {'email_body': email_body, 'to_email': user.email, 'email_subject': 'Verify … -
How to fix unsupported operand type(s) for +: 'NoneType' and 'str'
I am trying to interate Weazyprint to my project so that I can download order details as a PDF as a Receipt from admin side for my Django E-commerce project, but I am receiving the following error: TypeError at /store/admin/order/3/pdf/ unsupported operand type(s) for +: 'NoneType' and 'str' I have installed pip install weasyprint Here is the views.py: @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order,ordered=True, id=order_id) html = render_to_string('store/pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATIC_ROOT+ 'blog/main.css')]) return response Here is the traceback: Traceback (most recent call last): File "C:\Users\Ahmed\Desktop\Project\venv\lib\site-packages\django\core\handle rs\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Ahmed\Desktop\Project\venv\lib\site-packages\django\core\handle rs\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Ahmed\Desktop\Project\venv\lib\site-packages\django\contrib\aut h\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Ahmed\Desktop\Project\store\views.py", line 593, in admin_order _pdf stylesheets=[weasyprint.CSS(settings.STATIC_ROOT+ 'blog/main.css')]) TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' Here is the settig.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Here is the admin.py from import_export.admin import ImportExportActionModelAdmin, ImportExportModelAdmin, ExportMixin def order_pdf(obj): return mark_safe('<a href="{}">PDF</a>'.format(reverse('store:admin_order_pdf', args=[obj.id]))) order_pdf.short_description = 'Order PDF' class OrderAdmin(ExportMixin, admin.ModelAdmin): list_display = ['id', ..... ,order_pdf] My question: What am i doing wrong which is leading to this error? How do I … -
Django DRF: default values in the model are not getting used
I have a model class Sample(model.Models): is_active = BooleanField(default=True) Now i craete a serializer class SampleSerializer(models.Model): class Meta: model = Sample Now trying to save with serializer and expecting it to use default value when not provided data = {} serializer = SampleSerializer(data = data) instance = serializer.save() but i see the value of instance.is_active as False -
django count and filter by the foreign key of foreign key
I'm struggling with getting a QuerySet of incomplete Poll objects in an optimal and fancy way. There is a poll model that has sections, each section has a group of questions. Then the answers have a foreign key to a question. This was modeled that way to allow an admin to create large polls separated into different sections and their questions have different answer types (Text, bool, choice, etc). A poll is considered incomplete if the number of answers is less than the number of questions. How can I get a list (QuerySet) of incomplete Polls of a given user? The simplified model is: class Polls(models.Model): name = models.TextField() active = models.BooleanField() @property def num_questions(self): return Questions.objects.filter(section__poll=self).count() @property def questions(self): """ Returns a Queryset of Questions that can be used to filter questions of this poll regardless how they were split by sections """ sections = Sections.objects.filter(Q(poll=self)) questions = Questions.objects.filter(Q(section__in=sections)) return questions def unanswered_questions_by_user(self, user: User): """ Returns a queryset of Questions that haven't been responded by a given user """ answered_questions = user.answers.filter( question__in=self.questions).values_list('question__pk', flat=True) unanswered_questions = self.questions.exclude(pk__in=answered_questions) return unanswered_questions class Sections(models.Model): name = models.TextField() poll = models.ForeignKey(Poll) class Questions(models.Model): question = models.TextField() section = models.ForeignKey(Section) class Answer(models.Model): user … -
Django REST API and Nuxt.js - (CORS error in Nuxt)
I can access my Django REST api using Postman however when I run it on Nuxt, I get the "has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." Let me know which parts of my code you would like to see and I will be happy to share. -
Import and modify a .ics calendar file on my own webpage
So I am making a web app for an inventory and the web app needs a calendar which already exists in the form of an outlook calendar. I have managed to import the calendar link as a .html and as a .ics file and I have added the calendar to my website. The problem is modifying the calendar: the website needs me to add 'tags' on the calendar (for bookings made) such that hovering over or clicking on a tag shows booking details. Because the imported calendar is basically an outlook calendar I am unable to implement this. Is there a way to do that? Or perhaps, is there a way for me to make my own calendar on HTML/CSS and then add the .ics file to my own self-designed calendar? Ps: I am using Django, html, CSS for development. Thank you! -
Django get_absolute_url for ManyToManyField
I am trying to set up a site for the url flow to be: states -> county -> storename With ForeignKey between county and state I was able to use get_absolute_url with something like: def get_absolute_url(self): return reverse('county-detail', args=[str(self.states),str(self.county) I am now trying to create my model for storename and am having problems with manytomany relationships. I tried making states and county foreign keys within the model and it works with get_absolute_url. However, storenames can be in multiple states and counties. My current model code is: class StoreName(models.Model): name = models.CharField(max_length=100) county = models.ManyToManyField('county') states = models.ManyToManyField('states') def get_absolute_url(self): return reverse('StoreName-detail', args=[str(self.states),str(self.county),str(self.name)]) I am getting the error: 'Reverse for 'StoreName-detail' with arguments '('ls.states.None', 'ls.country.None', 'Ralphs')' not found' Is there a way to have states and county populate data for the args like it did when they were foreignkeys? -
Django model to automatically update username and date/time when Article modified
I have a model called Post and I am trying to automatically save the username of the logged in user who last modified the article along with the timestamp. So far DateTime timestamp is updating values but I am unable to achieve the same result with the username. class Post(models.Model): article = models.TextField(max_length=2000) username = models.ForeignKey(User, on_delete=models.CASCADE, related_name='usernames') updated_at = models.DateTimeField(auto_now=True) -
How I can all the current user who posses a subdomain using django tenant
I am using django tenant for a sass application. Following are the model configuration. How I can call the present user who owns the current subdomain class Client(TenantMixin): name = models.CharField(max_length=100) paid_until = models.DateField(default=ten_days) on_trial = models.BooleanField(default=True) created_on = models.DateField(auto_now=True) user = models.ForeignKey(User, related_name='clients', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name class Domain(DomainMixin): pass DomainMixin config is as follows in the package class DomainMixin(models.Model): domain = models.CharField(max_length=253, unique=True, db_index=True) tenant = models.ForeignKey(settings.TENANT_MODEL, db_index=True, related_name='domains', on_delete=models.CASCADE) # Set this to true if this is the primary domain is_primary = models.BooleanField(default=True, db_index=True) settings.TENANT_MODEL is pointing to Client, I tried as follows current_site = Site.objects.get_current() try: current_domain = current_site.domain domain_active = Domain.objects.get(domain=current_domain) user = domain_active.tenant.user print(user) except: pass But not getting output on terminal, somebody can show me the right way -
Django Search Bar Function Not Yielding Results
I have a table that is shown in my django app that I am trying to filter with a search bar. I am not receiving any errors, but whenever I search anything (id, name, etc) no data pops up. search.html: {% extends "polls/stakeholders.html" %} {% block content %} {% for stakeholder in all_search_results %} <h3>{{stakeholder.employee}}</h3> <p>{{stakeholder.description}}</p> {% empty %} <h2>No results found</h2> {% endfor %} {% endblock %} stakeholders.html (table and search bar portion): <form class="form-inline my-2 my-lg-0" method="GET" action="{% url 'polls:search' %}"> <input class="form-control mr-sm-2" type="search" name="search"> <button class="btn btn btn-outline-info my-2 my-sm-0" type="submit"> Search </button> </form> <br> <table class="table table-hover" style="width:90% "> <thead> <tr style="font-family: Graphik Black; font-size: 14px"> <th scope="col">#</th> <th scope="col">Employee</th> <th scope="col">Stakeholder Group</th> <th scope="col">Quadrant</th> <th scope="col">Description</th> </tr> </thead> <tbody> {% for stakeholder in stakeholder_list %} <tr style="font-family: Graphik;font-size: 12px"> <td>{{ stakeholder.id }}</td> <td style="font-size: 15px">{{ stakeholder.employee }}</td> <td>{{ stakeholder.stakeholder_group }}</td> <td>{{ stakeholder.stakeholder_quadrant }}</td> <td>{{ stakeholder.description }}</td> <td><button type="button" class="btn btn-danger btn-sm badge-pill" style="font-size: 11px; width:60px" data-toggle="modal" data-target="#new">Edit</button></td> </tr> {% endfor %} </tbody> </table> urls.py path('results/', views.SearchView.as_view(), name='search'), views.py (currently filters by id, but i've already tried the other fields) class SearchView(ListView): model = Stakeholder template_name = 'polls/search.html' context_object_name = 'all_search_results' def get_queryset(self): result = … -
HTML Containers Going Over the Page
I am relatively new to HTML but am getting a weird result from my django app. I have outlined what I have vs. what I'm looking for below for reference. As you can see by my code, the only places that I have called out a height is in that iframe which is pushing down the rest of the contents outside of container two. Container one is also purposed to extend the entire height of the page (that's just a side bar) and there should be some padding at the bottom of the page after the last container. Any idea why this is happening? HTML <div class="two" style="padding-left: 15px;padding-right: 15px"> <div class="card"> <iframe width="1220" height="1241" src="x" ... > </div> <div class="card"> </div> </div> style.css .container { width: 100%; height: 100%; background: rgb(233, 236, 239); margin: auto; padding: 10px; } .one { width: 15%; background:white; float: left; } .two { margin-left: 15%; background: rgb(233, 236, 239); } Current: Desired: -
Django: Checkbox Onclick Event
I want to make it so that if To be annouced is clicked then the form input for the release date disapears. How can I add an onclick to the checkbox of a form input? Templates: {{form.tba.label}} {{form.tba}} <p>{{form.release_date.label}} (not required)</p> <div class="date_container">{{form.release_date}}</div> forms: tba = forms.BooleanField(label="Release date to be announced", widget=forms.CheckboxInput(attrs={'class': 'form_input_bool'}), required=False) release_date = forms.DateField(widget=forms.SelectDateWidget(attrs={'class': 'form_input_select_date'}, years=YEARS, empty_label="---"), required=False) -
How to configure viewset and router based on existing viewset and router?
I am a newbie in django and am trying to dabble with social website. I have a question. I have a Discussion Viewset class DiscussionViewSet(viewsets.ModelViewSet): # general implementation with urls.py router = DefaultRouter() router.register('discussions', views.DiscussionViewSet) app_name = 'discussion' urlpatterns = [ path('', include(router.urls)) ] So, this generate /discussion/discussions/, /discussion/discussions/2. etc.. Now, I am trying to add a similar "Comment" ViewSet on "Discussion" I am hoping to have the functionality like discussion/discussions/2/comment/ -> post new comment and discussion/discussions/2/comment/1 -> retrieves the comment. and so on.. I found an example here: https://github.com/DK-Nguyen/django-social-network/blob/master/discussion/urls.py but they are using a different way to achieve this but I want to use ViewSet and router to achieve this? -
Django url (slug)
The question is, I have a mini-blog, there are articles and user profile (pages). I display articles at site/articlename I want to display the user account at site/username views.py (article): def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) return render(request, 'post_detail.html', {'post': post }) views.py (profile users): class UserProfileView(DetailView): template_name = 'users/profile/profile-user-view.html' queryset = User.objects.all() def get_object(self): username = self.kwargs.get("username") return get_object_or_404(User, username=username) URL's: path('<str:username>', UserProfileView.as_view(), name='user_detail') path('<slug:slug>', views.post_detail, name='post_detail') Now my user profile opens at site/username, but the article does not open at site/article name. I suspect some kind of conflict in the URL (slug). How can I make it so that both articles and an account at the site / address are opened without additional directories. I would be grateful for any help. -
Methode() got multiple values for argumen 'name'
i trying to do Django3 by example online shop => cart section and i tried this for my cart View @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(MainProduct, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product, quantity= cd['quantity'], override_quantity=cd['override'], color = cd['color'], size = cd['size'], ) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) and this for cart.py that handle my cart requests class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self,color,size, product,quantity=1, override_quantity=False): """ Add a product to the cart or update its quantity. """ # self.cart['color'] = color # self.cart['size'] = size product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price), 'color' : str(colors), 'size': str(sizes) } if override_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() and i have this Error Exception Value: add() got an unexpected keyword argument 'colors' but when i ignore color and size that will work with no Error ... -
i am not able to render my urls in my template it gives me error rendering
NoReverseMatch at / Reverse for 'Jersey' with no arguments not found. 1 pattern(s) tried: ['Jersey/(?P[^/]+)/$'] Below is the code to my views.py class JerseyView(TemplateView): #paginate_by=3 template_name='Ecommerce/Jersey.html' def get_context_data(self, **kwargs): et =super(JerseyView, self).get_context_data(**kwargs) et['United']= Item.objects.filter(category="3").filter(subcategory="9") et['Chelsea']= Item.objects.filter(category="3").filter(subcategory="10") return et below is the code for my urls.py path('Jersey/<slug>/', JerseyView.as_view(), name="Jersey" ), I called This link in my Navbar as <a class="dropdown-item" href="{% url 'Ecommerce:Jersey' %}">Men's Clothing</a> when I click on it it gives me the error as NoReverseMatch at / Reverse for 'Jersey' with no arguments not found. 1 pattern(s) tried: ['Jersey/(?P[^/]+)/$'] I don't know if there's something i am missing out because i have checked my spelling and still getting the same error -
Update field in db in django from views with existing form, won't update because of "Integrity Error"
My first post, really newbie at programming. I am having issues to update a field in a form. I'll try to explain my best. I have a Catalog class (products or services) with a couple fields, 2 of them must be unique. models.py class Catalogo(models.Model): item = models.CharField( max_length=100, help_text="Product or service name", unique=True ) sku = models.CharField(max_length=50, help_text="Part Number", unique=True) category = models.CharField( max_length=15, choices=categoria, verbose_name="Category" ) description = models.CharField( max_length=200, help_text="Item description", verbose_name="Descripción", ) created = models.DateTimeField(auto_now_add=True, help_text="Created") updated = models.DateTimeField(auto_now_add=True, help_text="Updated") active = models.BooleanField(default=True) class Meta: verbose_name = "product and service" verbose_name_plural = "products and services" def __str__(self): return self.item Then i have a form to gather the information forms.py categories = [("Product", "Product"), ("Service", "Service")] class NewProductForm(forms.Form): item = forms.CharField( widget=forms.TextInput(attrs={"class": "form-control"}), label="Item", max_length=100, ) sku = forms.CharField( widget=forms.TextInput(attrs={"class": "form-control"}), label="Part number", max_length=50, ) category = forms.ChoiceField( choices=categories, label="Category", ) description = forms.CharField( widget=forms.Textarea(attrs={"class": "form-control"}), label="Item description", ) Now for the views...i created 2 functions, one for adding new product/service and one for updating views.py def new_prod_serv(request): new_form = NewProductForm() if request.method == "POST": new_form = NewProductForm(request.POST) if new_form.is_valid(): new_product = Catalogo( item=new_form["item"].value(), sku=new_form["sku"].value(), category=new_form["category"].value(), description=new_form["description"].value(), ) new_product.save() return redirect("products-services") else: print(new_form.errors) context = {"formulario": new_form} … -
Errors while reloading Django project
In my Django project, which I run from batch file in Cmd, I get the following errors after I update the code and the code is reloading, which crashes my cmd and causes an exit from it: ** On entry to SGEBRD parameter number 10 had an illegal value ** On entry to SBDSVDXSafe MinimumPrecisionEpsilon parameter number 2 had an illegal value What is the meaning of these two lines? And how to prevent my code from crashing? -
Add extra fields to django form depending on another field value
I have a model 'Project' that is supposed to take multiple installment percentages of the total project cost. For example, if total cost of the project is $100, there can be four or five or as many installments are set. So one field is 'num_installment' = 4 (say). Now each installment can have different percentages of total cost (eg, 50,30,10,10 or any such combination). The problem is, since we don't know the number of installments prior to the form validation, the installment percentage fields can't be set before hand. So we need a dynamic form where four (or n number of) installment fields are popped up according to the num_installment field value. The Project model- class Project(models.Model): client = models.ForeignKey(Client, null=True, on_delete=models.SET_NULL) description = models.CharField(max_length=200, null=True, blank=True) net_charge = models.FloatField(null=True) num_isntallment = models.IntegerField(null=True) installments = ?????? -
two url django (slug and username)
I have a small blog, there was a little problem. I have articles and I have user profiles. I want articles to open at: http://127.0.0.1:8000/namearcticle There are user profiles, I want them to open at: http://127.0.0.1:8000/username My views article views.py: def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) return render(request, 'post_detail.html', {'post': post }) My views UserNameProfile views.py: : class UserProfileView(DetailView): template_name = 'users/profile/profile-user-view.html' queryset = User.objects.all() def get_object(self): username = self.kwargs.get("username") return get_object_or_404(User, username=username) URL's: path('<str:username>', UserProfileView.as_view(), name='user_detail'), path('<slug:slug>', views.post_detail, name='post_detail'), Now when trying to open the article, the error is: Page not found (404) Request URL: http://127.0.0.1:8000/testarcticle Raised by: users.views.UserProfileView No User matches the given query. Although the user page opens. The question is, how can I make it so that I can open user profiles at the article address? site/username site/article -
Can't create the same object in Django HTML
I need to create 4 objects like the first one. But the second and the next iterations create objects under the first. Looks like there must be one more in the cycle. But doesn't. tamplate {% extends "main/base.html" %} {% block content %} <div class="row"> {% for item in articles %} <div class="col-md-12"> <div class="card mb-3" style="max-width: 540px; color: #212529"> <div class="row no-gutters"> <div class="col-md-4"> <img src="link" class="card-img" alt="..."> </div> <div class="col-md-8"> <div class="card-body"> <h5 class="card-title"><a href={% url 'articles-detail' item.id %}> {{ item.title | safe }}</a></h5> <p class="card-text">{{ item.content | safe | slice:":255" }}...</p> <p class="card-text"><small class="text-muted">{{ item.pub_date | date:"d-m-Y H:i" }} | {{ item.author }}</small></p> </div> </div> </div> </div> </div> {% endfor %} </div> {% endblock %} how it looks on the web-site -
Entries not showing up in the django table
Problem: I have got one contact model. In this contact model, I`ve got severals type (supplier, Customer and Employee). The data has been uploaded in the SQL table but it is not showing up in Django/html table. Do I need to change the way how my model is written? Thanks in advance Model: class Contact(models.Model): CONTACT_TYPE = ( (0, 'Customer'), (1, 'Supplier'), (2, 'Employee'), ) GENDER = ( (0, 'Male'), (1, 'Female'), ) type = models.IntegerField(choices=CONTACT_TYPE,default=1) gender = models.IntegerField(choices=GENDER,default=0) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) Views: def index_supplier(request): contacts = Contact.objects.all() suppliers = Contact.objects.filter(type=1).all() count_supplier= Contact.objects.filter(type=1).count() context = { 'contacts': contacts, 'count_supplier': count_supplier, } return render(request, 'contacts/index_supplier.html', context) Templates: <div class="container-fluid"> <div class="col-sm-20"> <table id="dtBasicExample" class="table table-striped table-hover"> <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script> <script> $(document).ready(function(){ $('#dtBasicExample').DataTable(); }); </script> <thead> <tr> <th>Type</th> <th>Contact Name</th> <th>Company</th> </tr> </thead> <tbody> {% for contact in suppliers.all %} <tr> <td>{{ contact.get_type_display }}</td> <td>{{ contact.first_name }}</td> <td>{{ contact.company }}</td> </tr> {% endfor %} </div> </div> -
OSError: [Errno 9] Bad file descriptor, every command for python
**every command are fail. i cannot run any command. it show OS error** -
Provide different pricing/ product information depending on logged in user in Django
I am building an ecommerce site in Django that is intended for B2B (business to business) and B2C (business to consumer) transactions. Regarding B2C, I could store the retail price in the databse. However, regarding B2B, the price can take on many values (infinite options). The pricing structure depends on some real-world agreements between the businesses. So the Supplier can create "Pricing Policies". This would require providing different pricing through different markup and margins on the product cost (cost stored in the database), or provide different shipping/ tax cost structures depending on the user account location. It could entail providing different discounts on the retail price according to the volume of sales on that business account. I imagined that the Supplier can create pricing policies (through some PricingPolicy model) and when the Business Customer logs in, they would see their relevant prices. It is not practical to store a different price for each product for every Business Customer in the database. How would one implement different pricing depending on the logged in user account?