unable to save Foreign key object to the model.cc - python-3.x

I am trying to save the data from views, My two models are:
models.py
class Customer(models.Model) :
name = models.CharField(max_length=25)
address = models.CharField(max_length=250)
phone_number = models.IntegerField()
email = models.EmailField(max_length=35)
contact_person = models.CharField(max_length=25)
created_date = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
class Product(models.Model):
support = models.CharField(max_length=8, choices=support_choice, null=True)
amc_date = models.DateField(null=True)
amc_product = models.CharField(max_length=500, default="No Products in amc")
warranty_date = models.DateField(null=True)
warranty_product_list = models.CharField(max_length=500, default="No Products in warranty")
product_name = models.CharField(max_length=100, null=True)
serial_number = models.CharField(max_length=50, null=True)
customer = models.ForeignKey(Customer)
def __str__(self):
return self.product_name
i have created a form for the Product:
class ProductForm(forms.ModelForm):
support = forms.ChoiceField(choices=support_choice, required=True,)
amc_date = forms.DateField(required=False, widget=forms.TextInput(attrs={'placeholder': 'ex: 10/25/2006'}))
amc_product = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Products listed in AMC'}))
warranty_date = forms.DateField(required=False, widget=forms.TextInput(attrs={'placeholder': 'ex: 10/25/2006'}))
warranty_product_list = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'Products listed in warranty'}))
product_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'placeholder':'Product model'}))
serial_number = forms.CharField(required=True)
class Meta:
model = Product
fields = ['support', 'amc_date', 'amc_product', 'warranty_date', 'warranty_product_list', 'product_name',
'serial_number']
in my views.py i am trying to save the Foreign key object to the Product database but i am getting an error "Cannot assign "'Sabaree'": "Product.customer" must be a "Customer" instance."
views.py
def product_detail(request):
cust = request.POST.get('customer_name')
obj = Customer.objects.all()
obj1 = obj.filter(name=cust)
print (cust)
if request.method == 'POST':
form = ProductForm(request.POST)
if form.is_valid():
a = form.save(commit=False)
a.customer = cust
form.save()
context = {'obj':obj, 'form':form}
return render(request,"products.html",context)
and my template is:
products.html
{% block content %}
<script type="text/javascript" src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="{% static 'js/product_detail.js' %}"></script>
<div class="container">
<h2>Products</h2>
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
<div class="controls ">
<select class="select form-control" id="id_customer_name" name="customer_name">
{% for i in obj %}
<option id="{{ i.id }}" value="{{ i.name }}">{{ i.name }}{{ i.id }}</option>
{% endfor %}
</select>
</div>
{{ form|crispy }}
<input type="submit" class="btn btn-default " value="Submit">
</form>
</div>
{% endblock %}
I am not sure how to save the data which is assigned as Foreign key in Product table.

Since Customer is foreign key you cannot assign the value you get from POST method. Try either of this
a.customer.name = cust
or you convert it to Customer table object as follows
cust_obj = Customer.objects.get(name=cust) # Assuming cust is unique or do a query to return obj
then while save,
a.customer = cust

Related

Issue displaying question for answer in views.py

