<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: tochimclaren</title>
    <description>The latest articles on DEV Community by tochimclaren (@tochimclaren).</description>
    <link>https://dev.to/tochimclaren</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F566868%2F739c69e3-2c76-4496-84d7-c2d7a12da84f.jpg</url>
      <title>DEV Community: tochimclaren</title>
      <link>https://dev.to/tochimclaren</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/tochimclaren"/>
    <language>en</language>
    <item>
      <title>Django ajax form submission with fetch api</title>
      <dc:creator>tochimclaren</dc:creator>
      <pubDate>Sat, 14 Aug 2021 00:14:31 +0000</pubDate>
      <link>https://dev.to/tochimclaren/django-ajax-form-with-fetch-api-lob</link>
      <guid>https://dev.to/tochimclaren/django-ajax-form-with-fetch-api-lob</guid>
      <description>&lt;p&gt;Following my previous post &lt;a href="https://dev.to/tochimclaren/django-infinite-scrolling-with-javascript-fetch-api-and-function-based-view-47fo"&gt;Django infinite scrolling with javascript fetch api and function based view&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I will be covering how to do hassle free django ajax form submission with fetch api and django form.&lt;br&gt;
the code is available over here. &lt;a href="https://github.com/tochimclaren/django-infinite-scroll/tree/ajax-form-submission"&gt;link&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Setting templates.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Moving on from the previous tutorial, add the following code in template directory of the app;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;blog/templates/post/partials/navigation.html&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Create a directory named partials; inside it, paste this bootstrap navbar html component, we going to include this in the base html template which we will create in a minute. We don't want to clutter the base template.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;nav class="navbar navbar-expand-lg navbar-light bg-light"&amp;gt;
  &amp;lt;div class="container-fluid"&amp;gt;
    &amp;lt;a class="navbar-brand" href="/"&amp;gt;Posts&amp;lt;/a&amp;gt;
    &amp;lt;button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"&amp;gt;
      &amp;lt;span class="navbar-toggler-icon"&amp;gt;&amp;lt;/span&amp;gt;
    &amp;lt;/button&amp;gt;
    &amp;lt;div class="collapse navbar-collapse" id="navbarNav"&amp;gt;
      &amp;lt;ul class="navbar-nav"&amp;gt;
        &amp;lt;li class="nav-item"&amp;gt;
          &amp;lt;a class="nav-link" href="{% url 'create' %}"&amp;gt;Create&amp;lt;/a&amp;gt;
        &amp;lt;/li&amp;gt;
      &amp;lt;/ul&amp;gt;
    &amp;lt;/div&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/nav&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;after that create a base.html inside the blog template directory&lt;/p&gt;

&lt;p&gt;&lt;code&gt;blog/templates/post/base.html&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Add the following html template&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{% load static %}
&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;

&amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
    &amp;lt;link rel="stylesheet" href="{% static 'blog/css/bootstrap.min.css' %}"&amp;gt;
    &amp;lt;title&amp;gt;My Blog&amp;lt;/title&amp;gt;
    &amp;lt;style&amp;gt;
    #content {
        margin: 0 auto;
        width: 40vw;
    }
    &amp;lt;/style&amp;gt;
&amp;lt;/head&amp;gt;

&amp;lt;body&amp;gt;
    {% block navigation %}
        {# include the navigatio #}
    {% include 'post/partials/navigation.html' %}
    {% endblock %}
    &amp;lt;div id="notify"&amp;gt;

    &amp;lt;/div&amp;gt;
    {% block content %}
    {% endblock %}

    &amp;lt;script src="{% static 'blog/js/bootstrap.bundle.min.js' %}"&amp;gt;&amp;lt;/script&amp;gt;
    {% block script %}
    {% endblock %}
&amp;lt;/body&amp;gt;

&amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;open &lt;code&gt;blog&lt;/code&gt; and create a new python file &lt;code&gt;forms.py&lt;/code&gt;&lt;br&gt;
&lt;code&gt;blog/forms.py&lt;/code&gt;&lt;br&gt;
inside &lt;code&gt;blog/forms.py&lt;/code&gt; add the below code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django import forms
from .models import Post


class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'content']

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;in &lt;code&gt;views.py&lt;/code&gt; import the PostForm&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from .forms import PostForm
from django.forms import model_to_dict
from django.http import JsonResponse
from django.shortcuts import render
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;add the following code to &lt;code&gt;views.py&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def post_create(request):
    form = PostForm()
    if request.method == "POST":
        form = PostForm(request.POST or None)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.save()
            # converts Post instance to dictionary so JsonResponse can serialize it to Json
            return JsonResponse(
                model_to_dict(instance, fields=['title']), status=201)
        else:
            return JsonResponse(form.errors, safe=False, status=200)

    ctx = {
        'form': form
    }
    return render(request, 'post/post_create.html', ctx)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;in &lt;code&gt;blog/urls.py&lt;/code&gt; add the post_create view function&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.urls import path
