i'm working on my first django project and i got this error
(Cannot assign "'433245675'": "Lockers.locker_id" must be a "Renters" instance.)
anyone here can help me pleas.
the views:
def adding_renter(request):
form_data = forms.AddingRenter(request.POST or None)
msg = ''
if form_data.is_valid():
renters = models.Renters()
renters.renter_id = form_data.cleaned_data['renter_id']
renters.renter_name = form_data.cleaned_data['renter_name']
renters.renter_email = form_data.cleaned_data['renter_email']
renters.renter_phone_number = form_data.cleaned_data['renter_phone_number']
renters.renting_start_date = form_data.cleaned_data['renting_start_date']
renters.renting_end_date = form_data.cleaned_data['renting_end_date']
renters.save()
msg = 'Renter has been added successfully'
context = {
'form': form_data,
'msg': msg
}
return rend
er(request, 'addingrenter.html', context)
def adding_locker(request):
form_data = forms.AddingLocker(request.POST or None)
msg = ''
if form_data.is_valid():
lockers = models.Lockers()
lockers.locker_id = form_data.cleaned_data['locker_id']
lockers.locker_number = form_data.cleaned_data['locker_number']
lockers.locker_information = form_data.cleaned_data['locker_information']
lockers.locker_status = form_data.cleaned_data['locker_status']
lockers.locker_notes = form_data.cleaned_data['locker_notes']
lockers.save()
msg = 'Locker has been added successfully'
context = {
'form': form_data,
'msg': msg
}
return render(request, 'addinglocker.html', context)
I'm going to guess you have the field named as locker_id. If that's the case, the actual ID field is named locker_id_id. So try using:
lockers.locker_id_id = form_data.cleaned_data['locker_id']
Though your error makes it seem like your model is defined as:
class Renters(models.Model):
...
class Lockers(models.Model):
locker_id = models.ForeignKey(Renters)
Instead it should be:
class Renter(models.Model): # Models should be singular
...
class Locker(models.Model):
renter = models.ForeignKey(Renter)
Related
Here is my code:
In forms.py
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ("title","business_partner","transaction")
widgets = {
'transaction': forms.NumberInput()
}
In views.py
def uploadpdf(request,pk):
project_form = ProjectForm(request.POST)
if project_form.is_valid() and request.FILES:
project_form.instance.user = request.user
project = Project.objects.get(id=pk)
project.title = project_form['title']
project.business_partner = project_form['business_partner']
project.transaction = project_form['transaction']
project.save()
project = Project.objects.get(id=pk)
file_path = None
for file in request.FILES:
file = request.FILES[file]
pdf_file = PDFFile(file=file, filename=file.name)
pdf_file.project = project
pdf_file.save()
if PRODUCTION:
file_path = HOST_NAME +'/'+ str(pdf_file.file)
else:
file_path = HOST_NAME +'/media/'+ str(pdf_file.file)
resp = HttpResponse(f'{{"message": "Uploaded successfully...", "id": "{project.id}","url":"{file_path}","title": "{project.title}"}}')
resp.status_code = 200
resp.content_type = "application/json"
return resp
else:
return reverse("dashboard:homepage")
When I run this, it says like "TypeError: Field 'transaction' expected a number but got <django.forms.boundfield.BoundField object at 0x000001A803935250>."
Looking forward to hearing a good solution.
You want to use the cleaned_data attribute of the form instead of the field itself like so:
project.transaction = project_form.cleaned_data['transaction']
Edit: Note that you should have to do the same for the other fields.
I am trying to pass a list of student IDs but it is not working.
from angular I am passing data as follows
let noticeData = this.announceForm.value;
if (noticeData.students.includes('all')){
noticeData.students = noticeData.students.filter((s) => s != 'all')
}
noticeData.students = JSON.stringify(noticeData.students);
rest call
var formData = new FormData();
for (var key in noticeData) {
formData.set(key, noticeData[key]);
}
this._rest.one("/classwork/notices/")
.post('', formData)
.toPromise()
.then((classworks) => {
}, (error) => {
console.log("ERROR SENDING ANNOUNCEMENT ", error);
this.alert = {
type : "error",
message: "Something went wrong, please try again."
}
});
}
from django i am reading and trying to store data as
Below is the to_internal_value method which I have overridden.
def to_internal_value(self, data):
tempdict = data.copy()
tempdict['students'] = json.loads(data['students'])
data = tempdict
return super(NoticesSerializer, self).to_internal_value(data)
views.py
class ClassworkView(APIView):
def get(self, request, format=None):
notices = ClassworksFilter(request.query_params, queryset=Notice.objects.all()).qs
materials = ClassworksFilter(request.query_params, queryset=Material.objects.all()).qs
assignments = ClassworksFilter(request.query_params, queryset=Assignment.objects.all()).qs
queryset = sorted(
chain(notices, materials, assignments),
key=lambda instance: instance.create_date
)
model_serializers = {
'notice': NoticesSerializer,
}
classworks = []
for instance in queryset:
serializer = model_serializers[instance._meta.model_name]
data = serializer(instance).data
data['classwork_type'] = instance._meta.model_name
classworks.append(data)
page_number = request.query_params.get('page', 1)
page_size = request.query_params.get('page_size', 20)
page = Paginator(classworks, per_page=page_size).get_page(page_number)
base_url = f'{request.scheme}://{request.get_host()}{reverse("classworks")}'
params = [f'{k}={v}' if k!='page' else None for k,v in request.query_params.items()]
indx = 0
for param in params:
if param==None:
params.pop(indx)
indx+=1
params = '&'.join(params)
next = f'{base_url}?page={page.next_page_number()}&{params}' if page.has_next() else None
prev = f'{base_url}?page={page.previous_page_number()}&{params}' if page.has_previous() else None
response = {
'count': len(classworks),
'next': next,
'previous': prev,
'results': page.object_list
}
return Response(response)
here is serializer.py
class NoticesSerializer(serializers.ModelSerializer):
class Meta:
model = Notice
fields = '__all__'
def to_representation(self, instance):
representation = super(NoticesSerializer, self).to_representation(instance)
try:
representation['classroom'] = ClassroomsSerializer(instance.classroom, context=self.context).data
students = StudentsSerializer(instance.students, many=True, context=self.context).data
for student in students:
student['classroom'] = student['classroom']['id']
representation['students'] = students
except Exception as error:
print("ERROR SETTING REPRESENTATION FOR NOTICE SERIALIZER", error)
return representation
here is the models.py
class Notice(Classwork):
file = models.FileField(upload_to='classworks/attachments', blank=True, null=True)
link = models.URLField(blank=True, null=True)
description = models.TextField()
class Meta(BaseModel.Meta):
db_table = 'ec_notice'
but it always returns the same error
{students: [“Incorrect type. Expected pk value, received list.”]}
here the data I am posting by form data
in view.py:
#require_POST
#csrf_exempt
def ipn(request):
transactions_logger = logging.getLogger("django")
processor = Ipn(request.POST, logger=transactions_logger)
verification_success = processor.verify_ipn()
encoding = request.POST.get('ok_charset', None)
data = QueryDict(request.body, encoding=encoding)
if verification_success:
form = OkpayIpnForm(data)
if form.is_valid():
print("ALL FINE!!")
form.save()
return HttpResponse("")
In forms.py:
class OkpayIpnForm(forms.ModelForm):
class Meta:
model = OkpayIpn
exclude = []
Code for IPN Checkprocessor = Ipn(request.POST, logger=transactions_logger:
class Ipn(object):
OKPAY_VERIFICATION_URL = 'https://checkout.okpay.com/ipn-verify'
OKPAY_IPN_INVALID = b'INVALID'
OKPAY_IPN_VERIFIED = b'VERIFIED'
OKPAY_IPN_TEST = b'TEST'
OKPAY_STATUS_COMPLETED = 'completed'
__verification_result = False
def __init__(self, request_data, logger):
if 'ok_verify' in request_data:
raise Exception("ok_verify must not be present in initial request data for {}".format(
self.__class__.__name__
))
self._request_data = request_data
self.logger = logger
return
def verify_ipn(self):
self.__verification_result = False
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
verify_request_payload = {
'ok_verify': 'true',
}
verify_request_payload.update(self._request_data)
resp = requests.post(self.OKPAY_VERIFICATION_URL, data=verify_request_payload, headers=headers)
if resp.content == self.OKPAY_IPN_VERIFIED or resp.content == self.OKPAY_IPN_TEST:
self.__verification_result = True
# if resp.content == self.OKPAY_IPN_VERIFIED: # anyway disable test on production.
# self.__verification_result = True
return self.__verification_result
All is ok, I revice IPN and validate it, then I try to validate form and save it to Database.
But form doesn't pass validation and doesn't save to database.
Thank You for help
Problem was that 1 CharField of Model for saving IPN has maxlength=20, but recieved 40 symbols.
Thx jape he advised to add in form validation else statement and print form.errors
the error of of form validation was :
<li>ok_item_1_type<ul class="errorlist"><li>Ensure this value has at most 20 characters (it has 40).</li></ul></li>
In the view below, I prevent creation of a meeting with the same date and time. But anyhow, this code results in creating a recurrent meeting.
def new_meeting_board(request):
if User.is_authenticated:
username = request.user.username
else:
return HttpResponseRedirect('/login/board/')
if request.method == 'POST':
form = new_meetingForm(request.POST)
now = datetime.datetime.now()
if form.is_valid():
clash = 1
user = User.objects.get(username = username)
try:
meet_check = meeting.objects.get(date = form.cleaned_data['date'], time = form.cleaned_data['time'])
except meeting.DoesNotExist:
clash = 0
if clash == 1:
form = new_meetingForm()
variables = RequestContext(request, {
'username': username,
'form': form,
})
return render_to_response('new_meeting_board.html', variables)
else:
mem = memo(
snd_username = user,
rcv_username = form.cleaned_data['reciever'],
subject = 'Meeting',
date = str(now.year) + '-' + str(now.month) + '-' + str(now.day),
time = str(now.hour) + ':' + str(now.minute),
)
mem.save()
mee = mem.meeting_set.create(
snd_username = username,
rcv_username = mem.rcv_username,
status_username = '0',
date = form.cleaned_data['date'],
time = form.cleaned_data['time'],
venue = form.cleaned_data['venue'],
)
mee.save()
return HttpResponseRedirect('/dashboard/board/' + username)
else:
form = new_meetingForm()
variables = RequestContext(request, {
'username': username,
'form': form,
})
return render_to_response('new_meeting_board.html', variables)
The except portion of the try/except block does not seem to work for some reason. Please help.
meeting.objects should probably be Meeting.objects
There are multiple reformatting and optimization can be done in your code. Rather than using get(), you can use get_or_create to optimize code. You can write the code like this:
def new_meeting_board(request):
if not request.user.is_authenticated(): # there is a mistake in your code, its not User.is_authenticated.
return HttpResponseRedirect('/login/board/')
if request.method == 'POST':
form = new_meetingForm(request.POST)
now = datetime.datetime.now()
if form.is_valid():
user = request.user
meet_obj, meet_check = meeting.objects.get_or_create(
date = form.cleaned_data['date'],
time = form.cleaned_data['time'],
subject = 'Meeting',
snd_username=user,
rcv_username = form.cleaned_data['reciever']
)
if meet_check is True:
form = new_meetingForm()
variables = RequestContext(request, {
'form': form,
})
return render_to_response('new_meeting_board.html', variables)
else:
mee = meet_obj.meeting_set.create(
snd_username = username,
rcv_username = meet_obj.rcv_username,
status_username = '0',
date = form.cleaned_data['date'],
time = form.cleaned_data['time'],
venue = form.cleaned_data['venue'],
)
mee.save()
return HttpResponseRedirect('/dashboard/board/' + username)
else:
form = new_meetingForm()
variables = RequestContext(request, {
'form': form, # no need to send username, You can access it in the template by putting {{ request.user.username }}
})
return render_to_response('new_meeting_board.html', variables)
I have "oReverseMatch at /filter" error while running my app?
This is urls.py:
urlpatterns = patterns('myform.views',
url(r'^contact$', 'contact'),
url(r'^affiche$', 'affiche'),
url(r'^add$', 'add'),
url(r'^filter$', 'filter'),
url(r'^filter_display/(?P<continent>[-\w]+)/$', 'filter_display',name='FilterDisplay'),
This is my view.py:
class FilterForm(forms.Form):
Continent = forms.ChoiceField(choices=Select_continent())
Country = forms.ChoiceField(choices=Select_country())
City = forms.ChoiceField(choices=Select_city())
Server_Adress = forms.ChoiceField(choices=Select_adress())
def filter(request):
if request.method == 'POST':
form = FilterForm(request.POST)
if form.is_valid() :
Continent = form.cleaned_data['Continent']
Country = form.cleaned_data['Country']
City = form.cleaned_data['City']
Server_Adress = form.cleaned_data['Server_Adress']
#Continent = dict(form1.fields['Continent'].choices)[Continent]
#Country = dict(form1.fields['Country'].choices)[Country]
#City = dict(form1.fields['City'].choices)[City]
#Server_Adress = dict(form1.fields['Server_Adress'].choices)[Server_Adress]
url = reverse('filter_display', args=(), kwargs={'continent': 'America',})
return HttpResponseRedirect(url)
else:
form = FilterForm()
return render_to_response('filter.html', { 'form': form }, RequestContext(request))
def filter_display(request, continent):
if request.method == 'POST':
form1 = FilterForm(request.POST)
if form1.is_valid() :
Continent = form1.cleaned_data['Continent']
Country = form1.cleaned_data['Country']
City = form1.cleaned_data['City']
Server_Adress = form1.cleaned_data['Server_Adress']
else:
form1 = FilterForm()
data = Select_WHERE(continent)
return render_to_response('affiche_continent.html', {'form1':form1, 'data':data }, RequestContext(request))
It works when I type 'localhost:8000/filter_display/EUROPE/' in URL.
The code works perfectly in "filter_display".
But when I try to pass parameter using the "filter" function in view I get this error
You have supplied a name for that URL, so you should use that in the call to reverse:
url = reverse('FilterDisplay', kwargs={'continent': 'America',})