I ran into a problem I have questions that are related to items_buy_id , there are also choices that are related to question_id questions
Questions items_buy_id It turns out to connect
And with the choice you will not contact as it should
My models.py
from django.db import models
from datetime import datetime
from phonenumber_field.modelfields import PhoneNumberField
from django_resized import ResizedImageField
from email.policy import default
from django.utils.translation import gettext_lazy
class Items_buy(models.Model):
class Meta:
db_table = 'items_buy'
verbose_name = 'Телефон который покупаем'
verbose_name_plural = 'Телефоны которые покупаем'
image_phone = ResizedImageField(size=[100,100], upload_to='for_sell/',verbose_name='Фотография модели телефона')
model_produkt = models.TextField(max_length=80, verbose_name='Модель продукта ')
text = models.TextField(max_length=500, verbose_name='Текст')
max_prise_iphone = models.FloatField(verbose_name='Максимальная цена telefoha')
image_phone_for_buy_bord = ResizedImageField(size=[100,100],upload_to='for_sell/',verbose_name='Фотография модели телефона ha prodazy')
def __str__(self):
return self.model_produkt
class Question(models.Model):
class Meta:
db_table = 'question'
verbose_name = 'Вопрос к телефону'
verbose_name_plural = 'Вопросы к телефону'
items_buy_id = models.ForeignKey(Items_buy, on_delete=models.RESTRICT)
title = models.CharField(max_length=150,verbose_name='Заголовок вопросa')
question_text =models.TextField(max_length=100, verbose_name='Заголовок вопросa text')
max_prise_qustion = models.FloatField(verbose_name='Максимальная цена')
def __str__(self):
return self.title
class Choice(models.Model):
class Meta:
db_table = 'choice'
verbose_name = 'Выбор ответа'
verbose_name_plural = 'Выбор ответов'
#items_buy_id = models.ForeignKey(Items_buy, on_delete=models.RESTRICT)
question_id = models.ForeignKey(Question, on_delete=models.RESTRICT)
title = models.CharField(max_length=1000, verbose_name='Заголовок выбора')
points = models.FloatField(verbose_name='Цена ответа')
#lock_other = models.BooleanField(default=False, verbose_name='Смотреть другой вариант ответа')
def __str__(self):
return self.title
My urls.py
from django.urls import path, re_path
from . import views
urlpatterns = [
path('',views.home, name ='home'),
path('sell_iphone/', views.sell_iphone, name = 'sell_iphone'),
path('sell_iphone_page/<int:pk>/', views.sell_iphone_page, name= 'sell_iphone_page'),
path("getqestion/<int:pk>/", views.getqestion, name = 'getqestion'),
]
My html
{% load static %}
{% block content %}
<head>
<link rel="stylesheet" href="{% static 'css/qestion.css' %}" type="text/css">
</head>
<body>
{% include 'navbar.html' %}
<div class="bar">
{% for question in test %}
<div class="bar_infor_bar">
<div class="bar_infor_bar_title">{{question.title}} </div>
<div class="wraper_sell_in_line_img_class2_qestion_text">{{question.question_text}}</div>
{% for choiceses in choice %}
<div class="bar_infor_button_nav">
<button class="bar_infor_button">{{choiceses.title}}</button>
</div>
{% endfor %}
</div>
{% endfor %}
</div>
</body>
{% endblock %}
My views.py
from django.shortcuts import render, redirect
from .models import Items_buy, Question, Choice, Answer, Orders
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage
def home(request):
return render(request, 'home.html')
def sell_iphone(request):
limit = request.GET.get('limit')
if limit == None:
limit = 40
limit = int(limit)
iphone = Items_buy.objects.filter()
count = iphone.count()
page = request.GET.get('page')
paginator = Paginator(iphone, 1)
try:
iphone = paginator.page(page)
except PageNotAnInteger:
page = 1
iphone = paginator.page(page)
except EmptyPage:
page = paginator.num_pages
iphone = paginator.page(page)
#pages = list(range(1, (paginator.num_pages + 1)))
iphone = Items_buy.objects.all()
#iphone = iphone[0:limit]
context = {'iphone':iphone, 'count':count, 'paginator':paginator, }
return render(request, 'sell_iphone.html', context)
def sell_iphone_page(request,pk ):
iphones = Items_buy.objects.filter(id=pk)
#question = Question.objects.all()
context = {'iphones':iphones, }
return render(request, 'sell_iphone_page.html', context)
`def getqestion( request, pk):
test = Question.objects.filter(items_buy_id = pk)
choice = Choice.objects.filter(question_id = pk)
context = {'test':test,'choice':choice}
return render(request, 'getqestion.html', context)`
I'm having a problem with the def getqestion function. I linked the question to the product, but the answer to the question didn't work at all
When using select choice = Choice.objects.filter(question_id = pk)
enter image description here
When using select choice = Choice.objects.all()
enter image description here
When using select choice = Choice.objects.filter(id = pk)
enter image description here
And you need 1.test1 to include: da, net, HY TAKOE
And 1.test2 included: 2,1,3
Thanks in advance to anyone who can suggest how to do this!!!
In my case it helped
views.py
class getqestion(generic.DetailView):
model = Items_buy
template_name = 'getqestion.html'
context_object_name = 'testing'
html
<div>
{% for testings in testing.question_set.all %}
<h1>{{testings.titles}}</h1>
<h3>{{testings.question_text}}</h3>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
{% csrf_token %}
<form action="{% url 'vote' testings.id%}" method="post">
{% for choice in testings.choice_set.all %}
<input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{choice.title}}</label>
{% endfor %}
{% endfor %}
</div>
<input type="submit" value="vote">
</form>