from . import views

urlpatterns = [
    path('', views.posts, name="posts"),
    path('create/', views.post_create, name="create") # new
]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;before we create a new template install &lt;code&gt;django-widget-tweaks&lt;/code&gt;&lt;br&gt;
&lt;code&gt;pipenv install django-widget-tweaks&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;widget-tweaks allows you to add html attributes in the templates using it's render template tags &lt;a href="https://pypi.org/project/django-widget-tweaks/"&gt;django-widget-tweaks&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;add it to your &lt;code&gt;INSTALLED_APPS&lt;/code&gt; like this &lt;code&gt;widget_tweaks&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;in &lt;code&gt;blog/templates/post&lt;/code&gt; create new html template &lt;code&gt;post_create.html&lt;/code&gt;&lt;br&gt;
&lt;code&gt;blog/templates/post/post_create.html&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{% extends "post/base.html" %}
{% load static %}
{% load widget_tweaks %}
{% block content %}
    &amp;lt;form action="" method='post' class="mx-auto w-75" id="PostCreateForm"&amp;gt;
        &amp;lt;h1 class="h1 ms-auto"&amp;gt;Create Post&amp;lt;/h1&amp;gt;
        {% csrf_token %}
            {% for field in form %}
                &amp;lt;label for="{{field.id_for_label}}" class="my-2"&amp;gt;{{field.label_tag}}&amp;lt;/label&amp;gt;
                {{ field.errors }}
                {% render_field field class="form-control" %}
            {% endfor %}
        &amp;lt;input type="submit" value="submit" class="btn btn-outline-dark mt-2"&amp;gt;
    &amp;lt;/form&amp;gt;
{% endblock %}

{% block script %}
    &amp;lt;script type="text/javascript" src="{% static 'blog/js/create.js' %}"&amp;gt;&amp;lt;/script&amp;gt;
{% endblock %}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;in your &lt;code&gt;blog/static/blog/js&lt;/code&gt; create a new js file with name &lt;code&gt;create.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;blog/static/blog/js/create.js

const postForm = document.querySelector("#PostCreateForm");


function handleSubmit(postForm) {
    postForm.addEventListener("submit", e =&amp;gt; {
        e.preventDefault();
        formData = new FormData(postForm);
        fetch('/create/', {
                method: 'POST',
                body: formData,
            })
            .then(response =&amp;gt; response.json())
            .then(data =&amp;gt; {
                postForm.reset();
                document.querySelector("#notify").innerHTML = `&amp;lt;div class="alert alert-info alert-dismissible fade show" role="alert"&amp;gt;
                                                                  &amp;lt;strong&amp;gt;Success!&amp;lt;/strong&amp;gt; ${data.title} &amp;lt;strong&amp;gt;saved&amp;lt;/strong&amp;gt;.
                                                                  &amp;lt;button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"&amp;gt;&amp;lt;/button&amp;gt;
                                                                &amp;lt;/div&amp;gt; `
            })
            .catch((error) =&amp;gt; {
                console.error('Error:', error);
            });
    })
}

handleSubmit(postForm)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And we are done! upcoming tutorial we will add image field in Post model and do some validation with ajax... stay tuned.&lt;/p&gt;

