Django: AttributeError 'WSGIRequest' object has no attribute 'get' - django

I am trying to add a set of inline forms, but when I try to save the information of the forms it throws me this error
views.py
The intention is to create more orders for a particular client, for that reason I focus on the "createOrder" function to achieve it.
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from django.forms import inlineformset_factory
from .forms import OrderForm, CustomerForm
# Create your views here.
def home(request):
orders_value = Order.objects.all()
customer_value = Customer.objects.all()
total_orders_value = orders_value.count()
total_customers_value = customer_value.count()
pending_value = orders_value.filter(status='Pending').count()
delivered_value = orders_value.filter(status='Delivered').count()
context = {'orders_key': orders_value, 'customer_key': customer_value,
'total_orders_key':total_orders_value, 'pending_key': pending_value,
'delivered_key': delivered_value}
return render (request, 'accounts/dashboard.html', context)
def products(request):
products_value = Product.objects.all()
return render (request, 'accounts/products.html', {'products_key': products_value})
def customer(request, pk_test):
customer_value = Customer.objects.get(id=pk_test)
orders_value = customer_value.order_set.all()
orders_value_count = orders_value.count()
context = {'customer_key':customer_value, 'orders_key': orders_value, 'orders_key_count': orders_value_count}
return render (request, 'accounts/customer.html', context)
def createOrder(request, pk):
OrderFormSet= inlineformset_factory(Customer, Order, fields=('product', 'status'))
customer = Customer.objects.get(id=pk)
form_set_value= OrderFormSet(instance=customer)
if request.method == 'POST':
form_set_value= OrderFormSet(request, instance=customer)
if form_set_value.is_valid:
form_set_value.save()
return redirect('/')
context = {'form_set_key':form_set_value}
return render(request, 'accounts/order_form.html', context)
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<form action="" method="POST">
{% csrf_token %}
{{ form_set_key.management_form }}
{% for form in form_set_key %}
{{form}}
<hr>
{% endfor %}
<input type="submit" name="Submit">
</form>
{% endblock %}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name="products"),
path('customer/<int:pk_test>/', views.customer, name="customer"),
path('create_order/<int:pk>', views.createOrder, name='create_order'),
path('update_order/<int:pk>', views.updateOrder, name='update_order'),
path('delete_order/<int:pk>', views.deleteOrder, name='delete_order'),
path('create_customer/', views.createCustomer, name='create_customer'),
]
forms.py
from django.forms import ModelForm, fields
from .models import Order, Customer
class OrderForm(ModelForm):
class Meta:
model = Order
# fields = ['customer', 'product']
fields = '__all__'
class CustomerForm(ModelForm):
class Meta:
model = Customer
fields = '__all__'
models.py
from django.db import models
from django.db.models.deletion import SET_NULL
class Customer(models.Model):
name = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
data_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
class Tag(models.Model):
name = models.CharField(max_length=200, null=True)
def __str__(self):
return self.name
class Product(models.Model):
CATEGORY = (
('Indoor', 'Indoor'),
('Out Door', 'Out Door'),
)
name = models.CharField(max_length=200, null=True)
prince = models.FloatField(null=True)
category = models.CharField(max_length=200, null=True, choices=CATEGORY)
description = models.CharField(max_length=200, null=True, blank=True)
data_created = models.DateTimeField(auto_now_add=True, null=True)
tags = models.ManyToManyField(Tag)
def __str__(self):
return self.name
class Order(models.Model):
STATUS = (
('Pending', 'Pending'),
('Out for delivery', 'Out for delivery'),
('Delivered', 'Delivered'),
)
customer = models.ForeignKey(Customer, null=True, on_delete=SET_NULL)
product = models.ForeignKey(Product, null=True, on_delete=SET_NULL)
status = models.CharField(max_length=200, null=True, choices=STATUS)
data_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.product.name
Traceback
Traceback (most recent call last):
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\le\Desktop\django-course\Django(02-09-21)\crm1\accounts\views.py", line 47, in createOrder
form_set_value.save()
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\models.py", line 681, in save
return self.save_existing_objects(commit) + self.save_new_objects(commit)
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\models.py", line 787, in save_existing_objects
if not self.initial_forms:
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\formsets.py", line 200, in initial_forms
return self.forms[:self.initial_form_count()]
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\formsets.py", line 157, in forms
for i in range(self.total_form_count())
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\formsets.py", line 130, in total_form_count
return min(self.management_form.cleaned_data[TOTAL_FORM_COUNT], self.absolute_max)
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\formsets.py", line 113, in management_form
form.full_clean()
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\forms.py", line 372, in full_clean
self._clean_fields()
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\forms.py", line 384, in _clean_fields
value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\widgets.py", line 263, in value_from_datadict
return data.get(name)
Exception Type: AttributeError at /create_order/1
Exception Value: 'WSGIRequest' object has no attribute 'get'
I think it has to do with the way the information is managed from the template, but I'm not really sure. Can someone help me?