Django: get user related field value in HTML to

I am trying to show the related field of the user on the webpage using Django.
I have models:
Models.py
class Companies(models.Model):
company_name = models.TextField()
company_email = models.EmailField()
company_owner = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.company_name
class Cars(models.Model):
company = models.ForeignKey('Companies', on_delete=models.CASCADE)
car_model = models.TextField()
views.py:
class UserCompanyCars(ListView):
model = Cars
template_name = 'home/company_cars.html'
context_object_name = 'cars'
slug_field ="username"
paginate_by = 100
def get_queryset(self):
company_n = get_object_or_404(Companies, company_owner=self.request.user)
return Cars.objects.filter(company=company_n)
and my html is:
{% extends 'home/base.html' %}
{% block content %}
<h1 class="mb-3"> Cars of {{user.Companies.company_name}}</h1>
{% for car in cars %}
<div class="media-body">
<div class = "article-metadata">
<p class="article-content">{{car.company}}</p>
{{car.car_model}}
<p class="article-content">{{car.car_carry }}</p>
</div>
</div>
{% endfor %}
{% endblock content %}
What I am trying to achieve is to write out "Cars of TestCompany (26)" on the webpage, but I cannot figure out how to get the Company_Name which is owned by the user. I have been trying all those Companies.objects... variations but none of them seem to work.
Try this (sample code taken from my project):
category = get_object_or_404(Category, pk=self.kwargs['pk'])
context['allcategories'] = MyPosts.objects.filter(category=category)
return context
This will filter all posts in the database based on certain categories. You can apply the same solution to your code.
If this solution does not work, please try to give more details about the problem.

How can i update with modelformset_factory on Django

