I am trying to save data that fill out with form to database but it doesn't work as well. when i click on Submit button nothing change, the webpage just refresh!
These are my codes.
Views.py
class HotelAdCreate(AuthorsAccessMixin,CreateView):
model = HotelBookingAd
form_class = HotelBookingAdForm
template_name = "account/article-create-update.html"
def form_valid(self,form):
form.save()
return super(HotelAdCreate).form_valid(form)
Forms.py
class HotelBookingAdForm(forms.ModelForm):
class Meta:
model = HotelBookingAd
fields = '__all__'
def clean_sales_price(self):
sales_price = self.cleaned_data["sales_price"]
purchase_price = self.cleaned_data["purchase_price"]
if sales_price > purchase_price:
raise forms.ValidationError("error.")
print("error")
return sales_price
Edit :
i just added template file codes to debaug clearly.
Template File
{% extends 'account/base.html' %}
{% load crispy_forms_tags %}
{% block title %}{% endblock %}
{% block title-meta %} آگهی{% endblock %}
{% block main %}
<div class="col-md-12">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title- mb-0">ایجاد آگهی </h3>
</div>
<div class="card-body">
<form method="post" enctype="multipart/form-data">{% csrf_token %}
<div class="row">
<div class="col-6">
{{form.title|as_crispy_field}}
</div>
<div class="col-6">
{{form.hotel_name|as_crispy_field}}
</div>
<div class="col-12">
{{form.sale_reason|as_crispy_field}}
</div>
<div class="col-6">
{{form.check_in_date|as_crispy_field}}
</div>
<div class="col-6">
{{form.check_out_date|as_crispy_field}}
</div>
<div class="col-6">
{{form.purchase_price|as_crispy_field}}
</div>
<div class="col-6">
{{form.sales_price|as_crispy_field}}
</div>
<div class="col-6">
{{form.city_name|as_crispy_field}}
</div>
<div class="col-6">
{{form.room_type|as_crispy_field}}
</div>
<div class="col-6">
{{form.confirm|as_crispy_field}}
</div>
{% if user.is_superuser %}
<div class="col-6">
{{form.slug_generator|as_crispy_field}}
</div>
{% endif %}
</div>
<button class="btn btn-success">ارسال مقاله</button>
{% if user.is_superuser and request.resolver_match.kwargs.pk %}
<a class="btn btn-danger "href="{% url 'account:hotelad-delete' request.resolver_match.kwargs.pk %}">
حذف مقاله
</a>
<a target="_blank" class="btn btn-dark "href="{% url 'primary:preview' request.resolver_match.kwargs.pk %}">
پیش نمایش
</a>
{% endif %}
</form>
</div>
</div>
</div>
{% endblock %}
I've tried different options, but I don't have enough skills to handle this problem.
Can anyone help me?
UPDATE (FIXED)
I found problem by my self, here it is :
As you see in forms.py, i am using __all__ for fields but in template i am not using all the fields, so form will not be valid.
To fix the bug completely i just added Exclude option and added the fields that i didn't use in template. finally everything works fine :)
Related
I am new here so I may have worded the title wrong I apologize if I did so.
So I created a checkout page in my django project for the user to purchase coins but it wont render the variable attribute on the browser it just shows up empty.
Here's the coinpack model.py code.
`
class Coinpack (models.Model):
amount= models.CharField(max_length=50)
price= models.FloatField()
image_url= models.CharField(max_length=3000)
`
Here's the coinpack views.py code.
`
def buycoins (request):
buycoins = Coinpack.objects.all
return render(request, 'buycoins.html', {'buycoins': buycoins})
`
Here's the html template code
`
{% extends 'base.html' %}
{% block content %}
<div class="row">
{% for Coinpack in buycoins %}
<div class="col">
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">{{ Coinpack.amount }} coins</h5>
<p class="card-text"> ${{ Coinpack.price}}</p>
Buy Now
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
`
After this the coipack page works well
but when I add the checkout page the attributes are not rendered, here's what I did.
checkout page views.py
`
def checkout(request, pk):
checkout = Coinpack.objects.get(id=pk)
context = {'checkout':checkout}
return render(request, 'checkout.html', context)
`
checkout page url.py
`
path('checkout/<int:pk>/', views.checkout, name="checkout"),
`
checkout page html template
`
<body>
<div class="container">
<div class="row">
<div class="col-lg">
<br>
<img src="{{Coinpack.image_url}}">
</div>
<div class="col-lg">
<br>
<div class="card card-body">
<h3> {{coinpack.amount}} </h3>
<hr>
<h4>Total: $ {{Coinpack.price}} </h4>
<hr>
</div
</div>
</div>
</div>
</body>
`
This is the result in the browser
So I have no idea why it ends up empty pls help, thank you.
You used the different variables in the template. Try this,
<body>
<div class="container">
<div class="row">
<div class="col-lg">
<br>
<img src="{{checkout.image_url}}">
</div>
<div class="col-lg">
<br>
<div class="card card-body">
<h3> {{checkout.amount}} </h3>
<hr>
<h4>Total: $ {{checkout.price}} </h4>
<hr>
</div
</div>
</div>
</div>
</body>
I have implemented search bar functionality with autocomplete feature. All is good except the fact that in HTML serach results contain multiple the same object. For instance, when I put 2 in my searchbar I see 4 the same in my HTML file. What I want is to get unique objects.
views.py
#login_required
def search_address_qa(request):
query = request.GET.get('title')
payload = []
if query:
lookups = Q(title__icontains=query)
address_objects = Article.objects.filter(lookups)
address_objects_qa = QA.objects.filter(lookups)
for address_object in address_objects or address_objects_qa:
payload.append(address_object.title)
return JsonResponse({'status':200, 'data': payload})
#login_required
def search_articles(request):
query = request.GET.get('q')
article = Article.objects.filter(title__icontains=query)
qa_list = QA.objects.filter(title__icontains=query)
if query is not None:
lookups = Q(title__icontains=query) | Q(tags__name__icontains=query)
article = Article.objects.filter(lookups)
qa_list = QA.objects.filter(lookups)
context = {
'search_articles': article,
'query_name': query,
'qa_list': qa_list
}
return render(request, 'search/search_articles.html', context)
search_view.html
{% extends 'base.html' %}
<title>{% block title %}search results{% endblock %}</title>
{% block search %}
{% include 'main/sidebar.html'%}
<link rel="stylesheet" type="text/css" href="/static/search.css">
<div class="d-flex justify-content-end h-100 pb-4">
<div>
{% if user.is_authenticated %}
<form action="{% url 'search_articles' %}" method="get" id="search">
{% csrf_token %}
<div class="searchbar " id="autocomplete">
<input name="q" type="text" placeholder="Search articles" class="search_input">
<i class="fas fa-search"></i>
<ul class="autocomplete-result-list"></ul>
</div>
</form>
{% endif %}</div>
</div>
{% endblock search %}
{% block content %}
<div class="d-flex justify-content-start pb-4">Search results for my question: <div class="ml-1 fw-bold"> {{ query_name }} </div></div>
<div class="container-fluid pb-4">
<h4>Articles</h4>
<hr>
<div class="row row-flex row-cols-1 row-cols-md-3 g-4">
{% for article in search_articles %}
<div class="col-lg-3 d-flex align-items-stretch">
<a href="{{ article.get_absolute_url }}">
<div class="card h-100 shadow text-left">
<h5 class="card-header">{{article.title}}</h5>
<img src="/static/preview_homepage3.png" class="card-img-top">
<div class="card-body">
<h5 class="card-title">{{ article.slug }}</h5>
<p class="card-text">
{% comment %} {% lorem 10 w %} {% endcomment %}
{{article.body | safe | truncatechars:75}}
</p>
</a><br>
{% include 'main/tag_cards.html' %}
</div>
<div class="card-footer">
<small class="text-muted">{{ article.publish|date:"d F Y" }}</small>
</div>
</div>
</div>
{% empty %}
<div class="container d-flex justify-content-center">No results</div>
{% endfor %}
</div>
</div>
<h4>Related questions</h4>
<hr>
<div class="container h-100 py-2 mb-4">
{% for qa in qa_list %}
<div class="card text-dark bg-light mb-3 text-left">
<a href="{{ qa.get_absolute_url }}">
<h5 class="card-header">Q: {{qa.title}}</h5>
<div class="card-body">
<div class="card-title text-justify">A: {{ qa.answer |safe | striptags }}</div>
{% comment %} <p class="card-text"> {{ qa.author }}</p> {% endcomment %}
</div>
<div class="card-footer">
<small class="text-muted">Published: {{qa.publish}}</small>
</div>
</a>
</div>
{% empty %}
<p>No results</p>
{% endfor %}
{% endblock %}
You can make use of Django's distinct() QuerySet method
.disctinct() Returns a new QuerySet that uses SELECT DISTINCT in its SQL query. This eliminates duplicate rows from the query results.
Change
article = Article.objects.filter(lookups)
to
article = Article.objects.filter(lookups).distinct()
Why does it happen?
In your case, this happens because you are using the Q object,
lookups = Q(title__icontains=query) | Q(tags__name__icontains=query)
suppose your search text is "test" and you have a row in the table with title="text" and tag_name="text", then the lookup will match both title and tag which leads to generating duplicate rows (since you are performing an OR operation in your lookkups) with the same result.
I am creating a printing ordering service website in Django and I am stuck on the order page.
I have three tables named "product" ,"size", and "sizeProductMap" table.
views.py
products = Product.objects.get(prod_ID=id)
print(products.prod_Name)
sizesmap = SizeProductMapping.objects.filter(prod_id=id)
sizeslist = []
for data in sizesmap:
sizes = data.size_id
sizeslist.append(sizes.prod_size) # Here I am getting all the sizes I needed.
print(sizes.prod_size)
return render(request, "GalaxyOffset/product.html", {'products': products, 'sizeslist': sizeslist})
product.html
{% extends 'GalaxyOffset\basic.html' %}
{% block title%}Products{% endblock %}
{% block body%}
<div class="card my-2 mx-0 auto">
<div class="mx-4 my-2">
<h1>{{ products.prod_Name }}</h1>
</div>
<div class="row">
<div class="col-3">
<img class="border border-secondary my-4 mx-4" height="200"
src="{{products.prod_img.url}}"
width="200"/>
</div>
<div class="col-8 my-4">
<p> {{products.prod_Desc}}</p>
</div>
<div class="dropdown-divider"></div>
</div>
</div>
<div class="row">
<div class="col-4">
<div class="card mx-2 my-2 border border-secondary">
<div class="mx-2 mt-4">
{% for category in categories %}
<a id="{{ category.prod_ID }}" class="dropdown-item" href="{% url 'product' category.prod_ID%}">
{{ category.prod_ID }}. {{ category.prod_Name }}</a>
<div class="dropdown-divider"></div>
{% endfor %}
</div>
</div>
</div>
<div class="col-8">
<div class="card mx-2 my-2">
<div class="my-2">
<!-- How can I reduce Number of Line of code here. -->
{% for s in sizeslist %}
<input type="radio" name="sizes">{{s}}
</br>
{% endfor %}
</div>
</div>
</div>
</div>
{% endblock %}
Can you help me here to reduce the Numer of Lines in my views.py for fetching sizes and displaying in product.html?
You can use a list comprehension here.
sizesmap = SizeProductMapping.objects.filter(prod_id=id)
sizeslist = [data.size_id.prod_size for data in sizesmap]
or use .values()
Ex:
sizeslist = SizeProductMapping.objects.filter(prod_id=id).values('size_id__prod_size')
I am new to Python and Django, and I have just created a website.
Basically I would like to have a page on the website that displays our company partners.
I have created an app 'partners' and in the model, I have 'website' as one of the fields.
On the partners html file, I have a button that users can click and this will take them to the partner's website in a new tab.
I tried to link the website in the following way:
{{ partner.website }}
However this ends up like:
www.mydomain.com/partners/www.partnerwebsite.com
I just want the partner website (www.partnerwebsite.com) to open in a new tab.
Any help appreciated. If there is already another post on this, please redirect me.
views.py
from django.shortcuts import render, redirect
from .models import Partner
def index(request):
partners = Partner.objects.order_by('-date_added').filter(is_published=True)
context = {
'partners': partners,
}
return render(request, 'partners/partners.html', context)
models.py
from django.db import models
from datetime import datetime
class Partner(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
website = models.CharField(max_length=100)
email = models.CharField(max_length=200)
contact_person = models.CharField(max_length=200)
phone = models.CharField(max_length=100)
mobile = models.CharField(max_length=100)
address = models.CharField(max_length=200)
photo_main = models.ImageField(upload_to='photos/partners/%Y/%m/%d/')
promo_code = models.CharField(max_length=20, blank=True)
is_published = models.BooleanField(default=True)
date_added = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.name
partners.html
{% extends 'base.html' %}
{% block title %} | Partners {% endblock %}
{% block content %}
<section id="showcase-inner" class="py-5 text-white">
<div class="container">
<div class="row text-center">
<div class="col-md-12">
<h1 class="display-4">Partners</h1>
</div>
</div>
</div>
</section>
<!-- Breadcrumb -->
<section id="bc" class="mt-3">
<div class="container">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="{% url 'index' %}">
<i class="fas fa-home"></i> Home</a>
</li>
<li class="breadcrumb-item active"> Partners</li>
</ol>
</nav>
</div>
</section>
<!-- Partners -->
<section id="partners" class="py-4">
<div class="container">
<div class="row">
{% if partners %}
{% for partner in partners %}
<!-- Partner 1 -->
<div class="col-md-6 col-lg-6 mb-4">
<div class="card listing-preview">
<img class="card-img-top-project" src="{{ partner.photo_main.url }}" alt="">
<div class="card-body">
<div class="listing-heading text-center">
<h4 class="text-primary">{{ partner.name | title }}</h4>
<p><i class="fas fa-map-marker text-secondary"></i> {{ partner.address }}</p>
</div>
<hr>
<div class="row py-2 text-secondary">
<div class="col-12 text-center">
{{ partner.description }}
</div>
</div>
{% if partner.promo_code %}
<hr>
<div class="row py-2 text">
<div class="col-12 text-center">
Use the following code to obtain 10% discount: {{ partner.promo_code }}
</div>
</div>
{% endif %}
<div class="container">
<hr>
<button class="btn btn-secondary btn-block">Visit Website</button>
</div>
</div>
</div>
</div>
{% endfor %}
{% else %}
<div class="container">
<p><h5 class="text-center">No Partners Available</h5></p>
</div>
{% endif %}
</div>
</div>
</section>
{% endblock %}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.index, name='partners'),
]
I was able to deduce the below solution from your views file. Add the below code in your template "partners.html"
{% for value in partners %}
<button>my button </button>
{% endfor%}
Im tries to open in Django the user edit form in Bootstrap modal. But the form is empty, only the save button is shown. But I don't understand how I can make the connection. If I call the edit page directly, then I can edit the user
127.0.0.1:8000/account/edit/
index.html, includes the referral to the form
{% extends 'base.html' %}
{% block head %}
{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-6">
<div class="panel panel-default">
<div class="panel-body">
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form action="{% url 'account:edit_profile' %}">
<input type="submit" value="Edit" />
</form>
<form action="{% url 'account:change_password' %}">
<input type="submit" value="Change Login" />
</form>
<br>
Open Modal
<br>
<div class="control-label col-sm-2">
First name:
</div>
<div class="col-sm-2">
{{ user.first_name }}
</div><br>
<div class="control-label col-sm-2">
Last name:
</div>
<div class="col-sm-2">
{{ user.last_name }}
</div><br>
<div class="control-label col-sm-2">
Email:
</div>
<div class="col-sm-2">
{{ user.email }}
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="edit-profile-modal" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" align="center">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
</div>
<div id="div-forms">
{% include "account/edit_profile.html" with form=form %}
</div>
</div>
</div>
</div>
{% endblock %}
edit_profile.html
{% block head %}
{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-6">
<div class="panel panel-default">
<div class="panel-body">
<h3>Profile</h3>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form method="post">
{% csrf_token %}
{{ user_form.as_p }}
<button type="submit">Save</button>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
views.py
def edit_profile(request):
if request.method == 'POST':
user_form = EditUserForm(request.POST, instance=request.user)
if all([user_form.is_valid(), profile_form.is_valid()]):
user_form.save()
return render(request, 'account/index.html')
else:
user_form = EditUserForm(instance=request.user)
args = {'user_form': user_form}
return render(request, 'account/edit_profile.html', args)
urls.py
urlpatterns = [
...
url(r'^edit/$', views.edit_profile, name='edit_profile'),
...
]
forms.py
class EditUserForm(forms.ModelForm):
class Meta:
model = User
fields = (
'email',
'first_name',
'last_name'
)
Im using:
Python 3.6.3
Django 2.0.7
Windows 8.1
Bootstrap 3.3.6
JQuery 1.12.0
I think that variable form doesn't exist and you use in template just user_form not form variable
{% include "account/edit_profile.html" with form=form %}
Try use it:
{% include "account/edit_profile.html" with user_form=user_form %}
Maybe you could try the code I wrote and you can find it at django-bootstrap-modal-forms. You will be able to bind your form to the modal and all of the validation stuff will work out of the box.
You will create a trigger element opening the modal
Your selected form will be appended to the opened modal
On submit the form will be POSTed via AJAX request to form's URL
Unsuccessful POST request will return errors, which will be shown under form fields in modal
Successful POST request will redirects to selected success URL