Change:
OrderFormSet(request, instance=customer)
to:
OrderFormSet(request.POST, instance=customer)
The formset requires the post data, not the request object.

Related

IntegrityError : null value in column of relation " violates not-null constraint

'm building a small webstore , in the product page i put the order form using FormMixin and TemplateView, when i submit the order i get a " null value in column "customer_id" of relation "products_order" violates not-null constraint
DETAIL: Failing row contains (21, null)." error :
models.py
class Product(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
nominal_price = models.PositiveIntegerField(verbose_name='prix normal',)
reduced_price = models.PositiveIntegerField(blank=True, null=True)
quantity = models.PositiveIntegerField(default=10)
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products')
photo = models.ImageField(upload_to="img/products/", default="img/products/user_default.png")
def __str__(self):
return self.name
class Customer(models.Model):
full_name = models.CharField(max_length=150)
address = models.CharField(max_length=1500, null=True)
phone = models.IntegerField()
city = models.CharField(max_length=100)
email = models.EmailField(null=True)
def __str__(self):
return self.full_name
class Order (models.Model):
product = models.ManyToManyField(Product, through='OrderProduct')
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
class OrderProduct(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
views.py :
class ProductDetailView(FormMixin, TemplateView):
model = Product
template_name = 'product.html'
form_class = OrderForm
def get_success_url(self):
return reverse('index')
def post(self, request, *args, **kwargs):
context = self.get_context_data()
form = OrderForm(request.POST)
if context['form'].is_valid():
product = get_object_or_404(Product, name=self.kwargs['product_name'])
customer = form.save()
instance = Order.objects.create(customer=customer)
instance.product.set(product)
return super(TemplateView, self)
def get_context_data(self, **kwargs):
context = super(ProductDetailView, self).get_context_data(**kwargs)
context['product'] = Product.objects.get(name=self.kwargs['product_name'])
context['form'] = self.get_form()
return context
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.ProductListView.as_view(), name='index'),
path ('<str:product_name>/', views.ProductDetailView.as_view(), name='product'),
path('categories/', views.CategoryListView.as_view(), name='categories'),
path('add_category', views.AddCategoryView.as_view(), name='add_category'),
path('add_product/', views.AddProductView.as_view(), name='add_product'),
path('categories/<str:category_name>/', views.CategoryProductsView.as_view(), name='category_products'),
]
Traceback
Traceback (most recent call last):
File "D:\Python\Django\Django projects\Store\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "D:\Python\Django\Django projects\Store\venv\lib\site-packages\django\utils\deprecation.py", line 119, in __call__
response = self.process_response(request, response)
File "D:\Python\Django\Django projects\Store\venv\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response
if response.get('X-Frame-Options') is not None:
AttributeError: 'super' object has no attribute 'get'

How to retrieve selected data from Django Choice Field?