I used the modelformset_factory method for multiple photo uploads. But when I want to update the post, I don't know how to do this, I tried something, but this only serves to re-upload photos and upload the uploaded photos again. How can I update or delete a previously uploaded photo? Also, I cannot access the photos in formset as {{formset.image}}. How can I access this?
Views.py
def post_update(request, slug):
post = get_object_or_404(Post, slug=slug)
if not request.user.is_authenticated and not request.user == post.seller or not request.user.is_admin:
raise Http404
ImageFormSet = modelformset_factory(PostImage, form=PostImageForm, extra=5, can_delete = True)
form = PostForm(data=request.POST or None, instance = post, files = request.FILES or None)
formset = ImageFormSet(data=request.POST or None, files= request.FILES or None, queryset=PostImage.objects.filter(post__slug=slug))
if form.is_valid():
if formset.is_valid():
for forms in formset.cleaned_data:
if forms:
image = forms['image']
print(forms['image'])
photo = PostImage(post=post, image=image)
photo.save()
form.save(commit=True)
messages.success(request,"Success")
return HttpResponseRedirect(reverse('gayrimenkul:detail',kwargs={'slug':form.instance.slug}))
return render(request,'post_update.html',{'form':form,'formset':formset,'slug':slug})
post_update.html
{% extends "main_page.html" %}
{% load static %}
{% block icerik %}
{% load crispy_forms_tags %}
<div class="row">
<div class="container">
<h2 class="page_header">İlan Ver</h2>
<hr>
{% if form.errors %}
{{form.errors}}
{% endif %}
<div class="col-md-12">
<form enctype="multipart/form-data" method="POST">
{% csrf_token %}
{{form.media}}
{{form|crispy}}
<div class="row">
<div class="col-md-6">
{{formset}}
</div>
<div class="col-md-6">
<button type="submit" id="inp" class="btn btn-outline-primary" style="float:right;">Kaydet</button>
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
Creating posts works successfully.
def post_create(request):
if not request.user.is_authenticated:
raise Http404
ImageFormSet = modelformset_factory(PostImage, form=PostImageForm, extra=5)
if request.method == 'POST':
post_form = PostForm(request.POST, request.FILES)
formset = ImageFormSet(request.POST, request.FILES, queryset=PostImage.objects.none())
if post_form.is_valid():
created_post = post_form.save(commit=False)
created_post.seller = request.user
created_post.save()
for form in formset.cleaned_data:
if form:
image = form['image']
photo = PostImage(post=created_post, image=image)
photo.save()
messages.success(request,'Success')
return HttpResponseRedirect(reverse('gayrimenkul:detail',kwargs={'slug':created_post.get_slug()}))
else:
post_form = PostForm()
formset = ImageFormSet(queryset = PostImage.objects.none())
return render(request,'post_create.html',{'form':post_form,'formset':formset})
Before checking if the form is valid just filter the model of the formset
data = PostImage.objects.filter(post=post)
Give index of the item for a formset item starting form 0 and (f)the item itself and if the item of the id is not changed than save previous item itself else change the database image with the new image you have updated.
if formset.is_valid():
for index, f in enumerate(formset):
if f.cleaned_data:
if f.cleaned_data['id'] is None:
pic = PostImage(post=post, image=f.cleaned_data.get('image'))
pic.save()
elif f.cleaned.data['image'] is False:
pic = PostImage.objects.get(id = request.POST.get('form-' + str(index) + '-id'))
pic.delete()
else:
pic = PostImage(post=post, image=f.cleaned_data.get('image'))
d = PostImage.objects.get(id=data[index].id) #get slide id which was uploaded
d.image = pic.image # changing the database title with new title
d.save()
This might work for you or get you some idea.

I have a db with table Organisations and another table Sites. How can I use Flask-WTF map new sites created to an organisation

