How to insert data to SQLite in Django - python

I am new to Django and I am following this website https://simpleisbetterthancomplex.com/tutorial/2018/02/03/how-to-use-restful-apis-with-django.html#passing-parameters-to-an-api-github-public-api
views.py
from django.shortcuts import render
import requests
def github(request):
user = {}
if 'username' in request.GET:
username = request.GET['username']
url = 'https://api.github.com/users/%s' % username
response = requests.get(url)
user = response.json()
return render(request, 'core/github.html', {'user': user})
core/github.html
{% extends 'base.html' %}
{% block content %}
<h2>GitHub API</h2>
<form method="get">
<input type="text" name="username">
<button type="submit">search on github</button>
</form>
{% if user %}
<p><strong>{{ user.name }}</strong> has <strong>{{ user.public_repos }}</strong> public repositories.</p>
{% endif %}
{% endblock %}
After passing parameters to an API and retrieve some location data, I would like to store the data to my SQLite in Django. I have created the model but I have no idea how to insert the data because I can't find examples under similar situations. And I am not sure where I should modify. Any hint or where I should look for? Many thanks.

I don't know yours models... let's asume:
models.py
from django.db import models
class Uuser(models.Model):
name = models.CharField(max_length=45,)
public_repos = models.CharField(max_length=45,)
then in your view.py
from django.shortcuts import render
import requests
from models import Uuser
def github(request):
user = {}
if 'username' in request.GET:
username = request.GET['username']
url = 'https://api.github.com/users/%s' % username
response = requests.get(url)
user = response.json()
usr = Uuser(name=user['name'], public_repos=user['public_repos']) # create new model instance
usr.save() #seve to db
return render(request, 'core/github.html', {'user': user})
I'm not checking if that exact name exist in db so there will be new record on the same name each time you post it to view.

Related

Reverse for 'all_clients' with keyword arguments '{'client_id': 3}' not found. 1 pattern(s) tried: ['clients/all_clients/$']

I am new to Django and I am having trouble implementing the edit template to my project. I am encountering the following error:
Reverse for 'all_clients' with keyword arguments '{'client_id': 3}' not found. 1 pattern(s) tried: ['clients/all_clients/$']
I have looked on the site for similar occurrences such as Reverse for 'plan_edit' with keyword arguments
but I haven't been able to pin point the issue. I believe the issue arises when I add a hyperlink to my all_clients.html template. Also, the template pages for /clients/edit_client/?/ will load, however after submission using the save changes button the NoReserse Match error resurfaces as it attempts to load the clients/all_clients page.
See code below:
models.py
from django.db import models
# Create your models here.
class Client(models.Model):
#A client is composed of the company general info
text = models.CharField('Company Name',default = 'Company Name', max_length = 200)
phone_num = models.CharField('Phone Number', default = '000-000-000', max_length = 12)
ceo_name = models.CharField ('CEO', max_length = 50)
num_employees = models.IntegerField('Number of Employees', default = 0)
maintenance_schedule = models.CharField('maintenance schedule', max_length = 100)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
"""Return a string representation of the model."""
return self.text
urls.py
"""Defines URL patterns for clients."""
from django.urls import path from django.conf.urls import url
from .import views
app_name = 'clients' urlpatterns = [
#Company Page
path('index/', views.index, name = 'index'),
#Page for listing all clients
path('all_clients/', views.all_clients, name = 'all_clients'),
#Page for adding a new client
path('all_clients/<int:client_id>/', views.add_client, name = 'add_client'),
#Page for adding a new client office using a form
path('new_office/', views.new_office, name = 'new_office'),
#Page for a company to edit their entry.
path('edit_clients/<int:client_id>/', views.edit_client, name = 'edit_client'),
]
view.py
from django.shortcuts import render, redirect
from .models import Client, Location, Lease, Soft_Service, Hard_Service, Safety_Service
from .forms import ClientForm
# Create your views here.
def add_client(request, client_id):
"""Comapany page for updating facilities info"""
client = Client.objects.get(id = client_id)
context = {'client':client}
return render(request, 'clients/add_client.html', context)
def all_clients(request):
'''Shows list of all clients'''
all_clients = Client.objects.order_by ('date_added')
context = {'all_clients':all_clients}
return render(request, 'clients/all_clients.html', context)
def index(request):
"""Test Page"""
return render(request, 'clients/index.html')
def edit_client(request, client_id):
"""Edit an existing Entry."""
client = Client.objects.get(id=client_id)
if request.method != 'POST':
#Inital request; pre-fill form with the current company info.
form = ClientForm(instance=client)
else:
# Post data submitted; process data.
form = ClientForm(instance=client, data=request.POST)
if form.is_valid():
form.save()
return redirect('clients:all_clients' , client_id=client.id)
context = {'form': form, 'client': client}
return render(request, 'clients/edit_client.html', context)
edit_client.html
{% extends "app/layout.html" %}
{% block content %} {% load staticfiles %} <p>Company: {{ client }}</p>
<h4>See Our Clients</h4>
<<form action="{% url 'clients:edit_client<client_id>' client.id %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button name="submit">Save changes</button> </form>
{% endblock %}
all_clients.html
{% extends "app/layout.html" %}
{% block content %}
{% load staticfiles %}
<div class="d-flex" style="height:75px"></div>
<div class="btn bg-white text-lg-left" style="width:425px">
<h4>See Our Clients</h4>
<ul>
{% for add_client in all_clients %}
<li>
{{ add_client }}
</li>
{%empty %}
<li> No clients have been added yet. </li>
{% endfor %}
</ul>
<a class="btn btn-secondary" href=" {% url 'clients:new_office' %}">Add a new location</a>
<a class="btn btn-secondary" href=" {% url 'clients:edit_client' client.id %}">Add a new location</a>
</div>
{% endblock content %}
First thing i think you should try is modifying the URL to the add_clients page, aside from the id you are passing is identical to all_clients, and "django may get confused":
#Page for listing all clients
path('all_clients/', views.all_clients, name = 'all_clients'),
#Page for adding a new client
path('add_clients/<int:client_id>/', views.add_client, name = 'add_client'),
instead of:
#Page for listing all clients
path('all_clients/', views.all_clients, name = 'all_clients'),
#Page for adding a new client
path('all_clients/<int:client_id>/', views.add_client, name = 'add_client'),