I want to retrieve the question_description answer_descritption and question_image answer_image if found in the database according to topic and question type using two ChoiceField for both: Topic and Question Type.
However, I don't know how to do that. I have seen some tutorials and gotten glimpses of what I have to do, but I am not sure how to preform the same techniques on my case because online there are not that many ChoiceField examples, except that there are general examples on how to use forms and extract data from the database.
This is the models.py
from django.db import models
from home.choices import *
# Create your models here.
class Topic(models.Model):
topic_name = models.IntegerField(
choices = question_topic_name_choices, default = 1)
def __str__(self):
return '%s' % self.topic_name
class Image (models.Model):
image_file = models.ImageField()
def __str__(self):
return '%s' % self.image_file
class Question(models.Model):
question_type = models. IntegerField(
choices = questions_type_choices, default = 1)
question_topic = models.ForeignKey( 'Topic',
on_delete=models.CASCADE,
blank=True,
null=True)
question_description = models.TextField()
question_answer = models.ForeignKey( 'Answer',
on_delete=models.CASCADE,
blank=True,
null=True)
question_image = models.ForeignKey( 'Image',
on_delete=models.CASCADE,
blank=True,
null=True)
def __str__(self):
return '%s' % self.question_type
class Answer(models.Model):
answer_description = models.TextField()
answer_image = models.ForeignKey( 'Image',
on_delete=models.CASCADE,
blank=True,
null=True)
answer_topic = models.ForeignKey( 'Topic',
on_delete=models.CASCADE,
blank=True,
null=True)
def __str__(self):
return '%s' % self.answer_description
This is the forms.py
from django import forms
from betterforms.multiform import MultiModelForm
from .models import Topic, Image, Question, Answer
from .choices import questions_type_choices, question_topic_name_choices
class TopicForm(forms.ModelForm):
topic_name = forms.ChoiceField(
choices=question_topic_name_choices,
widget = forms.Select(
attrs = {'class': 'home-select-one'}
))
class Meta:
model = Topic
fields = ['topic_name',]
def __str__(self):
return self.fields
class QuestionForm(forms.ModelForm):
question_type = forms.ChoiceField(
choices= questions_type_choices,
widget = forms.Select(
attrs = {'class': 'home-select-two'},
))
class Meta:
model = Question
fields = ['question_type',]
def __str__(self):
return self.fields
class QuizMultiForm(MultiModelForm):
form_classes = {
'topics':TopicForm,
'questions':QuestionForm
}
This is the views.py
from django.shortcuts import render, render_to_response
from django.views.generic import TemplateView
from home.models import Topic, Image, Question, Answer
from home.forms import QuizMultiForm
class QuizView(TemplateView):
template_name = 'index.html'
def get(self, request):
# What queries do I need to put here to get the question and answer's description according to the ChoiceField input
form = QuizMultiForm()
return render (request, self.template_name, {'form': form})
def post(self, request):
form = QuizMultiForm(request.POST)
if form.is_valid():
text = form.cleaned_data['topic_name', 'question_type'] # I don't know what to put here!
args = {'form': form, 'text': text}
return render (request, self.template_name, args)
This is the template:
{% extends 'base.html' %}
{% block content %}
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" id="home-Physics-time-button">It is Physics Time</button>
<h1> {{ text }} </h1>
</form>
{% endblock content %}
I would appropriate the help!
Thank you!
The cleaned_data attribute of the form, contains a dictionary that maps the name of the field with the bounded data. And from the MultiForm docs you can read:
cleaned_data
Returns an OrderedDict of the cleaned_data for each of the child forms.
Just extract data like this:
topic_name = form.cleaned_data['topics']['topic_name']
question_type = form.cleaned_data['question']['question_type']
# And so on ...

django_apscheduler.models.DoesNotExist: DjangoJob matching query does not exist