I have a one-to-many relationship created but I am not sure how I can post the organization that has been selected from the dropdown menu with the new site details that have been created.
Basic page layout will be dropdown containing organization names that have already been created and stored in the organization table in the db. End-user selects an organization then types in the new name for a site and clicks submit.
Code is below and any help will be most appreciated.
App.py
#app.route('/add_site')
def add_site():
""" Find and show field from db for the user to fill in """
form = AddSite()
organisations = db.session.query(Organisation)
return render_template('add_site.html', form=form,
organisations=organisations)
#app.route('/insert_site', methods=['GET', 'POST'])
def insert_site():
""" Insert populated fills from add_site to db """
form = AddSite()
site_name = Site(site_name=form.site_name.data)
db.session.add(site_name)
db.session.commit()
return redirect(url_for('get_org'))
forms.py
class AddSite(FlaskForm):
""" Adding new site """
site_name = StringField('Site Name', validators=[DataRequired()])
submit = SubmitField('Add Site')
Models.py
class Organisation(db.Model):
""" Table to store organisation details """
id = db.Column(db.Integer, primary_key=True, index=True,
unique=True)
org_name = db.Column(db.String())
timestamp = db.Column(db.DateTime, index=True,
default=datetime.utcnow)
sites = db.relationship('Site', backref='org_name', lazy='dynamic')
def __init__(self, org_name):
self.org_name = org_name
class Site(db.Model):
""" Table to store site details """
id = db.Column(db.Integer, primary_key=True)
site_name = db.Column(db.String())
timestamp = db.Column(db.DateTime, index=True,
default=datetime.utcnow)
org_id = db.Column(db.Integer, db.ForeignKey('organisation.id'))
def __init__(self, site_name):
self.site_name = site_name
add_site.html
<form action=" {{url_for('insert_site') }}" method="POST" class="col-12">
{{ form.hidden_tag() }}
<div class="col s12">
<select name="organisation_list">
<option value="" disabled selected>Choose an
Organisation</option>
{% for org in organisations %}
<option value ="{{org.org_name}}">{{org.org_name}}</option>
{% endfor %}
</select>
<label>Organisations</label>
</div>
<div class="row">
<div class="col s12">
{{ form.site_name.label }}
{{ form.site_name(size=32) }}
</div>
</div>
<div class="row">
<buttom>
{{ form.submit() }}
</buttom>
</div>
</form>
The end result is to map multiple sites to a organization. This is so I can create a page which will show all the sites that are under an organization.
Try this in your scripts
App.py
from flask import (request, render_template, redirect_url,
url_for)
from app.Models import db, Site # Use proper import here for your app
#app.route('/add_site', methods=['GET', 'POST'])
def add_site():
form = AddSite(request.form)
if request.method == 'POST' and form.validate():
site = Site(
site_name=form.site_name.data,
org_id=form.organisation.data
)
db.session.add(site)
db.session.commit()
return redirect(url_for('get_org'))
return render_template('add_site.html', form=form)
forms.py
from flask_wtf import FlaskForm as Form
from wtforms import (SelectField, StringField, SubmitField)
from wtforms.validators import DataRequired as Required
from app.Models import Organisation # Use proper import here for your app
class AddSite(Form):
""" Adding new site """
site_name = StringField('Site Name',
validators=[Required('Site name is required')])
organisation = SelectField('Organisation', coerce=int,
validators=[
Required('Please select an organisation')])
submit = SubmitField('Add Site')
def __init__(self, *args, **kwargs):
super(AddSite, self).__init__(*args, **kwargs)
organisations = Organisation.query.with_entities(
Organisation.id, Organisation.org_name). \
order_by(Organisation.org_name).all()
self.organisation.choices = [
(organisation.id, organisation.org_name)
for organisation in organisations
]
Models.py
class Organisation(db.Model):
""" Table to store organisation details """
__tablename__ = 'organisation'
id = db.Column(db.Integer, primary_key=True)
org_name = db.Column(db.String(100))
timestamp = db.Column(db.DateTime, index=True,
default=datetime.utcnow)
sites = db.relationship('Site', backref='organisation', lazy='dynamic')
def __repr__(self):
return '<Organisation: {!r}'.format(self.org_name)
class Site(db.Model):
""" Table to store site details """
__tablename__ = 'site'
id = db.Column(db.Integer, primary_key=True)
site_name = db.Column(db.String())
timestamp = db.Column(db.DateTime, index=True,
default=datetime.utcnow)
org_id = db.Column(db.Integer, db.ForeignKey('organisation.id'))
def __repr__(self):
return '<Site: {!r}'.format(self.site_name)
add_site.html
<form action=" {{url_for('add_site') }}" method="POST">
<div class="form-group{% if form.site_name.errors %} has-error{% endif %}">
{{ form.site_name.label(for_='site_name') }}
{{ form.site_name(class='form-control') }}
{% if form.site_name.errors %}
<span class="help-block">{{ form.site_name.errors[0] }}</span>
{% endif %}
</div>
<div class="form-group{% if form.organisation.errors %} has-error{% endif %}">
{{ form.organisation.label }}
{{ form.organisation(class='form-control') }}
</div>
{{ form.csrf_token }}
{{ form.submit(class='btn btn-default', value='Add Site') }}
</form>

