I create a customer model and a function for assign a customer to a user. Assign function is update user field in Customer model.
This Customer model has a country field. I want to assign the customers in the same country to a user with one form. For doing that I have listing all countries and a form for assign operation? How can I do that?
Edit: Now, I can get country name and the user for assigning. How can I use these attributes and update the objects (Customer) with chosen country and user.
models.py
class Customer(models.Model):
customer_name = models.CharField(max_length=20)
country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, unique=False)
...
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, blank=True, null=True)
class Country(models.Model):
REGION = [
('Northwest Europe', 'Northwest Europe'),
('Southwest Europe', 'Southwest Europe'),
...
]
country_name = models.CharField(max_length=30)
country_code = models.CharField(max_length=5)
views.py
def country_customer_list(request):
current_user = request.user
userP = UserProfile.objects.get_or_create(username=current_user)
customer_list = Customer.objects.filter(company=userP[0].company)
countries = Customer.objects.values_list('country__country_name', flat=True).distinct()
form = CountryForm(request.POST or None)
if request.POST:
country_form = request.POST.get('country_form', None)
user = request.POST.get('user', None)
form.save()
print(country_form)
print(user)
return redirect('user:customer_countries')
context = {
'customer_list': customer_list,
'countries': countries,
'form': form
}
return render(request, 'country_customer_list.html', context)
country_customer_list.html*
<table id="multi-filter-select" class="display table table-striped table-hover grid_" >
<thead>
<tr>
<th>Country</th>
<th>Operations</th>
</tr>
</thead>
<tbody>
{% for country in countries %}
<tr>
<td>{{country}}</td>
<td>
<button type="button" class="btn btn-info btn-block" data-toggle="collapse" data-target="#demo{{ forloop.counter }}"> Assign </button>
<div id="demo{{ forloop.counter }}" class="collapse">
<form method="post">
{% csrf_token %}
{{ form|crispy }}
<input type="hidden" name="country_form" value="{{ country }}">
<button type="submit" class="btn btn-primary btn-sm">Assign</button>
</form>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
forms.py
class CountryForm(forms.ModelForm):
class Meta:
model = Customer
fields = ('user',)
Populate Country models with your choise, and they will appear in the template
Change models
class Country(models.Model):
country_name = models.CharField(max_length=30)
country_code = models.CharField(max_length=5)
def __str__(self):
return str(self.country_name) + ' ' + str(self.country_code)
forms.py
class CountryForm(forms.ModelForm):
class Meta:
model = Customer
fields = ('user','country',)
in template
{{form.country}}
Related
In my project my user should be able to submit an appointment (class UserAppointment) based on the responsibility given by the staff (class StaffDuty). So I'd like to use the CreateView class of the UserAppointment model and ListView class for the StaffDuty model in the same template. With my code I can access the data from the StaffDuty model but I'm not able to submit the form for UserAppointment model, since the submit button does nothing.
Also I'd like to automatically assign the staff and event foreign key and pass data from StaffDuty to complete form.instance.date_appointment with the date given in the staff model and form.instance.event_name with the name of the event that is found in the Event model. But my code is not working at all
models.py
class Event(models.Model):
name = models.CharField(max_length=255)
staff_needed = models.PositiveIntegerField()
date = models.DateField()
spots_total = models.PositiveIntegerField()
venue = models.CharField(max_length=255)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('event_details', args=[str(self.id)])
class StaffDuty(models.Model):
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
event = models.ForeignKey(Event, on_delete=models.CASCADE)
date_work = models.DateField()
shift = models.CharField(max_length=255)
def __str__(self):
return self.event.name | str(self.date_work)
class UserAppointment(models.Model):
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
staff = models.ForeignKey(StaffDuty, on_delete=models.CASCADE)
event = models.ForeignKey(Event, on_delete=models.CASCADE)
event_name = models.CharField(max_length=255)
date_appointment = models.DateField(null=True)
morning_hour = models.CharField(max_length=255)
afternoon_hour = models.CharField(max_length=255)
spots_free = models.PositiveIntegerField(null=True)
def __str__(self):
return self.event.name | str(self.staff.date_work)
def get_absolute_url(self):
return reverse('home')
views.py
class StaffDutyAddView(CreateView):
model = StaffDuty
form_class = StaffDutyForm
template_name = 'reservation.html'
success_url = reverse_lazy('home')
class UserAppointmentAddView(CreateView):
model = UserAppointment
form_class = UserAppointmentForm
template_name = "reservation.html"
def form_valid(self, form):
form.instance.user = self.request.user.userinformation
# Code incomplete and that not work
form.instance.staff = StaffDuty.objects.filter(user=self.request.user.staffduty).first()
#form.instance.date_appointment = # add date_work from StaffDuty class
form.instance.event = Event.objects.filter(user=self.request.user.event).first()
#form.instance.event_name = # add name of the event from Event class
return super(UserAppointmentAddView, self).form_valid(form)
def get_context_data(self, **kwargs):
kwargs['object_list'] = StaffDuty.objects.order_by('id')
return super(UserAppointmentAddView, self).get_context_data(**kwargs)
html
<div class="container">
{% for appointment in object_list %}
<tbody>
<tr class="inner-box">
<th scope="row">
<div class="event-date">
</div>
</th>
<td>
<div class="event-img">
{% if appointment.id_image %}
<img src="#" alt="">
{% endif %}
<p>{{ appointment.event}}</p>
</div>
</td>
<td>
<div class="event-wrap">
<h3>{{ appointment.get_shift_display }}</h3>
<div class="time">
<span>{{ form.staff }}</span>
<span>{{ form.event }}</span>
<span>{{ form.morning_hour }}</span>
<span>{{ form.afternoon_hour }}</span>
</div>
</div>
</div>
</td>
<td>
<div class="r-no">
<span> {{ appointment.spots_free }}/{{ appointment.event.spots_total }}</span>
</div>
</td>
<td>
<div class="r-no">
<span>{{ appointment.event.venue }}</span>
</div>
</td>
<td>
<div class="primary-btn">
<input type="submit" value="submit" class="btn btn-primary">
</div>
</td>
</tr>
</tbody>
{% endfor %}
P.s (I had to change my code a little to make it shorter and more clear. They may be typo that are not in my original code)
hoping for some guidance around my below problem with displaying reverse lookup field in a template inside formsets.
Maintenance Item Model
class Maintenance_Item(CommonInfo):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100, unique=True)
name_description = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.name
Checklist Model
class MaintenanceCheckList(CommonInfo):
CHOICES = (
('P','Compliant'),
('F','Non-Compliant'),
)
id = models.AutoField(primary_key=True)
item = models.ForeignKey(Maintenance_Item, on_delete=PROTECT, related_name='item_name')
is_compliant = models.CharField(max_length=20, choices= CHOICES, default=CHOICES[0][0])
def __int__(self):
return self.item
EDIT Form
class MaintenanceCheckListComplianceForm(forms.ModelForm):
is_compliant = forms.ChoiceField(
choices=MaintenanceCheckList.CHOICES,
widget=forms.RadioSelect,
required=False,
)
class Meta:
model = MaintenanceCheckList
fields = ('item','is_compliant',)
END EDIT
The current template
<form class="" method='post'>
{% csrf_token %}
{{ form.management_form }}
<table class="table my-0" id="dataTable">
<thead>
<tr>
<th>Maintenance Items</th>
</tr>
</thead>
<tbody>
{% for sub_form in form %}
<tr>
{% for i in sub_form.item_name.all %}
<td>Item: {{ i.name }}</p>
{% endfor %}
{{ sub_form.item|add_class:"form-select" }}<p>
</p>{{ sub_form.is_compliant }}</td>
</tr>
{% endfor %}
</table>
<div class="divider"></div>
<div class="col-md-12">
<p class='pt-sm-2'>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Currently, I have generic formset view which creates an row for each item in the Maintenance_Item which works brilliant and generates the formset view as shown.
The challenge, I have is I want to hide the ModelChoice fields (I can do that easily with a Widget), and just display the friendly name in the ModelChoice field as a simple Text Label in the template.
Note setting disabled won't work because POST ignores disabled fields (already troubleshooted using that)
I created a system and in this system, there are several users and customers. What I want to create an assign function. A customer should assign to a user.
For example, I have a customer list. When the user clicks a button, the user will see a list that other users and select one of them. After that, the customer's name will be listed in the different assigned customers list of the selected user.
I wrote a code and this is working, but I cannot reach user from customer list. What I mean is when I click assign button it create a new customer. How can I reach user id or username?
views.py
def customer_list(request):
current_user = request.user
userP = UserProfile.objects.get_or_create(username=current_user)
customer_list = Customer.objects.filter(company=userP[0].company.comp_name)
# Assign
form = AssignForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('user:customer_list')
myFilter = TableFilter(request.GET, queryset=customer_list.all())
context = {
'customer_list': customer_list,
'myFilter': myFilter,
'form': form
}
return render(request, 'customer_list.html', context)
models.py
class Customer(models.Model):
customer_name = models.CharField(max_length=20)
country = models.CharField(max_length=20)
address = models.CharField(max_length=100)
VATnumber = models.CharField(max_length=10)
telephone = models.CharField(max_length=10)
email = models.CharField(max_length=30)
contact_person = models.CharField(max_length=30)
company = models.CharField(max_length=20)
id = models.AutoField(primary_key=True)
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, blank=True, null=True)
class UserProfile(AbstractUser, UserMixin):
company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True, unique=False)
user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True)
username = models.CharField(max_length=500, unique=True)
first_name = models.CharField(max_length=200)
customer_list.py
<table id="multi-filter-select" class="display table table-striped table-hover grid_" >
<thead>
<tr>
<th>Customer Name</th>
<th>Country</th>
<th>E-Mail</th>
<th>Phone</th>
<th>VAT Number</th>
<th>Operations</th>
</tr>
</thead>
<tbody>
{% for customer in customer_list %}
<tr>
<td>{{customer.customer_name}}</td>
<td>{{customer.country}}</td>
<td>{{customer.email}}</td>
<td>{{customer.telephone}}</td>
<td>{{customer.VATnumber}}</td>
<td>
<div class="row">
<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#demo{{ forloop.counter }}">Assign</button>
<div id="demo{{ forloop.counter }}" class="collapse">
{% if customer.user == null %}
<form method="post">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-success ">Assign</button>
</form>
{% else %}
Assigned to {{ customer.user.first_name }} {{ customer.user.last_name }}
{% endif %}
</div>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
forms.py
class AssignForm(forms.ModelForm):
class Meta:
model = Customer
fields = ('user',)
views.py
def customer_list(request):
current_user = request.user
userP = UserProfile.objects.get_or_create(username=current_user)
customer_list = Customer.objects.filter(company=userP[0].company.comp_name)
# Assign
form = AssignForm(request.POST or None)
if request.POST:
customer_id = request.POST.get('customer_id', None)
customer = Customer.objects.get(id=customer_id)
user = UserProfile.objects.get(id=request.POST.get('user', None))
customer.user = user
customer.save()
form.save()
return redirect('user:customer_list')
context = {
'customer_list': customer_list,
'form': form
}
return render(request, 'customer_list.html', context)
customer_list.html
...
<button type="button" class="btn btn-success" data-toggle="collapse" data-target="#demo{{ forloop.counter }}">Assigned</button>
...
<form method="post">
{% csrf_token %}
{{ form|crispy }}
<input type="hidden" name="customer_id" value="{{ customer.id }}">
<button type="submit" class="btn btn-success ">Assign</button>
</form>
I am trying to insert my product by category in django.I have two model Product and Category.I want to add Product in Product table.when i add product category comes in select box and select category .Category id in category value. which is insert in product table.Category is ForeignKey. But show this erroer: Cannot assign "'1'": "Product.p_c_name" must be a "Category" instance. 1 is the value of category id.
model.py:
from django.db import models
from django import forms
# Create your models here.
class Category(models.Model):
c_name = models.CharField(max_length=50)
def _str_(self):
return self.c_name
class Product(models.Model):
p_name = models.CharField(max_length=255)
p_desc = models.TextField()
p_price = models.CharField(max_length=255)
p_date=models.DateTimeField(auto_now_add=True)
status = models.BooleanField()
p_c_name = models.ForeignKey(Category, on_delete=True)
image = models.ImageField()
def __str__(self):
return self.p_name
my view.py:
# Product Start form here
def product_add(request):
print(request.POST)
cats = Category.objects.all()
if request.method == 'POST' and request.FILES['image']:
p_name = request.POST['p_name']
p_desc = request.POST['p_desc']
p_price = request.POST['p_price']
p_c_name = request.POST['p_c_name']
status = 0
myfile = request.FILES['image']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
data = Product(p_name=p_name,image=filename,p_desc=p_desc,p_price=p_price,p_c_name=p_c_name,status=status)
data.save()
return redirect('/product/product-list',{
'uploaded_file_url': uploaded_file_url
})
else:
return render(request,'product/add.html',{'cats':cats})
my form.html:
<form class="text-center border border-light p-5" method="POST" action=""enctype="multipart/form-data">
{% csrf_token %}
<!-- Name -->
<input type="text" id="defaultContactFormName" class="form-control mb-4"name="p_name" placeholder="Product Name">
<input type="text" id="defaultContactFormName" class="form-control mb-4"name="p_price" placeholder="Product Price">
<textarea class="form-control mb-4" name="p_desc"id="exampleFormControlTextarea5" rows="3"placeholder="Product Description"></textarea>
<select class="form-control mb-4"name="p_c_name">
<option selected disabled>Select Category</option>
{% for cat in cats %}
<option value="{{cat.id}}">{{cat.c_name}}</option>
{% endfor %}
</select>
<input type="file" id="defaultContactFormName" class="form-control mb-4"name="image">
<!-- Send button -->
<button class="btn btn-info btn-block" type="submit">Save</button>
</form>
Before you create the Product you need to get the Category object since it's a ForeignKey relationship.
category = Category.objects.get(id=p_c_name)
# in your case p_c_name is the category id
data = Product(
p_name=p_name,
image=filename,
p_desc=p_desc,
p_price=p_price,
p_c_name=category,
status=status
)
it's because you need to instantiate "Category"
from .models import Product, Category
def product_add(request):
category = get_object_or_404(Category, pk= p_c_name)
data=Product(p_name=p_name,image=filename,p_desc=p_desc,p_price=p_price,
p_c_name_id=category.id,status=status)
data.save()
I am iterating through a queryset in the template using template tags to show the data of existing database entries (i.e. Customer Orders). However, I want to allow users to edit one of these fields (i.e. Delivery Remarks) for each Customer Order.
My approach was to use ModelForm but I cannot iterate the instances for each form as I iterate through the Customer Orders in the template.
I tried to iterate through an instance to a ModelForm but I get stuck because I am unable to pass the instance to a ModelForm in a template when in context(in views.py) it is the entire queryset that is passed to the template, not an instance. Perhaps I am approaching this problem the wrong way.
My code is below and I am thankful for any help you can give:
Models.py
from django.db import models
from products.models import Product
from counters.models import Counter
from promo.models import Promo
from django.contrib.auth.models import User
class Order(models.Model):
order_status = models.ForeignKey('OrderStatus')
products = models.ManyToManyField(Product, through='OrderProductDetails', through_fields=('order','product'), null=True, blank=True)
counter = models.ForeignKey(Counter, null=True, blank=True)
order_type = models.ForeignKey('OrderType')
order_remarks = models.CharField(max_length=1000, null=True, blank=True)
order_date = models.DateTimeField(auto_now_add=True, auto_now=False)
ordered_by = models.ForeignKey(User, null=True, blank=True)
promo = models.ForeignKey('promo.Promo', verbose_name="Order for which Promotion (if applicable)", null=True, blank=True)
delivery_date = models.DateField(blank=True, null=True)
delivery_remarks = models.CharField(max_length=1000, null=True, blank=True)
updated_on = models.DateTimeField(auto_now_add=False, auto_now=True)
class Meta:
verbose_name = "Order"
verbose_name_plural = "*Orders*"
def __unicode__(self):
return str(self.id)
class OrderProductDetails(models.Model):
order = models.ForeignKey('Order')
product = models.ForeignKey('products.Product')
quantity = models.PositiveIntegerField()
selling_price = models.DecimalField(decimal_places=2, max_digits=10)
order_product_remarks = models.ForeignKey('OrderProductRemarks',blank=True, null=True)
class Meta:
verbose_name_plural = "Order - Product Details"
verbose_name = "Order - Product Details"
def __unicode__(self):
return str(self.id)
class OrderProductRemarks(models.Model):
order_product_remarks = models.CharField(max_length=240, null=False, blank=False)
class Meta:
verbose_name_plural = "Order Product Remarks"
def __unicode__(self):
return str(self.order_product_remarks)
class OrderStatus(models.Model):
order_status_number = models.PositiveIntegerField(null=False, blank=False)
order_status = models.CharField(max_length=100, null=False, blank=False)
class Meta:
verbose_name_plural = "Order Status"
def __unicode__(self):
return str(self.order_status_number) + ". " + str(self.order_status)
class OrderType(models.Model):
order_type = models.CharField(max_length=100, null=False, blank=False)
class Meta:
verbose_name_plural = "Order Type"
def __unicode__(self):
return str(self.order_type)
Views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.admin.views.decorators import staff_member_required
from orders.models import Order
from orders.forms import OrderForm, RemarksForm
from products.models import Product
#login_required(login_url='/admin/login/?next=/')
def warehouseOrders(request):
queryset = Order.objects.filter(order_status__order_status_number = 2) #Filter through default queryset manager with filter through FK
form = RemarksForm(request.POST or None)
if form.is_valid():
form.save()
context = {'queryset': queryset, 'form': form}
template = 'warehouse_orders.html'
return render(request, template, context)
Forms.py
from django import forms
from .models import Order
class RemarksForm(forms.ModelForm):
class Meta:
model = Order
fields = ['delivery_remarks']
Template.html
{% extends 'base_frontend.html' %}
{% load crispy_forms_tags %}
{% block head_title %}
({{ queryset|length}}) Warehouse Orders
{% endblock %}
{% block head_styles %}
{% endblock %}
{% block jquery %}
{% endblock %}
{% block content %}
<h1>Orders to Pack</h1>
<br>
{% for item in queryset %}
Order ID: {{ item }}<br>
<b>Order Status: {{ item.order_status }}</b><br>
Counter: {{ item.counter }}<br>
Order Type: {{ item.order_type }}<br>
Order Remarks: {{ item.order_remarks }}<br>
Order Date: {{ item.order_date }}<br>
Sales Rep: {{ item.ordered_by }}<br>
Promo: {{ item.promo }}<br>
Delivery Date: {{ item.delivery_date }}<br>
<table class="table table-striped table-bordered">
<tr>
<th class="bottom-align-th">#</th>
<th class="bottom-align-th">Article No.</th>
<th class="bottom-align-th">Barcode No.</th>
<th class="bottom-align-th">Color</th>
<th class="bottom-align-th">Free Size</th>
<th class="bottom-align-th">3MTH<br>110<br>S</th>
<th class="bottom-align-th">6MTH<br>120<br>M</th>
<th class="bottom-align-th">9MTH<br>130<br>L</th>
<th class="bottom-align-th">------<br>140<br>XL</th>
<th class="bottom-align-th">------<br>150<br>XXL</th>
<th class="bottom-align-th">Unit Price</th>
<th class="bottom-align-th">Total Quantity</th>
<th class="bottom-align-th">Remarks</th>
</tr>
{% for product in item.products.all %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ product.article_number }}</td>
<td>{{ product.barcode }}</td>
<td>{{ product.color }}</td>
<td>{{ product.quantity }}</td>
</tr>
{% endfor %}
</table>
<br>
Delivery Remarks: {{ item.delivery_remarks }}<br>
{% if form %}
<form method="POST" action=""> {% csrf_token %}
{{ form|crispy }}
<input type="submit" value="Save" class="btn btn-default"/>
</form>
{% endif %}
<br>
<button class="btn btn-success btn-lg">Start Packing</button>
<button class="btn btn-primary btn-lg">Finish Packing</button>
<button class="btn btn-danger btn-lg">Send Order to HQ for Changes</button>
{% endfor %}
{% endblock %}
Btw, using Django 1.7.2 here.