hi I am trying to implement a job scheduler using djangorestframework , django-apscheduler and requests libraries but when I try to post a request for scheduling a job following error appear although job is scheduled but response is code Internal server error (500) with following error
Traceback (most recent call last):
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args,
**callback_kwargs)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch
response = self.handle_exception(exc)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/gauravyadav/Python/env4/Scheduler3/distribute_jobs/views.py", line 298, in post
scheduler.start()
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/apscheduler/schedulers/blocking.py", line 19, in start
self._main_loop()
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/apscheduler/schedulers/blocking.py", line 30, in _main_loop
wait_seconds = self._process_jobs()
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/apscheduler/schedulers/base.py", line 987, in _process_jobs
jobstore_next_run_time = jobstore.get_next_run_time()
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django_apscheduler/jobstores.py", line 29, in inner
return func(*a, **k)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django_apscheduler/jobstores.py", line 79, in get_next_run_time
return
//not able to ident this code deserialize_dt(DjangoJob.objects.filter(next_run_time__isnull=False).earlie s .t('next_run_time').next_run_time)///
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django/db/models/query.py", line 597, in earliest
return self._earliest_or_latest(*fields, field_name=field_name)
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django/db/models/query.py", line 594, in _earliest_or_latest
return obj.get()
File "/Users/gauravyadav/Python/env4/lib/python3.6/site-packages/django/db/models/query.py", line 403, in get
self.model._meta.object_name
django_apscheduler.models.DoesNotExist: DjangoJob matching query does not exist.
[04/Jul/2018 12:19:05] "POST /jobs/ HTTP/1.1" 500 120459
-
Heading
models.py
class Jobs(models.Model, ListCharField, ListTextField):
title = models.CharField(max_length=20, blank=False, default='')
tenantId = models.TextField(max_length=50, null=True, default='')
studentid = models.CharField(max_length=20, blank=False, default=None,
null=True, db_index=False)
contentId = models.IntegerField(blank=False, null=False, db_index=False)
version = models.IntegerField(null=True)
appVersion = models.CharField(max_length=50, null=True)
devicePlatformName = models.TextField(max_length=50, null=True)
deviceIdentity = models.TextField(max_length=200, null=True)
deviceToken = models.TextField(max_length=200, null=True)
fcmToken = models.TextField(max_length=200, null=True)
fbTokenId = models.TextField(max_length=200, null=True)
userRole = models.TextField(max_length=50, null=True)
users = ListCharField(base_field=models.CharField(max_length=50,
null=True), null=True, size=100, max_length=20000)
# # users = models.CharField(max_length=600, null=True, default='')
allUsers = models.BooleanField(default=False)
groupIdList = ListTextField(base_field=models.IntegerField(null=True),
null=True)
sendSMS = models.BooleanField(default=False)
sendEmail = models.BooleanField(default=False)
distributeDateTime = models.CharField(max_length=200, null=True)
contentType = models.CharField(max_length=200, null=True)
distributeOn = models.CharField(max_length=200, null=True)
orgId = models.CharField(max_length=200, null=False, default=None)
run_immediate = models.BooleanField(default=False)
class Meta:
ordering = ('title',)
#######serializers.py########
class JobsSerializers(serializers.ModelSerializer):
users=serializers.ListField(child=serializers.CharField(max_length=200))
groupIdList = serializers.ListField(child=serializers.IntegerField())
class Meta:
model = Jobs
fields = (
'title',
'tenantId',
'studentid',
'contentId',
'version',
'appVersion',
'devicePlatformName',
'deviceIdentity',
'deviceToken',
'fcmToken',
'fbTokenId',
'userRole',
'groupIdList',
'allUsers',
'users',
'sendSMS',
'sendEmail',
'distributeDateTime',
'contentType',
'distributeOn',
'orgId',
'run_immediate',
# 'deviceInfoData'
)
def create(self, validated_data):
"""
Create and return a new `Jobs` instance, given the validated data.
"""
return Jobs.objects.create(**validated_data)
#########views.py
from rest_framework import mixins
from rest_framework import generics
from Scheduler3 import settings
from .models import Jobs
from .serializers import JobsSerializers
import requests
import json
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from django_apscheduler.jobstores import DjangoJobStore
scheduler = BlockingScheduler()
url = 'mysql+mysqldb://' + settings.DATABASES['default']['USER'] + ':'
\
+ settings.DATABASES['default']['PASSWORD'] + '#' +
settings.DATABASES['default']['HOST'] + '/' + \
settings.DATABASES['default']['NAME']
# jobstores = dict(default=SQLAlchemyJobStore(url=url))
# scheduler.configure(jobstores=jobstores)
scheduler.add_jobstore(DjangoJobStore(), "default")
def date_time_converter(distributeOn):
splited_run_date = '{}.000000'.format(distributeOn)
return splited_run_date
def schedule_job(users, contentId, orgId, allUsers, contentType,
tenantId, studentid, version, appVersion,
deviceInfoData, devicePlatformName, deviceIdentity,
deviceToken, fcmToken, fbTokenId, userRole,
groupIdList, sendSMS, sendEmail):
payload = {
"tenantId": "{}".format(tenantId),
"studentid": "{}".format(studentid),
"version": '{}'.format(version),
"appVersion": "{}".format(appVersion),
"devicePlatformName": "{}".format(devicePlatformName),
"deviceIdentity": "{}".format(deviceIdentity),
"deviceToken": "{}".format(deviceToken),
"fcmToken": "{}".format(fcmToken),
"fbTokenId": "{}".format(fbTokenId),
"userRole": "{}".format(userRole),
"users": users,
"allUsers": '{}'.format(allUsers) if 1 else 0,
"groupIdList": groupIdList,
"sendSMS": '{}'.format(sendSMS) if 1 else 0,
"sendEmail": '{}'.format(sendEmail) if 1 else 0,
"orgId": "{}".format(orgId),
"deviceInfoData": deviceInfoData
}
print("Payload")
print(payload)
url = 'http//:designated/url/distribute
r = requests.put(url, data=json.dumps(payload), headers=headers)
print(r.status_code, users)
print(r.reason)
print(r.text)
class JobList(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):
"""
List all jobs, or create a new job.
"""
queryset = Jobs.objects.all()
serializer_class = JobsSerializers
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request):
# print('c')
# scheduler.start()
# print('d')
print(request.data)
"""Serialzer data """
"""Fetching Request Data """
distributeOn = request.data.get('distributeOn')
jobTitle = request.data.get('title')
users = request.data.get('users')
contentId = request.data.get('contentId')
orgId = request.data.get('orgId')
contentType = request.data.get('contentType')
tenantId = request.data.get('tenantId')
studentid = request.data.get('studentid')
version = request.data.get('version')
appVersion = request.data.get('appVersion')
deviceInfoData = request.data.get('deviceInfoData')
devicePlatformName = request.data.get('devicePlatformName')
deviceIdentity = request.data.get('deviceIdentity')
deviceToken = request.data.get('deviceToken')
fcmToken = request.data.get('fcmToken')
fbTokenId = request.data.get('fbTokenId')
userRole = request.data.get('userRole')
groupIdList = request.data.get('groupIdList')
sendSMS = request.data.get('sendSMS')
sendEmail = request.data.get('sendEmail')
allUsers = request.data.get('allUsers')
"""Calling Time Formatter Function to provided time for Job Trigger"""
splited_datetime = date_time_converter(distributeOn)
"""Instantiating Scheduler and Scheduling Jobs"""
job1 = scheduler.add_job(schedule_job, 'date',
run_date='{}'.format(splited_datetime),
misfire_grace_time=200, args=[users,
contentId, orgId, allUsers, contentType,
tenantId,
studentid, version, appVersion,
deviceInfoData, devicePlatformName,
deviceIdentity,
deviceToken,
fcmToken, fbTokenId, userRole,
groupIdList,
sendSMS, sendEmail],
max_instances=20,
replace_existing=True)
if not scheduler.running == True:
print('c')
scheduler.start()
print('d')
print("after add job method called")
print(job1.id)
return self.create(request)
##########urls.py######
from django.conf.urls import url, include
from django.contrib import admin
from django.urls import path
urlpatterns = [
url('admin/', admin.site.urls),
url(r'^', include('distribute_jobs.urls')),
]
###distribute_jobs/url.py
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from distribute_jobs import views
urlpatterns = [
url(r'^jobs/$', views.JobList.as_view()),
url(r'^jobs/(?P<pk>[0-9]+)/$', views.JobDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)
Hi this issues is a bug on django-apscheduler version=0.2.11 which resolved on version=0.2.12 for more details please click here

Django/Python: Tried to update field with a model instance. Use a value compatible with CharField

I have created a Django project in which type-1 users can create a Post and type-2 users can bid on a post. Finally, post_owner can accept a bid. In my Post model there is a CharField 'bidder' which sets to '0' as default. After accepting I wanted to update this field with bidder_id as in accepted bid. I written an updated view for this field in my Auction view.
But it raising an error : Tried to update field MyApp1.Post.bidder with a model instance, . Use a value compatible with CharField. I would appreciate helping me solve this.
Models.py:
class Post(models.Model):
item = models.CharField(max_length=20)
post_owner = models.OneToOneField(settings.AUTH_USER_MODEL, default=1)
bidder = models.CharField(max_length=20, default=0)
class Bid(models.Model):
post = models.ForeignKey(Post, related_name = bids)
amount = models.IntegerField(max_length = 20)
bidder = models.ForeingKey(settings.AUTH_USER_MODEL)
class Auction(models.Model):
post = models.ForeignKey(Post, related_name='auctions')
post_owner = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
bid = models.OneToOneField('truck.Bid', related_name='auctions')
forms.py:
class AcceptedForm(forms.ModelForm):
bidder = forms.CharField(required=False, widget=forms.HiddenInput())
class Meta:
model = Post
fields = ('bidder', )
Views.py:
def live_bids(request):
if request.method=='POST':
instance_post = Post.objects.get( id = request.POST['post_id'])
form = AcceptedForm(request.POST, instance = instance_post)
post = Post.objects.get( id = request.POST['post_id'] )
bid = Bid.objects.get(id = request.POST['bid_id'])
if form.is_valid():
accepted = form.save(commit=False)
accepted.bidder = bid.bidder
accepted.save()
form.save()
else:
form = AcceptedForm()
return render(request, 'live_bids.html', 'form':form)
live_bids.html:
<form class="nomargin" method='POST' action='' enctype='multipart/form-data'>{% csrf_token %}
{{form.bidder}}
<input type='hidden' name='post_id' value='{{post.id}}'/>
<input type='hidden' name='bid_id' value='{{bid.id}}'/>
<input type='submit' value='Accept'/>
Traceback:
File "C:\python34\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\python34\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\python34\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "C:\python34\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "C:\Users\sumanth\Desktop\django-custom-user-master\search field\Project\mysite\personal\views.py" in live_bids
323. if form.is_valid() :
File "C:\python34\lib\site-packages\django\forms\forms.py" in is_valid
161. return self.is_bound and not self.errors
File "C:\python34\lib\site-packages\django\forms\forms.py" in errors
153. self.full_clean()
File "C:\python34\lib\site-packages\django\forms\forms.py" in full_clean
364. self._post_clean()
File "C:\python34\lib\site-packages\django\forms\models.py" in _post_clean
380. self.instance = construct_instance(self, self.instance, opts.fields, exclude)
File "C:\python34\lib\site-packages\django\forms\models.py" in construct_instance
60. f.save_form_data(instance, cleaned_data[f.name])
File "C:\python34\lib\site-packages\django\db\models\fields\__init__.py" in save_form_data
865. setattr(instance, self.name, data)
File "C:\python34\lib\site-packages\django\db\models\fields\related_descriptors.py" in __set__
207. self.field.remote_field.model._meta.object_name,
Exception Type: ValueError at /live_bids/
Exception Value: Cannot assign "''": "Post.bidder" must be a "EmailUser" instance.
The problem is in view. You cant do this:
bid = Bid.objects.get(id = request.POST['bid_id'])
if form.is_valid():
accepted = form.save(commit=False)
accepted.bidder = bid.bidder
because accepted.bidder is CharField and bid.bidder is UserModel
so you can do either:
bid = Bid.objects.get(id = request.POST['bid_id'])
if form.is_valid():
accepted = form.save(commit=False)
accepted.bidder = str(bid.bidder_id) # add User.id as string
OR I think better solution is make little changes
class AcceptedForm(forms.Form):
bidder = forms.InteferField(required=False, widget=forms.HiddenInput())
post_id = forms.InteferField(required=False, widget=forms.HiddenInput())
bid_id = forms.InteferField(required=False, widget=forms.HiddenInput())
class Meta:
fields = ('bidder', 'post_id', 'bid_id')
and view:
if request.method=='POST':
form = AcceptedForm(request.POST)
if form.is_valid():
post = Post.objects.get( id = form.cleaned_data['post_id'] )
bid = Bid.objects.get(id = form.cleaned_data['bid_id'])
post.bidder = bid.bidder # You set post.bidder instance so you have to change model
post.save()
else:
form = AcceptedForm()
and models:
class Post(models.Model):
item = models.CharField(max_length=20)
post_owner = models.OneToOneField(settings.AUTH_USER_MODEL, default=1)
# Bidder should be User Foreign Key, but you have to set related_name, because you already have one User FK in model
bidder = models.ForeingKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name='posts_bidded')
and template:
<form class="nomargin" method='POST' action='' enctype='multipart/form-data'>{% csrf_token %}
{{form}}
<input type='submit' value='Accept'/>
But I dont know purpose of bidder field, even in your code you override the field bidder anyway.