Django Viewflow using class based views but getting error : Reverse for 'index' not found. 'index' is not a valid view function or pattern name

I am using class based views for my Django viewflow project. However I am getting the below error:
Reverse for 'index' not found. 'index' is not a valid view function or pattern name
Here are my classes:
rules/flows.py
class MyFlow(Flow):
"""
My App Flow
"""
process_class = models.MyProcess
start = flow.Start(
views.MyDetailView,
fields=["rule"],
task_title="New Task"
).Permission(
auto_create=True
).Next(this.end)
end = flow.End()
rules/urls.py
rule_urls = FlowViewSet(MyFlow).urls
urlpatterns = [
url(r'^rule/', include(rule_urls, namespace='rule')),
url(r'^(?P<pk>\d+)/mydetail/', MyDetailView.as_view(), {'flow_class': MyFlow, 'flow_task': MyFlow.start}, name='mydetail')
]
rules/models.py
class SubRules(models.Model):
rule_id = models.AutoField(primary_key=True)
src_id = models.IntegerField()
src_description = models.CharField(max_length=160, blank=True)
class Meta:
db_table = 'sub_rules'
class EntRules(models.Model):
rule = models.OneToOneField(SubRules, primary_key=True, on_delete=models.CASCADE)
entitlement_code = models.IntegerField()
rule_approved = models.SmallIntegerField()
rule_approved_datetime = models.DateTimeField(null=True)
class Meta:
db_table = 'ent_rules'
class MyProcess(Process):
entrule = models.ForeignKey(EntRules, blank=True, null=True, on_delete=models.CASCADE)
class Meta:
permissions = (
('approve_ent_rules','Can approve ent_rules')
)
rules/forms.py
class MyDetailForm(forms.ModelForm):
class Meta:
model = EntRules
fields = [
'rule',
'entitlement_code',
]
def __init__(self, *args, **kwargs):
pk = kwargs.pop('rule_id', None)
super(MyDetailForm, self).__init__(*args, **kwargs)
sub_rule = SubRules.objects.get(rule_id=pk)
self.fields['rule'].queryset = sub_rule.objects.filter(rule_id=pk)
rules/views/my_detail.py
class MyDetailView(StartFlowMixin, generic.UpdateView):
model = EntRules
template_name = 'rules/my_detail.html'
form_class = MyDetailForm
layout = Layout(
Fieldset('Rule Details',
Row('rule',),
Row('entitlement_code',),
)
)
def activation_done(self, form):
ent_rule = form.save()
self.activation.process.entrule = ent_rule
super(MyDetailView, self).activation_done(form)
def get_object(self):
return self.activation.process.entrule
def get_form_kwargs(self):
kwargs = super(MyDetailView, self).get_form_kwargs()
pk = int(self.kwargs['pk'])
kwargs['rule_id'] = pk
return kwargs
rules/templates/rules/my_detail.html
{% extends "base.html" %}
{% load material_form %}
{% block content %}
<form method="POST">
{% csrf_token %}
<div class="row">
{% form form=form %} {% endform %}
{{ activation.management_form }}
<div class="right">
<button type="submit" name="_start" class="btn">Submit</button>
</div>
</div>
</form>
{% endblock %}
Can you please advise what could be the issue here ?
I looked at Process Views outside viewflow.frontend
However how do I pass the sub_rule pk "^(?P\d+)" to startview as given in the URL like below ?
class MyFlow(Flow):
start = flow.Start(detail_view_class=MyDetailTaskView)
Please advise.
You can just pass a custom detail view as an argument for flow.Start http://docs.viewflow.io/viewflow_flow_nodes.html#viewflow.flow.StartFunction.detail_view

Resources