Field 'id' expected a number but got <WSGIRequest: GET '/r/1/'> - python

i tried to make a project which would convert long url to short. take input url from html page and save it to database and redirect it to long url though my new url
but got an error
and the index.html looks like
<h1>short any url here</h1>
<form method="POST">
{% csrf_token %}
<input type="url" name="url" placeholder="enter your url here">
<input type="submit" value="submit">
</form>
{% for urlconverter in urlconv %}
<li>{{ urlconverter.short }} </li>
{% endfor %}
urls.py
from django.urls import path
from .import views
app_name='shorturl'
urlpatterns=[
path('shorturl/',views.indx,name='home'),
path('r/<int:urlconverter_id>/',views.redirect,name='redirect'),
]
the models.py
from django.db import models
# Create your models here.
class urlconverter(models.Model):
url=models.CharField(max_length=1000)
short=models.CharField(max_length=100)
def __str__(self):
return self.url
views.py
from django.shortcuts import render,redirect,get_object_or_404
from django.http import HttpResponse
from django.template import loader
from .models import urlconverter
# Create your views here.
def indx(request):
template=loader.get_template('urlconverter/index.html')
urlconv=urlconverter.objects.all()
if request.method=='POST':
a=request.POST.get('url')
b=urlconverter.objects.all()
c=b.count()
nwurl='/r/'+str(c)
s=urlconverter(url=a,short=nwurl)
s.save()
context={
'urlconv':urlconv
}
return HttpResponse(template.render(context,request))
def redirect(request,urlconverter_id):
obj=get_object_or_404(urlconverter,pk=urlconverter_id)
org_url=obj.url
return redirect(org_url,request)
and i got this error
TypeError at /r/1/
Field 'id' expected a number but got <WSGIRequest: GET '/r/1/'>.
Request Method: GET
Request URL: http://127.0.0.1:8000/r/1/
Django Version: 4.0.5
Exception Type: TypeError
Exception Value:
Field 'id' expected a number but got <WSGIRequest: GET '/r/1/'>.
could anyone please help me, where is the problem here?

Related

Unable to return using post method in an html form. what am i doing wrong?

I am new to programming, i have been learning django for the first time. I created a form using home.html file an i requested using POST method, but in the error it is giving the request method as GET. When I remove the method="POST" and put request.GET in views file, it is working fine. What am I doing wrong here?
home.html
< form action="add" method="POST">
{% csrf_token %}
Enter 1st number : <input type="text" name="num1"><br>
Enter 2nd number : <input type="text" name="num2"><br>
<input type="submit">
</form>
views.py
def add(request):
val1= int(request.POST['num1'])
val2= int(request.POST['num2'])
res= val1 +val2
return render(request, 'result.html' ,{'result': res})
I am getting the following error:
MultiValueDictKeyError at /add
'num1'
Request Method: GET
Request URL: http://127.0.0.1:8000/add?num1=17&num2=4
Django Version: 4.0.1
Exception Type: MultiValueDictKeyError
Exception Value:
'num1'
Views.py
def add(request):
if request.method == "POST":
#LOGIC AS TO WHAT TO SERVE WHEN THIS VIEW RECIEVES A POST REQUEST
val1= int(request.POST.get('num1'))
val2= int(request.POST.get('num2'))
res= val1 +val2
return render(request, 'result.html' ,{'result': res})
else:
#serves non POST request , ie GET in this case
...your GET REQUEST LOGIC
return render(request, 'GETREQUESTPAGE.html' ,{'param1': paramval})
urls.py:
# blog.urls
from django.urls import path
from . import views
#example consider a url for app named blog... mention the app name in the urls.py as below
app_name = 'blog'
urlpatterns = [
path('', views.index(), name='add'),
]
home.html :
if you want to the view called "add" in the app blog to handle the POST request, then ...
< form action="{% url blogs.add %}" method="POST">
{% csrf_token %}
Enter 1st number : <input type="text" name="num1"><br>
Enter 2nd number : <input type="text" name="num2"><br>
<input type="submit">
</form>

Django ListView is missing a QuerySet - Error Message - 2 Models In 1 View