Django Photo app not displaying

I'm making a photo app using this light bird tutorial .
The problem is , The pictures that I upload . Won't display on the page.
I have never displayed a picture in django before and I think the problem is with the configuration
My models.py
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
from string import join
import os
from PIL import Image as PImage
from mysite.settings import MEDIA_ROOT
class Album(models.Model):
title = models.CharField(max_length=60)
public = models.BooleanField(default=False)
def __unicode__(self):
return self.title
def images(self):
lst = [x.image.name for x in self.image_set.all()]
lst = ["<a href='/media/%s'>%s</a>" % (x, x.split('/')[-1]) for x in lst]
return join(lst, ', ')
images.allow_tags = True
class Tag(models.Model):
tag = models.CharField(max_length=50)
def __unicode__(self):
return self.tag
class Image(models.Model):
title = models.CharField(max_length=60, blank=True, null=True)
image = models.FileField(upload_to="images/")
tags = models.ManyToManyField(Tag, blank=True)
albums = models.ManyToManyField(Album, blank=True)
created = models.DateTimeField(auto_now_add=True)
rating = models.IntegerField(default=50)
width = models.IntegerField(blank=True, null=True)
height = models.IntegerField(blank=True, null=True)
user = models.ForeignKey(User, null=True, blank=True)
def save(self, *args, **kwargs):
"""Save image dimensions."""
super(Image, self).save(*args, **kwargs)
im = PImage.open(os.path.join(MEDIA_ROOT, self.image.name))
self.width, self.height = im.size
super(Image, self).save(*args, ** kwargs)
def size(self):
"""Image size."""
return "%s x %s" % (self.width, self.height)
def __unicode__(self):
return self.image.name
def tags_(self):
lst = [x[1] for x in self.tags.values_list()]
return str(join(lst, ', '))
def albums_(self):
lst = [x[1] for x in self.albums.values_list()]
return str(join(lst, ', '))
def thumbnail(self):
return """<img border="0" alt="" src="/media/%s" height="40" />""" % (
(self.image.name, self.image.name))
thumbnail.allow_tags = True
def __unicode__(self):
return self.image.name
class AlbumAdmin(admin.ModelAdmin):
search_fields = ["title"]
list_display = ["title"]
My views.py
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.contrib.auth.decorators import login_required
from django.core.context_processors import csrf
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.forms import ModelForm
from mysite.settings import MEDIA_URL
from photo.models import *
def main(request):
"""Main listing."""
albums = Album.objects.all()
if not request.user.is_authenticated():
albums = albums.filter(public=True)
paginator = Paginator(albums, 10)
try: page = int(request.GET.get("page", '1'))
except ValueError: page = 1
try:
albums = paginator.page(page)
except (InvalidPage, EmptyPage):
albums = paginator.page(paginator.num_pages)
for album in albums.object_list:
album.images = album.image_set.all()[:4]
return render_to_response("photo/list.html", dict(albums=albums, user=request.user,
media_url=MEDIA_URL))
class TagAdmin(admin.ModelAdmin):
list_display = ["tag"]
class ImageAdmin(admin.ModelAdmin):
search_fields = ["title"]
list_display = ["__unicode__", "title", "user", "rating", "size", "tags_", "albums_",
"thumbnail", "created"]
list_filter = ["tags", "albums", "user"]
def save_model(self, request, obj, form, change):
obj.user = request.user
obj.save()
admin.site.register(Album, AlbumAdmin)
admin.site.register(Tag, TagAdmin)
admin.site.register(Image, ImageAdmin)
Ok here's the problem why the picture didn't show. You call the incorrect and override the path of the image. Remember you have already put function in your model the thumbnail so in your template you must put only:
<ul>
{% for album in albums.object_list %}
<div class="title">{{ album.title }} ({{ album.image_set.count }} images)</div>
<ul>
{% for img in album.images %}
{{img.thumbnail}}
{% endfor %}
</ul>
{% endfor %}
</ul>
This is correct but my problem is when I test it, the allow tags function has no effect so the output is a link instead of image. So I modified it and got the images show.
{% for img in album.images %}
<a href="{{MEDIA_URL}}{{ img.image}}">
<img border="0" alt="" src="{{MEDIA_URL}}{{ img.image}}" />
</a>
{% endfor %}