im new with Django and Python, and im still confuse about how to prepopulate values from manytomany field related lookup as my question in Prepopulate tabularinline with value from related lookup in manytomany field
here is my model:
class Product(models.Model):
product_name= models.CharField(max_length=50)
price = models.DecimalField(max_digits=10, decimal_places=2, default=Decimal('0.00'))
tax_per_item = models.DecimalField(max_digits=10, null=True, blank=True, decimal_places=2, default=Decimal('0.00'))
discount_per_item = models.DecimalField(max_digits=10, null=True, blank=True, decimal_places=2, default=Decimal('0.00'))
class Order(models.Model):
produks = models.ManyToManyField(Product, verbose_name=u"Kode Produk")
no_customer = models.ForeignKey(Customer, null=True, blank=True, related_name='%(class)s_kode_cust')
def order_view(request):
if 'enter' in request.POST:
#response to tabular.html template
return HttpResponseRedirect('/admin/POS/Pemesanan/inline')
class Foo(models.Model):
product = models.ForeignKey(Product, editable=False)
pemesanan = models.ForeignKey(Order)
quantity = models.IntegerField()
price = models.IntegerField()
discount = models.IntegerField()
tax = models.IntegerField()
and here is my admin:
class PemesananAdmin(admin.ModelAdmin):
fieldsets = (
('Customer in Time (Person)', {
'fields': ('no_customer',),
}),
('Date', {
'fields' : ('date', 'delivery_date',),
}),
('Order Details', {
'fields' : ('produks',),
}),
)
search_fields = ['produks', 'no_customer']
raw_id_fields = ('produks', 'no_customer',)
related_lookup_fields = {
'fk': ['no_customer'],
'm2m': ['produks'],
}
inlines = [
FooInline,
]
class FooInline(admin.TabularInline):
model = Foo
template = 'admin/POS/Pemesanan/inline/tabular.html'
extra = 0
allow_add = True
and here is my change_form override template:
{% extends "admin/change_form.html" %}
{% block after_field_sets %}{{ block.super }}
<form action="" method="post">
<input type="submit" name="enter" value="Enter" />
</form>
{% endblock %}
But, still nobody can tell me how :(. (If you please response to my question on that page). And now, im confusing about 2 problems:
1. I want my submit button in change_form to redirect to change_form too a.k.a in the same page need no refresh page (not to change_list page or the actual submission).
2. How can i get instances of related lookup 'produks' fieldset (manytomany) from submit button so that i can access parent values (Class Product) and prepopulate all to tabularinline (Class Foo or intermediary class)?
FYI, submit button is below all fieldsets.
Anyone help me please :(. Thank you for your kindly responses :).
your problem is, that this
<form action="" method="post">
<input type="submit" name="enter" value="Enter" />
</form>
will just send your submit-button back to your server.
the form-tag needs to sorround every form-element.
just remove: <form action="" method="post"> and </form>
and it may work.
as i understand you correctly you want to display an order (Order) and its items (Foo)?
my naive solution would be:
class Product(models.Model):
...
class Order(models.Model):
products = models.ManyToManyField(Product, through='Item')
class Item(models.Model):
order = models.ForeignKey(Order)
product = models.ForeignKey(Product)
quantity = models.IntegerField()
...
and the admin could be as simple as this:
class ItemInline(admin.TabularInline):
model = Item
class OrderAdmin(admin.ModelAdmin):
inlines = (ItemInline,)
you need to test that, as i cant (actually)
Related
So I'm building a real estate website for school. And one of the requirements is to have CRUD functionality on the front end for admins. But before i knew that i created in the backend admin page, all the fields that need to be filled before a listing can be published.
But now i need to display all of the fields i created on the backend admin page to show on the front end. I've tried writing the code to display it but its not really working. Im only seeing the submit button.
Im new to coding and stack overflow, so please do let me know if you need anything els from me or if ive done something wrong.
these are the fields that should be filled and show up in the front end for realtors to publish, edit and remove a listing:
models.py
class Listing(models.Model):
realtor = models.ForeignKey(Realtor, on_delete=models.DO_NOTHING)
title = models.CharField(max_length=200)
address = models.CharField(max_length=200)
city = models.CharField(max_length=100)
state = models.CharField(max_length=100)
zipcode = models.CharField(max_length=20)
description = models.TextField(blank=True)
price = models.IntegerField()
bedrooms = models.IntegerField()
bathrooms = models.DecimalField(max_digits=2, decimal_places=1)
garage = models.IntegerField(default=0)
sqft = models.IntegerField()
photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/')
photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
is_published = models.BooleanField(default=True)
list_date = models.DateTimeField(default=datetime.now, blank=True)
This is the code that Ive tried writing to display the code above on the front end so it can be edited.
forms.py
from django.forms import ModelForm
from listings.models import Listing
class listingForm():
class Meta:
model = Listing
fields = '__all__'
create_listing.html
{% extends 'base.html' %}
{% block content %}
<form action="" method="POST">
{% csrf_token %}
{{ form }}
<input type="submit" name="submit">
</form>
{% endblock %}
views.py
def createListing(request):
form = listingForm()
context = {'form': form}
return render(request, 'accounts/create_listing.html')
You didn't pass in the context to the render function, the code should look like this:
def createListing(request):
form = listingForm()
context = {'form': form}
return render(request,'accounts/create_listing.html', context)
Also a suggestion for your code is optimising the photos for your Listing model, here is a good material to watch: https://youtu.be/-0nYBqY9i5w
I wanted to consult about a question I have, in my system I want this view to give me the products selected by their primary key that would be id, this is done with the form that is in a toggle window
enter image description here
views.py
def add(request):
cart = get_or_create_cart(request)
productos = Producto.objects.get(pk=request.POST.get('producto_id'))
cart.productos.add(productos)
return render(request, 'carts/add.html', {
'productos': productos
})
Models.py
class Cart(models.Model):
cart_id = models.CharField(max_length=100, null=False, blank=False, unique=True)
user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
productos = models.ManyToManyField(Producto)
subtotal = models.DecimalField(default=0.0, max_digits=8, decimal_places=2)
total = models.DecimalField(default=0.0, max_digits=8, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.cart_id
HTML
{% csrf_token %}
<form action="{% url 'Carts:add' %}" method="post">
<input type="hidden" name="producto_id" value="{{ producto.id }}">
<button type="submit" class="btn btn-warning">Agregar al carrito</button>
</form>
Your request method is GET. In the view, try using request.GET.get(arg) instead of POST.
PS You can set the second argument to empty, which is request.GET.get('arg', None) or request.GET.get('arg', ' '). Also, try to use filter() instead of get().
models.py
here is my model
class Load_post(models.Model):
user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE)
pick_up_station = models.CharField(max_length=150)
destination_station = models.CharField(max_length=150)
sender_name = models.CharField(max_length=150)
phone_number = PhoneNumberField(null=False , blank=False , unique=True)
receiver_name = models.CharField(max_length=150)
sending_item = models.CharField(max_length=150)
weight = models.CharField(max_length=150)
metric_unit = models.CharField(max_length=30, default='SOME STRING')
quantity = models.PositiveIntegerField(default=1)
requested_shiiping_price = models.PositiveIntegerField()
pick_up_time = models.DateField()
drop_time = models.DateField()
paid_by = models.CharField(max_length=150)
created_at = models.DateTimeField(auto_now=True)
published_date = models.DateField(blank=True, null=True)
def __str__(self):
return self.user.username
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
def publish(self):
self.published_date = timezone.now()
self.save()
def get_absolute_url(self):
return reverse('local')
class Meta:
ordering = ["-created_at"]
unique_together = ["sender_name", "receiver_name"]
please check the phone number
forms.py
this is form.py
class Loader_post_form(forms.ModelForm):
phone_number = PhoneNumberField()
metric_unit = forms.ChoiceField(choices=UNIT, required=True)
class Meta:
model = Load_post
fields = ("pick_up_station", "destination_station",
"sender_name", "phone_number", "receiver_name",
"sending_item","image_of_load","weight","metric_unit",
"quantity","requested_shiiping_price","pick_up_time",
"drop_time","paid_by")
views.py
This is my views.py
absolute URL used in models already
class Loader_post_view(CreateView, LoginRequiredMixin):
login_url = 'Driver/login/'
form_class = forms.Loader_post_form
model = Loader_Signup
template_name = "Driver/post.html"
def form_valid(self,form):
form.instance.user = self.request.user
form.save()
return super(Loader_post_view,self).form_valid(form)
post.html
this is html page (template)
{% extends "Driver/base.html" %}
{% block content %}
<h1>create a post</h1>
{% csrf_token %}
{{form}}
<button type="submit">submit</button>
{% endblock content %}
this is html code
how to add it to the database
and I cannot see any error in my forms
thank you
am working on driver and client-side project
From what I see you html template cannot submit the form because you ae missing the <form> tags - if you do not have them hidden in your base.html.
Your html template should be something like this:
{% extends "Driver/base.html" %}
{% block content %}
<h1>create a post</h1>
<form method="POST">
{% csrf_token %}
{{form}}
<button type="submit">submit</button>
</form>
{% endblock content %}
The {{ form }} renders the form with all the inputs but does not create the tags needed for html forms.
In addition there are some other errors in the code you posted.
In your view the model you defined is called Loader_Signup, however the model you posted is Load_post. Either you posted the wrong model or you declared the wrong model in your view.
In your form one field is called image_of_load, however, this field is not part of you model.
In your model you have got a field called phone_number, you are defining a field with the same name in your form. The field in your form has got no connection to your model so take it out.
Unfortunately you are not providing any details about your PhoneNumberField so this cannot be checked.
I am creating a website for users to upload images... here's the form page:
As from the screencap above, I cannot input any tags, I can only choose existing tags
My Question is: What to add to the code so that users can input at most 10 tags when they have to upload an image
models.py
class Image(models.Model):
owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.DO_NOTHING)
tag = models.ManyToManyField(Tag, blank=True, null=True)
title = models.CharField(max_length=100)
photo = models.FileField()
description = models.CharField(max_length=1000)
def __str__(self):
return self.title + '-' + self.description
class Tag(models.Model):
tag_name = models.CharField(max_length=50)
class ImageTag (models.Model):
image = models.ForeignKey(Image, blank=True, null=True, on_delete=models.DO_NOTHING)
tag = models.ForeignKey(Tag, blank=True, null=True, on_delete=models.DO_NOTHING)
urls.py
url(r'image/add/$', views.ImageCreate.as_view(), name='image-add'),
view.py
class ImageCreate (CreateView):
model = Image
fields = ['category', 'title', 'photo', 'description', 'tag']
image_form.html (I have deleted unrelated div)
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'imagebank/form-template.html' %}
<button type="submit" class="btn btn-success">Submit</button>
</form>
Hi Perhaps someone could point me in the right direction, i am learning Django through Tango with Django and i am also following along with the official Django tutorials as well as creating my own Django app for purchase orders.
I need to understand how I can access the Foreign key details of another Model and save it using forms. Basically my app has Orders and Suppliers when creating an order I can get the supplier foreign key options to appear on the form but when I save it I also want to save with the suppier_name into the orders table currently it just saves with the supplier_id, I have searched through many examples of different scenarios but just can't understand it thanks.
view.py
def add_order(request):
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
form.save(commit=True)
return orders(request)
else:
print(form.errors)
else:
form = OrderForm()
context_dict = {'form':form}
return render(
request,
'purchaseorders/add_order.html',
context_dict
)
model.py
# Create your models here.
class Supplier(models.Model):
supplier_code = models.CharField(max_length=10)
supplier_name = models.CharField(
max_length=100,
unique=True
)
supplier_email = models.EmailField(max_length=100)
supplier_website = models.URLField(max_length=100)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.supplier_name)
super(Supplier,self).save(*args, **kwargs)
def __unicode__(self):
return self.supplier_name
def __str__(self):
return self.supplier_name
class Meta:
verbose_name_plural = "Suppliers"
class Order(models.Model):
supplier = models.ForeignKey(Supplier)
po_number = models.IntegerField(default=0)
ordered_by = models.CharField(max_length=50)
order_date = models.DateTimeField()
supplier_name = models.CharField(max_length=50)
net_value = models.DecimalField(
decimal_places=2,
max_digits=10
)
class Meta:
verbose_name_plural = "Orders"
def __unicode__(self):
return self.po_number
forms.py
from django import forms
from PurchaseOrders.models import Supplier, Order
class SupplierForm(forms.ModelForm):
supplier_code = forms.CharField(
max_length=10,
help_text="Please enter a unique code"
)
supplier_name = forms.CharField(
max_length=100,
help_text="Please enter the Suppliers full name"
)
supplier_email = forms.EmailField(
max_length=100,
help_text="Please enter a email address"
)
supplier_website = forms.URLField(
max_length=100,
help_text="Please enter a website"
)
slug = forms.CharField(
widget=forms.HiddenInput(),
required=False
)
# an inline class to provide additional information on the form
class Meta:
# provide an association between the ModelForm and model
model = Supplier
fields = (
'supplier_code', 'supplier_name',
'supplier_email', 'supplier_website'
)
class OrderForm(forms.ModelForm):
#list all form details except the Foreignkey connection
po_number = forms.IntegerField(
help_text="please enter a PO Number"
)
ordered_by = forms.CharField(
max_length=50,
help_text="please enter your name"
)
order_date = forms.DateTimeField(
help_text="please enter a date of order"
)
#supplier_name = forms.ModelChoiceField(
queryset=Supplier.objects.all()
)
net_value = forms.DecimalField(
decimal_places=2,
max_digits=10,
help_text="please enter a net amount"
)
class Meta:
# provide an association between the ModelForm and model
model = Order
html
{% load staticfiles %} <!-- New line -->
<html>
<head>
<title>Purchase Orders</title>
</head>
<body>
<img src="{% static "purchaseorders/images/po_icon.png" %}"
alt="PO icon" />
<h1>Add a Order</h1>
<form id="order_form" method="post"
action="/PurchaseOrders/add_order/{{ supplier }}">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
<ul style="list-style-type:none ">
{% for field in form.visible_fields %}
<li></li>
{{ field.errors }}
{{ field.help_text }}
<li>{{ field }}</li>
{% endfor %}
</ul>
<input type="submit" name="submit" value="Add Order" />
</form>
</body>
</html>
To start with the question as-asked, you could capture this data in the model's save() method:
class Order(models.Model):
[...]
def save(self, *args, **kw):
if self.supplier_id is not None:
self.supplier_name = self.supplier.supplier_name
super(Order, self).save(*args, **kw)
HOWEVER, although there are some cases where the above might be correct (such as if supplier name is expected to change), it is much more typical to simply access a related field through the existing relationship, ex:
myorder.supplier.supplier_name