</description>
      <category>django</category>
      <category>fetch</category>
      <category>ajax</category>
      <category>widgettweaks</category>
    </item>
    <item>
      <title>Django Infinite scrolling with javascript fetch api and function based view.</title>
      <dc:creator>tochimclaren</dc:creator>
      <pubDate>Thu, 12 Aug 2021 23:35:43 +0000</pubDate>
      <link>https://dev.to/tochimclaren/django-infinite-scrolling-with-javascript-fetch-api-and-function-based-view-47fo</link>
      <guid>https://dev.to/tochimclaren/django-infinite-scrolling-with-javascript-fetch-api-and-function-based-view-47fo</guid>
      <description>&lt;p&gt;Hello, I will take you straight through the process of adding inifinte pagination in your django application like it's abc complete code is down below&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note: this is for absolute beginner&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/tochimclaren/django-infinite-scroll.git"&gt;django-infinite-scroll&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;First thing first, we create our django project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir django-infinite-scroll
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd django-infinite-scroll
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pipenv shell #this initializes with Pipfile and creates the environment
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We install our django application&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pipenv install django
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We create a new django project&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;django-admin startproject core .
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We create our app blog and add it to &lt;code&gt;INSTALLED_APPS&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py startapp blog
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # our blog app
    'blog.apps.BlogConfig',
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the development server and make sure everything is working properly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py runserver
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Migrate the database and createsuperuser in my case the credentials were username: &lt;code&gt;admin&lt;/code&gt; password: &lt;code&gt;admin&lt;/code&gt; run the server and let the fun begin!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py createsuperuser
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py runserver
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Creating a simple model for a blog to hold&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# models.py
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=255)
    content = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    published = models.BooleanField(default=False)

    def __str__(self):
        return self.title
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# views.py
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render
from .models import Post


def posts(request):
    # it's not a bug if it's intentional ;)
    post_list = Post.objects.filter(published=False)
    # we get page 1 returns 10 post objects
    paginator = Paginator(post_list, 10)

    # page_number is initialized to `1` see main.js
    page_number = request.GET.get('page')

    # we are applying page number which defaults to `1`
    page_obj = paginator.get_page(page_number)

    if page_number:
        # We are checking if `page_number` &amp;lt; or == 
        paginator.num_pages total amount of pages returned by the `Paginator` this only runs if the above conditions are met
        if int(page_number) &amp;lt;= paginator.num_pages:

            obj_list = paginator.get_page(page_number)

            obj_list = obj_list.object_list.values()

            return JsonResponse(list(obj_list), status=200, safe=False)

    ctx = {'page_obj': page_obj}
    return render(request, 'post/posts.html', ctx)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add your app url to project url config&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#core/urls.py

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls'))
]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Define your app urls.py&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# blog/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.posts, name="posts")
]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We create a simple example template&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# template
# 'blog/templates/post/posts.html'
{% load static %}
&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;

&amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
    &amp;lt;title&amp;gt;Document&amp;lt;/title&amp;gt;
    &amp;lt;style&amp;gt;
        #content{
            margin: 0 auto;
            width: 40vw;
        }
    &amp;lt;/style&amp;gt;
&amp;lt;/head&amp;gt;

&amp;lt;body&amp;gt;
    &amp;lt;div id="content"&amp;gt;
        {% for post in page_obj %}
            &amp;lt;div&amp;gt;
                &amp;lt;h1&amp;gt;{{post.title}}&amp;lt;/h1&amp;gt;
                &amp;lt;p&amp;gt;{{post.content}}&amp;lt;/p&amp;gt;
            &amp;lt;/div&amp;gt;
        {% endfor %}
    &amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;script type="text/javascript" src="{% static 'blog/js/main.js' %}"&amp;gt;&amp;lt;/script&amp;gt;

&amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On the js side of things, we are listening to scroll event, when we scroll to the bottom of the page, we trigger a function that calls our view which in turn returns a Json objects that we can inject to our template.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# main.js
# 'blog/static/blog/js/main.js'

content = document.querySelector("#content");
let page = 1

window.onscroll = function() {
    url = `/?page=${page}`
    if (window.innerHeight + window.pageYOffset &amp;gt;= document.body.offsetHeight) {
        fetch(url).then(res =&amp;gt; {
            if (res.ok) {
                return res.json();
            }
        }).then(data =&amp;gt; {
            console.dir(data)
            page += 1
            content.innerHTML += data.map(
                obj=&amp;gt;`&amp;lt;div&amp;gt;
                &amp;lt;h1&amp;gt;${obj.title}&amp;lt;/h1&amp;gt; 
                &amp;lt;p&amp;gt;${obj.content}&amp;lt;/p&amp;gt; 
                &amp;lt;/div&amp;gt;`
                ).join("\n")
        }).catch(err =&amp;gt; {

        })
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I hope this helps shed some weight on your web application, because things like these are not worth intsalling an external library (waypointjs i'm looking at you), please help your app shed some weight! Happy coding!&lt;/p&gt;

</description>
      <category>django</category>
      <category>ajax</category>
      <category>fetch</category>
      <category>pagination</category>
    </item>
  </channel>
</rss>