I'm trying to view data from 2 models in a single list view. I'm getting the below error message and I can't seem to figure out why. I have included the browser error, views.py, urls.py and html page. Any assistance would be appreciated and as a side note I'm new to programming, Python and Django.
Error:
ImproperlyConfigured at /scripts/patientsdetails/
PatientListView is missing a QuerySet. Define PatientListView.model, PatientListView.queryset, or override PatientListView.get_queryset().
Request Method: GET
Request URL: http://127.0.0.1:8000/scripts/patientsdetails/
Django Version: 3.2.2
Exception Type: ImproperlyConfigured
Exception Value:
PatientListView is missing a QuerySet. Define PatientListView.model, PatientListView.queryset, or override PatientListView.get_queryset().
urls.py
from django.urls import path
from .views import (
ScriptListView,
ScriptUpdateView,
ScriptDetailView,
ScriptDeleteView,
ScriptCreateView,
PatientListView,
PatientUpdateView,
PatientDetailView,
PatientDeleteView,
PatientCreateView,
)
urlpatterns = [
path('patientsdetails/',
PatientListView.as_view(), name='patient_list'),
]
views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView, DetailView
from django.views.generic.edit import UpdateView, DeleteView, CreateView
from django.urls import reverse_lazy
from bootstrap_datepicker_plus import DatePickerInput, TimePickerInput
from django.contrib.auth import get_user_model
from django.shortcuts import render
from scripts.models import Patient, Script
from .models import Script, Patient
class PatientListView(LoginRequiredMixin, ListView):
template_name = 'patient_summary.html'
def get_context_data(self, **kwargs):
context = super(PatientListView, self).get_context_data(**kwargs).filter(author=self.request.user)
context['patient'] = Patient.objects.filter(author=self.request.user)
context['script'] = Script.objects.filter(author=self.request.user)
return context
html
{% for patient in object_list %}
<div class="card">
<div class="card-header">
<span class="font-weight-bold">{{ patient.patient_name }}</span> ยท
<span class="text-muted"></span>
</div>
<div class="card-body">
Cycle Start Date - {{ patient.cycle_start_day }} <br>
{% endfor %}
{% for script in object_list %}
Drug Name - {{ script.drug_name }} <br>
{% endfor %}
</div>
<div class="card-footer text-center text-muted">
</div>
</div>
<br />
I think it's clear from the error that you have to define which model/queryset attribute to work upon by list view
Do this in your view:
model = Patient
Or
queryset = Patient.objects.all()
Or override get_queryset method
def get_queryset(self):
return Patient.objects.all()

Django ImportError: No module named 'collection'

As stated in the title, I keep getting an error when trying to create a form. It's on the line that has:
from collection.forms import contact_form
An I'm getting the error:
File "/home/mike/CINS465/465proj/project/firstapp/views.py", line 2, in <module>
from collection.forms import contact_form
ImportError: No module named 'collection'
Any idea where I'm going wrong? I'm new to django and this was pulled from a tutorial on creating a contact form. I thought collection was built-in to django
Edit:
from views.py
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from .models import *
from .forms import contact_form
# Create your views here.
def contact(request):
form_class = contact_form
return render(request, 'contact.html', {
'form': form_class,
})
from urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'contact/$',views.contact, name='contact'),
]
from contact.html
{% block title %}Contact - {{ block.super }}{% endblock %}
{% block content %}
<h1>Contact</h1>
<form role="form" action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
from forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
class contact_form(forms.Form):
contact_name = forms.CharField(label='Contact Name', max_length=255)
contact_email = forms.CharField(label='Contact Email',max_length=255)
contact_message = forms.CharField(
label='Contact Message',
required=True,
widget=forms.Textarea
)
I didn't include code that was irrelevant (i.e. index page).
You need to create an empty file called __init__.py in the app directory to make it into a package. If you don't have that file, you cannot perform submodule imports.
touch /home/mike/CINS465/465proj/project/firstapp/collections/__init__.py

Python Django - django-filters app - autogenerate searchfield based on model