Getting Data From the Request Object using Django webframework for MySQL

Hello experts,
I am new in django and trying to learn how to build django web-framework for MySQL database.I can post my query (search term) and get desired results. But I am trying to modify my project so user can submit query in submission page and see their query parameter in URL when it is executed.
Something like this:
submission page: http://localhost:8000/
and after execution page will be like this:http://localhost:8000/xtrack/?searchid=XXXX
But still now I couldn't figure out how to do it in a right way after spending few days.
forms.py
from django import forms
from models import Query
class SQLForm(forms.ModelForm):
xtrackid=forms.CharField(max_length=100)
def checkxID(self):
xtrackid=self.cleaned_data.get("xtrackid")
return xtrackid
class QueryForm(forms.ModelForm):
class Meta:
model=Query
fields=["xtrackid"]
views.py
from django.shortcuts import render
from django.http import HttpResponse
from forms import SQLForm, QueryForm
import sys
def search_form(request):
return render(request, 'index.html')
def search(request):
form = QueryForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
xtrackid = form.cleaned_data.get("xtrackid")
xtrackid =xtrackid.strip()
conn = MySQLdb.connect (host = "localhost", user = "root", passwd = "XXXX", db = "XXXtracker")
cursor = conn.cursor ()
cursor.execute ("SELECT xInfo.xtideID, xIDunID.AccessionNumber FROM xInfo, xIDunID WHERE xInfo.xtideID = xIDunID.xtideID AND xIDunID.xtideID LIKE '%" + xtrackid +"%'")
row = cursor.fetchone ()
listrow= list(row)
contextres={}
if cursor.rowcount==0:
contexterror = {
'outputerror': xtrackid
}
return render(request, 'errorform.html', contexterror)
else:
if contextres.has_key(str(listrow[0])):
contextres[str(listrow[0])].append(listrow[1])
else:
contextres[str(listrow[0])]= [listrow[1]]
resulstdict = {'contextresultinfo': contextres}
return render(request, 'resultform.html', {'xinfo': resulstdict, 'query': xtrackid})
conn.close()
else:
return HttpResponse('Please submit a valid search term.')
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from myapp import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^xtrack/$', views.search_form),
url(r'^resultform/$', views.search),
url(r'^errorform/$', views.search)
]
and my templates are like:
index.html
<html>
<h1> Welcome to xTrack </h1>
<head>
<title>Search</title>
</head>
<body>
<form action="/xtrack/" method="get">
<input type="text" name="xtrackid">
<input type="submit" value="Search">
</form>
</body>
</html>
resultform.html
Results
{% if contextresultinfo %}
<table border="1" style="width:100%">
<tr>
<td>xtide tracker ID<br> </td>
<td>Accession number<br></td>
</tr>
{% for key, values in contextresultinfo.items %}
<tr>
{% for items in values %}
<tr>
<td>{{key}}</td>
{% for data in items %}
<td>{{data}}</td>
{% endfor %}
</tr>
{% endfor %}
</tr>
{% endfor %}
</table>
{% else %}
<p>No xtrack matched your search criteria.</p>
{% endif %}
</body>
Can you please give some idea where do I need to change code in my project.
Thanks
in you view, you're getting the submission data through:
form = QueryForm(request.POST or None)
but in you html file, you define your form method as:
<form action="/peptrack/" method="get">
Thus request.POST would't get any data.