Alright,
First time I'm asking a question over here, i did search for similar question but haven't found my answer yet..
I'm working on a simple delivery app with Django, it shows an overview of customers checkin in and out and some details on the delivery.
I have a view called "CheckInsListView" and "CheckOutListView" and i would like to filter these lists on a user given date, based on the django-filters app.
I tried following this link: https://simpleisbetterthancomplex.com/tutorial/2016/11/28/how-to-filter-querysets-dynamically.html
The problem now is, the searchform is not automatically created. It does show the submit button but the formfield isn't generated. It doesn't come up with any errors either.
Can somebody point out what I'm missing here?
Thanks in advance,
Kevin
#filters.py
from .models import Delivery
import django_filters
class DeliveryFilter(django_filters.FilterSet):
class Meta:
model = Delivery
fields = ['arrival_date']
Adding the view:
#views.py
"""
Create a search view to sort deliveries on date, django-filter app is used
"""
from django.shortcuts import render
from .models import Delivery
from .filters import DeliveryFilter
def search(request):
delivery_list = Delivery.objects.all()
delivery_filter = DeliveryFilter(request.GET, queryset=delivery_list)
return render(request, 'all_deliveries.html', {'filter': delivery_filter})
And urls
#urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^search/$', views.search, name='search'),
]
The form in html
{% extends "framework.html" %}
{% block content %}
<div class="form_search_header">
<form method="get">
{{ filter.form.as_p }}
<button type="submit">Search</button>
</form>
</div>
{% endblock %}
delivery_filter = DeliveryFilter(request.GET, queryset=delivery_list)
This is still going to return filtered records. There you need to write a for loop in the template, something like below:
<option value="" disabled selected>Select Delivery Item</option>
{% for d in filter %}
<option value="{{ d.id }}">{{ d.arrival_date }}</option>
{% endfor %}

Django from doesn't get processed. HTTP 405 error raises

I am trying to process a post form, but I can't manage. I have prepared the form, gave the action link, set the method to post, but when I hit the submit button, nothing happens, not even an error page isn't shown by django despite my debug option is True.
Here is the form code in my template file:
<form method="post" action="{% url 'articles:stepprocess' 0 %}">
{% csrf_token %}
<p><label for="title">Title:</label>
<input name="title" id="title" type="text"/></p>
<p>
<label for="dif">Difficulty</label>
<select name="dif" id="dif">
{% if difficulties %}
{% for difficulty in difficulties %}
<option value="{{ difficulty.pk }}">{{ difficulty }}</option>
{% endfor %}
{% endif %}
</select>
</p>
<p><label for="article">Content:</label>
<textarea cols="37" rows="11" name="article" id="article"></textarea></p>
<p><input name="send" style="margin-left: 150px;" class="formbutton" value="Send"
type="submit"/></p>
</form>
My urls.py file:
from django.conf.urls import url
from .views import *
urlpatterns = [
url(r'^$', Index.as_view(), name="index"),
url(r'^new/(?P<step>[0-9]+)/$', NewArticle.as_view(), name="newarticle_continue"),
url(r'^new/', NewArticle.as_view(), name="newarticle"),
url(r'^new/process/(?P<step>[0-9]+)/$', FormManager.as_view(), name='stepprocess')
#url(r'^show/(?P<article>[0-9]+)/$'),
]
And lastly, my views.py file:
#required imports...
class FormManager(View):
def post(self, request, *args, **kwargs):
return HttpResponse(kwargs['step'])
When I hit the submit button, it gives me HTTP 405 error. I can see this error in python console but nothing shows in browser. Just blank white screen.
This was actually to test if view works properly. My final purpose is that I would like to access the post variables and redirect the page. However, HttpResponseRedirect also doesn't work. How can I fix this?
HTTP 405 error means "method not allowed"
In your case you are POSTing... the view looks like it should accept POST requests though.
The problem is your urls.py is wrong, the url you POSTed to is intercepted by the NewArticle view instead, which I guess only accepts GETs.
from django.conf.urls import url
from .views import *
urlpatterns = [
url(r'^$', Index.as_view(), name="index"),
url(r'^new/process/(?P<step>[0-9]+)/$', FormManager.as_view(), name='stepprocess')
url(r'^new/(?P<step>[0-9]+)/$', NewArticle.as_view(), name="newarticle_continue"),
url(r'^new/', NewArticle.as_view(), name="newarticle"),
#url(r'^show/(?P<article>[0-9]+)/$'),
]
Django looks at the urls in the urlconf in the order they are defined and will dispatch your request to the first one that matches.
Above I have modified the order, alternatively you could just add the $ to end of url:
url(r'^new/$', NewArticle.as_view(), name="newarticle"),
this will prevent it matching any new/* url paths.

Categories