Django - importing form into template outside app

I have an app with name account which contain all the models, views, and forms to be used in registering and signing in users.
I have a template that is located outside the app folder that suppose to contain all the forms in account app.
I am having problem trying to get the forms showing in the template.
Can someone help me?
Here are some snippet of codes:
accounts/forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
# Safe from injection, etc.
class UserRegistrationForm(UserCreationForm):
email = forms.EmailField(required = True)
first_name = forms.CharField(max_length=30, required=True)
last_name = forms.CharField(max_length=30, required=True)
class Meta:
model = User
fields = ('username','email','password1', 'password2','first_name','last_name')
def save(self, commit=True):
user = super(UserRegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
if commit:
user.save()
return user
accounts/view.py
from forms import UserRegistrationForm
def register_user(request):
if request.POST:
form = UserRegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
else:
form = UserRegistrationForm()
args = {}
# prevent forgery
args.update(csrf(request))
# empty form
args['form'] = form
return render_to_response('signup.html', args)
def register_success(request):
return render_to_response('signup_success.html')
and finally the template, which is not in account folder. It's in the same folder as settings.py
signup.html
{% extends "base.html" %}
{% block content %}
<form action="" method="post"> {% csrf_token %}
<ul>
{{accounts.form.as_ul}}
</ul>
<input type="submit" name="submit" value="Register">
</form>
{% endblock %}
UPDATE
Upon obtaining permission to move the template from the project manager, I moved it to accounts/template, and changed the render to response address.
I have new problem of form not submitting now.
OMG what's going on??
The template should not be in the same directory as settings.py.
It should be in a directory within the accounts app: accounts/templates/signup/html.
If you've configured your Django project correctly then Django should pickup the template after restarting the web server.
as I see you are passing form variable to template,
but you are trying to use accounts.form.
Hope this helps.
Ok the problem lies on my signup.html file. It should have script for onclick and the form should have an id.
{% extends "base.html" %}
{% block content %}
<form action="" method="post" id="form"> {% csrf_token %}
<ul>
{{accounts.form.as_ul}}
</ul>
<input type="submit" name="submit" value="Register" onclick="submit()">
</form>
<script>
function submit() {document.forms["form"].submit();}
</script>
{% endblock %}

Django form to query database (models)

So I want to create a super basic form with a single input field which will be used to query my database.
My model (models.py) is as follows:
from django.db import models
class Book(models.Model):
uid = models.IntegerField(primary_key=True)
title = models.CharField(max_length=30)
class Meta:
db_table = u'books'
forms.py:
from django import forms
from myapp.models import Book
class EnterIDForm(forms.form):
book_id = forms.CharField()
# add a custom clean function to validate that the user input
# is a valid book ID
def clean_book_id(self):
try:
book_id = int(self.cleaned_data["book_id"])
except:
book_id = None
if book_id and Book.objects.filter(uid=book_id).count():
return book_id
else:
raise forms.ValidationError("Please enter a valid book ID number.")
views.py:
from django.shortcuts import render_to_response
from myapp.models import Book
def form_view(request):
if request.method == "POST":
# the user has submitted the form, see if we have a book
book_id_form = EnterIDForm(request.POST) # instantiate our form class with the user data
if book_id_form.is_valid():
# if our form is valid, then we have a book_id that works:
the_book = Book.objects.get(uid=book_id_form.cleaned_data["book_id"])
return render_to_response("book_template.html", { "the_book": the_book }, context_instance=RequestContext(request))
# if the form wasn't valid, it will fall through to the other return statement.
else:
# If the user didn't submit a form, instantiate a blank one.
book_id_form = EnterIDForm()
return render_to_response("form_template.html", { "book_id_form": book_id_form }, context_instance=RequestContext(request))
I want the input field to collect the "uid" from the user and display the all of the data from the Book model instance where uid is some book in the database.
I have an understanding of how the form is tied in with the view, and later templates, but I just cannot seem to get it to work.
I've endlessly searched the Django site and many other resources for an example I can learn from, but nothing.
Anyone mind helping me out?
Thanks.
You can do a simple search here. You do not need any POST calls or form creation. However, if you want to create a form this should still point you in the correct direction.
Try something like this:
search.html:
<form method="get" action="/search/">
Search Notecards:<input type="text" name="q" id="id_q" value="{{ query }}"/>
<input type="submit" value="Search" />
</form>
views.py:
from myapp.models import Book
from django.template import RequestContext
from django.shortcuts import render_to_response
def search(request):
query = request.GET.get('q')
try:
query = int(query)
except ValueError:
query = None
results = None
if query:
results = Book.objects.get(uid=query)
context = RequestContext(request)
return render_to_response('results.html', {"results": results,}, context_instance=context)
results.html:
{% if results %}
{% for result in results %}
{{ result.uid }}
{{ result.xxxx }}
{{ result.xxxx }}
{% endfor %}
{% else %}
<h3 class='error'>Please enter a valid UID</h3>
<form method="get" action="/search/">
Search Notecards:<input type="text" name="q" id="id_q" value="{{ query }}"/>
<input type="submit" value="Search" />
</form>
{% endif %}

Multiple text inputs in django form via Google App Engine

Goal: to create a question where a user creates a poll question that is "mad-libs" style (i.e. "Would you fool around with _(text)__ if she wasnt dating _(text)_?").
Code: This file creates a django form corresponding to an appengine entity.
from django import newforms as forms
import models
from google.appengine.ext.db import djangoforms
class PollForm(djangoforms.ModelForm):
class Meta:
model = models.Poll
This is an excerpt from the models.py file
from google.appengine.ext import db
from django import newforms as forms
class Poll(db.Model):
question = db.StringProperty()
created_on = db.DateTimeProperty(auto_now_add = 1)
created_by = db.UserProperty()
def __str__(self):
return '%s' %self.question
def get_absolute_url(self):
return '/poll/%s/' % self.key()
here is the html for this section
<form action="." method="post">
{{pollform.as_p}}
{% for form in choiceforms %}
{{form.as_p}}
{% endfor %}
<input type="submit" name="createpoll" value="createpoll" />
</form>
Is there a fairly straightforward way to create a question like this with some pre-coded text and some input text? Can I harcode it in the HTML?
Any direction is greatly appreciated!
I still don't totally understand your question. If you post your full source and an example of the result you are trying to get, then you will get a better response.
Here's an example of constructing a form for someone to answer the question. I hard coded the question, but you could easily retrieve that dynamically.
class Answer(models.Model):
answer1 = models.CharField(max_length=100)
answer2 = models.CharField(max_length=100)
class AnswerForm(forms.ModelForm):
class Meta:
model = Answer
def test(request):
if request.method == 'GET':
form = AnswerForm()
question_template = 'Would you fool around with %s if she wasn\'t dating %s?'
html = question_template % (form['answer1'], form['answer2'])
params = {'form': form,
'html': html}
return render_to_response('test.html',
params,
context_instance=RequestContext(request))
Template:
<form method="post" action="">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{{ html|safe }}
<input type="submit" value="Save"/>
</form>

Categories